我有一个文件夹中的树tiew,我想在单击一个文件时打开该文件
一切正常,但当我单击文件时,它不会向我发送正确的路径
import os
import platform
import subprocess
import tkinter as tk
import tkinter.ttk as ttk
class App(tk.Frame):
def openfolderfile(self,filename2open):
if platform.system() == "Windows":
os.startfile(filename2open)
elif platform.system() == "Darwin":
subprocess.Popen(["open", filename2open])
else:
subprocess.Popen(["xdg-open", filename2open])
def select(self):
for i in self.tree.selection():
print("".join([str(self.tree.item(i)['text'])]))
print(os.path.abspath("".join([str(self.tree.item(i)['text'])])))
# self.openfolderfile()
def __init__(self, master, path):
tk.Frame.__init__(self, master)
self.tree = ttk.Treeview(self)
ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
self.tree.heading('#0', text=path, anchor='w')
abspath = os.path.abspath(path)
root_node = self.tree.insert('', 'end', text=abspath, open=True)
self.process_directory(root_node, abspath)
self.tree.grid(row=0, column=0,ipady=200,ipadx=200)
ysb.grid(row=0, column=1, sticky='ns')
xsb.grid(row=1, column=0, sticky='ew')
self.grid()
self.tree.bind("<Double-Button>", lambda e: self.select())
def process_directory(self, parent, path):
for p in os.listdir(path):
abspath = os.path.join(path, p)
isdir = os.path.isdir(abspath)
oid = self.tree.insert(parent, 'end', text=p, open=False)
if isdir:
self.process_directory(oid, abspath)
root = tk.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
root.title("Success ")
app = App(root, path="Reports/")
app.mainloop()
这是它打印的内容:
/Users/myuser/PycharmProjects/OCP/Notas.txt
真正的路径是:
/Users/myuser/PycharmProjects/OCP/Reports/rep1/Notas.txt
为什么会出现这种情况
对于
select
函数,可以这样尝试:实现中的问题是,您使用了
os.path.abspath
,这将为您提供当前工作目录,而不是所选文件所在的目录相关问题 更多 >
编程相关推荐