Search code examples
pythontkinterwindowtoplevel

Why do I get an extra empty window in Tkinter?


Here is my code:

from tkinter import *

OPTIONS = ["Available","Busy","Invisible","Away"]

now = Toplevel()
variable = StringVar(now)
variable.set(OPTIONS[0]) # default value
details = {"U_status":""}
def verify():
    global u_status
    details["U_status"]=variable.get()
    print ("value is:" + variable.get())
    now.destroy()
def status():
    w = OptionMenu(now, variable, *OPTIONS)
    w.pack()
    button = Button(now, text="OK", command=verify, relief='flat')
    button.pack()
if __name__=='__main__':
    status()
    mainloop()

While running the above code, along with the window (I wanted) another empty window appears. Can anyone figure out what is wrong in this code?


Solution

  • Here now = Toplevel() should be replaced with Tk(), like:

    now = Tk()
    

    When you use Toplevel() a Tk() window is made in the background, if its not already made(your case), and that is the reason you are getting a blank new window. Actually that blank window is your main window.

    Toplevel() is used to make child windows for the parent Tk() windows,ie, if you want sub windows within your main window(now), you will use Toplevel(). Because more than one Tk() in your code will cause some errors later on.