Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter gives following error in python 3.6: TclError: NULL main Window

I am writing a python program which executes the following sequence:
1. Dialog box to open/select a directory
2. perform certain operations
3. rename the file using a tkinter dialog box
4. Perform rest of the operations

I have written the following code:

def open_directory():
    directory_name = filedialog.askdirectory(title='Ordner Auswählen',parent=root)
    print(directory_name)
    root.destroy()

def input_name():
    def callback():
        print(e.get())
        root.quit()
    e = ttk.Entry(root)
    NORM_FONT = ("Helvetica", 10)
    label = ttk.Label(root,text='Enter the name of the ROI', font=NORM_FONT)
    label.pack(side="top", fill="x", pady=10)
    e.pack(side = 'top',padx = 10, pady = 10)
    e.focus_set()
    b = ttk.Button(root, text = "OK", width = 10, command = callback)
    b.pack()

def close_window():
    root.destory()

root = tk.Tk()
root.withdraw()
open_directory()  #dialogue box to select directory
<perform certain operations>
input_name()  #dialgue box for user input file name
root.mainloop()
close_window() #exit the mainloop of tkinter
<perform rest of the functions>

but I get the following error Tclerror: NULL main window I think it is realted to declaring root as the main window, but I dont seem to find where I have made the mistake. Is there some other method, which is better, for what I am trying to do here?

like image 755
Gaurav Kumar Avatar asked Jun 13 '26 12:06

Gaurav Kumar


1 Answers

As @CommonSense has mentioned, when you use withdraw to hide the main window, then you need to use the method deiconify to use the root again. Hence, change the function change_directory as follows:

def open_directory():
    directory_name = filedialog.askdirectory(title='Ordner Auswählen',parent=root)
    print(directory_name)
    root.deiconify()

If you do not deiconify the window, you could not call the function input_name, which makes use of the root window.

I have tested this code and it works.

PS: You also have a typo in the function close_window (when destroying the window).

like image 173
David Duran Avatar answered Jun 15 '26 01:06

David Duran