2017-01-19 51 views
0

我試圖編寫一個代碼,在文件資源管理器中用單選按鈕打開一個文件夾。我發現了一個例子,但我被困在下面的錯誤: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新手,希望得到任何幫助。

回答

1

你有兩個問題,通過什麼。首先,您直接從單選按鈕調用self.askopenfilename,而不給它必要的參數。這正是錯誤信息告訴你的。

其次,您已經定義了一個名爲filedialog的類,它需要一個參數:root該類覆蓋了filedialog模塊。因此,從askopenfilename內,您正在遞歸調用askopenfilename,並且由於self.file_opt是空字典,因此未能提供所需的參數。

+0

感謝您的快速反應。我有點明白你在說什麼,但我不知道如何在我的代碼中實現它。你可以添加一個例子嗎? – Cucumber12

+0

@ Cucumber12:只從'def askopenfilename(self,root)'中移除'root',因爲你永遠不會使用它。接下來,將'filedialog'重命名爲其他內容。 –

+0

我實際上在'askopenfilename(self)'中添加了根目錄來擺脫錯誤:'TypeError:__init __()缺少1位置參數:'root''我開始認爲我的代碼不好:) – Cucumber12

0

askopenfilename(self, root)功能需要root參數,但你沒有在你的

tkinter.Radiobutton(self, text = "Browse", 
       command = self.askopenfilename 
       ).grid(row=2, column =0, columnspan = 2, sticky =W) 
相關問題