我正在創建一個函式來獲取我的 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()
uj5u.com熱心網友回復:
您在串列框中打開選定的檔案夾而不是選定的檔案。您需要從串列框中獲取所選檔案并加入所選檔案夾以獲取完整檔案路徑: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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441033.html
上一篇:如何更改QR碼的顏色?
