python - 如何将我在 tkinter 树中单击的目录的路径传递给“打开文件”函数以显示它
问题描述
此代码显示目录和文件,但是如果我尝试通过按“打开”按钮打开文件,我希望它打开突出显示的路径。我的意思是,当我运行这段代码时,我会得到一个完美的目录树,其中包含我桌面上的目录,如果我展开一个目录,它的文件列表就会完美列出。现在我想点击一个文件,比如一个 .txt 文件,然后我想点击 OPEN 按钮,我希望它真正打开这个文件!
这是代码:
import os
import glob
import tkinter
from tkinter import ttk, filedialog
def openfile():
filedialog.askopenfilename()####I WANT IT TO OPEN WHATEVER I
###HIGHLIGHT LATER IN THE TREE AFTER RUNNING
def populate_tree(tree, node):
if tree.set(node, "type") != 'directory':
return
path = tree.set(node, "fullpath")
tree.delete(*tree.get_children(node))
parent = tree.parent(node)
special_dirs = [] if parent else glob.glob('.') + glob.glob('..')
for p in special_dirs + os.listdir(path):
ptype = None
p = os.path.join(path, p).replace('\\', '/')
if os.path.isdir(p): ptype = "directory"
elif os.path.isfile(p): ptype = "file"
fname = os.path.split(p)[1]
id = tree.insert(node, "end", text=fname, values=[p, ptype])
if ptype == 'directory':
if fname not in ('.', '..'):
tree.insert(id, 0, text="dummy")
tree.item(id, text=fname)
elif ptype == 'file':
size = os.stat(p).st_size
tree.set(id, "size", "%d bytes" % size)
# button = ttk.Button(root, text="Open", command=openfile) # <------
# button.grid(column=1, row=1)
def populate_roots(tree):
dir = os.path.abspath('.').replace('\\', '/')
node = tree.insert('', 'end', text=dir, values=[dir, "directory"])
populate_tree(tree, node)
def update_tree(event):
tree = event.widget
populate_tree(tree, tree.focus())
def change_dir(event):
tree = event.widget
node = tree.focus()
if tree.parent(node):
path = os.path.abspath(tree.set(node, "fullpath"))
if os.path.isdir(path):
os.chdir(path)
tree.delete(tree.get_children(''))
populate_roots(tree)
def autoscroll(sbar, first, last):
"""Hide and show scrollbar as needed."""
first, last = float(first), float(last)
if first <= 0 and last >= 1:
sbar.grid_remove()
else:
sbar.grid()
sbar.set(first, last)
root = tkinter.Tk()
vsb = ttk.Scrollbar(orient="vertical")
hsb = ttk.Scrollbar(orient="horizontal")
tree = ttk.Treeview(columns=("fullpath", "type", "size"),
displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
xscrollcommand=lambda f, l:autoscroll(hsb, f, l))
vsb['command'] = tree.yview
hsb['command'] = tree.xview
tree.heading("#0", text="Directory Structure", anchor='w')
tree.heading("size", text="File Size", anchor='w')
tree.column("size", stretch=0, width=100)
populate_roots(tree)
tree.bind('<<TreeviewOpen>>', update_tree)
tree.bind('<Double-Button-1>', change_dir)
#Arrange the tree and its scrollbars in the toplevel: side="left", fill="both", expand=True
tree.grid(column=0, row=0, sticky='nswe')
vsb.grid(column=1, row=0, sticky='ns')
hsb.grid(column=0, row=1, sticky='ew')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
tree.grid(column=0, row=0, sticky='nswe')
button = ttk.Button(root, text="Open", command=openfile) # <------
button.grid(column=1, row=1)
root.mainloop()
我希望它打开我在浏览模式下突出显示的文件或路径。谢谢
解决方案
只需导入lib的popen
方法。os
它打开带有路径的文件。为了获取所选树视图的路径,您需要获取树视图的焦点,然后获取焦点的项目,它是所选项目的信息字典。要获取路径,您需要获取值并选择第一个(路径)。然后你使用popen
打开文件。
from os import popen
def openfile():
curItem = tree.focus()
popen(tree.item(curItem)['values'][0])
推荐阅读
- python - 测试python类是否为str、list等
- flutter - 单个子滚动视图不适用于底部溢出像素
- javascript - Javascript 我的函数(写在下面)是未定义的(当试图画一些东西时)
- javascript - 如何使具有特定尺寸要求的引导模态居中
- python - 执行子文件夹内的代码
- terraform - 如何动态地将参数传递给 terraform 模块并根据条件运行模块
- javascript - 使用 Javascript 阻止 target="_blank" 弹出窗口
- c - 如何在 Debian 10 中使用 QEMU 进行调试
- swift - 列表重新排序后 SwiftUI 关闭
- java - CucumberOptions 不运行功能