如何像 python tkinter 中的 vs 代码一样在我们的 gui 文件中打开文件夹?

How to open folder in our gui file like vs code in python tkinter?

我正在创建一个函数来获取我的 gui 中的所有文件,就像 vs 代码一样。我尝试了很多次我创建了一个函数,通过它我可以在我的 gui 中获取文件夹文件但是我无法从我的 gui 打开文件而且我也无法根据包含的扩展名将图像放在它们的名称之前

错误:-

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "d:\coding notes\pytho project\project1.py", line 24, in <lambda>
    list_box.bind("<<ListboxSelect>>",lambda event=None:Open(file))
  File "d:\coding notes\pytho project\project1.py", line 6, in Open
    with open(value,"r") as f:
PermissionError: [Errno 13] Permission denied: 'D:/coding notes/pytho project'

这是我的代码

import os
from tkinter import*
from tkinter.filedialog import askdirectory
def Open(value):
    editor.delete(1.0,END)
    with open(value,"r") as f:
        editor.insert(1.0,f.read())
def Open_folder():
    global file 
    file = askdirectory()
    if file == "":
        file = None
    else:
        for i in os.listdir(file):
            list_box.insert(END,i)
root = Tk()
file = ""
root.geometry("1550x850+0+0")
editor = Text(root,font="Consolas 15",bg="gray19",fg="white",insertbackground="white")
editor.place(x=400,y=0,relwidth=True,height=850)
Button(root,text="Open folder",font="Consolas 10",relief=GROOVE,bg="gray19",fg="white",command=Open_folder).place(x=0,y=0)
list_box = Listbox(root,font="Consolas 15",bg="gray19",fg="white",selectbackground="gray29")
list_box.place(x=0,y=20,width=400,height=850)
list_box.bind("<<ListboxSelect>>",lambda event=None:Open(file))
root.mainloop()

您打开选定文件夹,而不是Open()内列表框中的选定文件。您需要从列表框中获取所选文件并加入所选文件夹以获取完整文件路径:

def Open(value):
    # get the selected filename from listbox
    file = list_box.get(list_box.curselection())
    # get the absolute path of the selected filename
    filepath = os.path.join(value, file)
    
    editor.delete(1.0, END)
    with open(filepath, "r") as f:
        editor.insert(1.0, f.read())