如何将我在tkinter树中单击的目录的路径传递给“open file”函数,以便显示I

2024-03-29 07:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码显示目录和文件,但是如果我试图通过按“打开”按钮打开文件,我希望它打开高亮显示的路径。我的意思是当我运行这段代码时,我得到了一个完美的目录树,如果我展开一个目录,它的文件列表就是完美的。现在我想点击一个文件,比如说一个.txt文件,然后我想点击打开按钮,我想它实际打开这个文件!你知道吗

代码如下:

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()
我希望它打开我在浏览模式下突出显示的文件或路径。谢谢

Tags: 文件pathtextnodetreesizeifos
1条回答
网友
1楼 · 发布于 2024-03-29 07:29:54

只需导入popen库的os方法。它打开带有路径的文件。为了获得所选树视图的路径,您需要获得树视图的焦点,然后获得焦点的项,这是所选项的信息字典。要获取路径,需要获取值并选择第一个值(路径)。然后使用popen打开文件。你知道吗

from os import popen    
def openfile():
    curItem = tree.focus()
    popen(tree.item(curItem)['values'][0])

相关问题 更多 >