我試圖編寫一個代碼,在文件資源管理器中用單選按鈕打開一個文件夾。我發現了一個例子,但我被困在下面的錯誤:TypeError:askopenfilename()缺少1所需的位置參數:'root'In []:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Anaconda3\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
TypeError: askopenfilename() missing 1 required positional argument: 'root'
這是我的代碼:
from tkinter import*
from tkinter import filedialog
import tkinter.constants
class filedialog(tkinter.Frame):
def __init__(self, root):
tkinter.Frame.__init__(self, root)
Radiobutton_opt = {'fill': tkinter.constants.BOTH, 'padx': 5, 'pady': 5}
tkinter.Radiobutton(self, text = "Browse",
command = self.askopenfilename
).grid(row=2, column =0, columnspan = 2, sticky =W)
self.file_opt = options = {}
self.dir_opt = options = {}
options['initialdir'] = 'C:\\Users\\Documents\\Python Scripts'
def askopenfilename(self, root):
filename = filedialog().askopenfilename(**self.file_opt)
if filename:
return open(filename, 'r')
def askdirectory(self, root):
return filedialog.askdirectory(**self.dir_opt)
if __name__=='__main__':
root = Tk()
filedialog(root).grid()
root.mainloop()
按鈕出現了,但是當我按下它,我得到的錯誤。我是python新手,希望得到任何幫助。
感謝您的快速反應。我有點明白你在說什麼,但我不知道如何在我的代碼中實現它。你可以添加一個例子嗎? – Cucumber12
@ Cucumber12:只從'def askopenfilename(self,root)'中移除'root',因爲你永遠不會使用它。接下來,將'filedialog'重命名爲其他內容。 –
我實際上在'askopenfilename(self)'中添加了根目錄來擺脫錯誤:'TypeError:__init __()缺少1位置參數:'root''我開始認爲我的代碼不好:) – Cucumber12