Cucumber12
Cucumber12

Reputation: 15

TypeError: askopenfilename() missing 1 required positional argument: 'root' In [ ]:

I'm trying to write a code that opens a folder in the file explorer with a radiobutton. I found an example, but I got stuck on the following error:

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'

This is my code:

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()

The button does appear, but when I press it, I get the error. I'm new to python and would appreciate any help.

Upvotes: 1

Views: 767

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386155

You have two problems. First, you are directly calling self.askopenfilename from the radiobutton without giving it the required argument. This is precisely what the error message is telling you.

Second, You have defined a class named filedialog that takes one parameter: root. This class overrides the filedialog module. Thus, from within askopenfilename you are making a recursive call to the very same askopenfilename, and are failing to provide the required argument since self.file_opt is an empty dictionary.

Upvotes: 2

Bobby
Bobby

Reputation: 1571

Your askopenfilename(self, root) function requires a root parameter but you didn't pass anything in your

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

Upvotes: 0

Related Questions