Как я могу передать функции "открыть файл" путь к каталогу, на который я нажимаю в дереве tkinter, чтобы отобразить его - PullRequest
0 голосов
/ 14 февраля 2019

Этот код отображает каталоги и файлы, однако, если я пытаюсь открыть файл нажатием кнопки «открыть», я хочу, чтобы он открыл выделенный путь.Я имею в виду, что когда я запускаю этот код, я получаю идеальное дерево того, что у меня есть на рабочем столе в качестве каталогов, если я разверну один каталог, список его файлов будет полностью указан.СЕЙЧАС я хочу щелкнуть файл, скажем, файл .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()
Я хочу, чтобы он открыл файл или путь, который я выделяю в режиме просмотра.Спасибо

1 Ответ

0 голосов
/ 15 февраля 2019

Просто импортируйте метод popen из библиотеки os.Он открывает файл с путем.Чтобы получить путь к выбранному древовидному представлению, вам нужно получить фокус древовидного представления, а затем получить элемент фокуса, представляющий собой словарь информации о выбранном элементе.чтобы получить путь, вам нужно получить значения и выбрать первое (путь).Затем вы используете popen, чтобы открыть файл.

from os import popen    
def openfile():
    curItem = tree.focus()
    popen(tree.item(curItem)['values'][0])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...