![](/img/trans.png)
[英]Trying to get full file path from the currently selected file in QtreeView
[英]Get full path of selected file
我有一個文件夾中的樹狀結構,我想在單擊一個文件時打開該文件。
一切正常,但是當我單擊該文件時,它不會向我發送正確的路徑
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
功能嘗試它:
def select(self):
for i in self.tree.selection():
print("".join([str(self.tree.item(i)['text'])]))
full_path = ''
current_iid = i
while True:
# get next parent directory
parent_iid = self.tree.parent(current_iid)
attach_path = self.tree.item(parent_iid)['text']
# change the parent identifier to be the current now
current_iid = parent_iid
# break if the path is empty and thus no more parents are available
if attach_path == '':
break
# add found path to the full path
full_path = os.path.join(attach_path, full_path)
print(os.path.join(full_path, ("".join([str(self.tree.item(i)['text'])]))))
您實現的問題是,您使用了os.path.abspath
,這為您提供了當前工作目錄,而不是所選文件所在的目錄。
import os
file = 'myfile.txt'
file = 'directory/to/myfile.txt'
path = os.path.abspath(file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.