Search code examples
pythontkintertoplevel

Why is Toplevel showing 2 windows?


I am trying to make a tkinter application which doesn't close everything (other windows) when the first window (root) is closed. I have tried to use Toplevel() which works perfectly for pop-up windows in other programs but not for making a base level.

from tkinter import *

top = Toplevel(bg='red')

top.mainloop()

I don't know if this is possible or I don't know if I can change the Tk()'s properties to make it so it doesn't shut all other windows down.


Solution

  • There are two windows getting displayed because when a tkinter widget is created, it forces a Tk instance to be created as well, and every widget, unless a parent is explicitly passed, is a child to that automatically created Tk instance. So your code essentially mimics the following code:

    from tkinter import *
    
    root = Tk()
    
    top = Toplevel(root, bg='red')
    
    root.mainloop()
    

    Now there are some ways to work around that for the behavior you want, one is to hide the actual Tk instance:

    import tkinter as tk
    
    root = tk.Tk()
    root.withdraw()
    
    top = tk.Toplevel(root, bg='red')
    
    #to display root window again
    #root.iconify()
    #root.deiconify()
    root.mainloop()
    

    Another way would be to overrule the deletion of the root itself, but I doubt that's actually what you want:

    import tkinter as tk
    
    
    def callback():
        print("Won't close")
    
    root = tk.Tk()
    
    root.protocol("WM_DELETE_WINDOW", callback)
    
    root.mainloop()