Search code examples
pythontkinterwindowtk-toolkittoplevel

Close existing toplevel when a new is created. Tkinter Python 3


Ive got a button in a program that opens a toplevel window. If the button is pressed again I want the old toplevel to be destroyed and a new one to be created. I've searched for hours and tried implementing different ways but nothing seems to work.

Ive tried these approaches in various forms:

if toplevel is None or not toplevel.winfo_exists():
    toplevel.destroy()


try:
    toplevel.destroy()
except:
    pass


if toplevel.winfo_exists() == "1":
    toplevel.destroy()

My code looks like this:

def translate():
        #(I would like to check for and close existing toplevels here)
        toplevel = Toplevel()
        ...stuff

I greatly appreciate all the help I can get!


Solution

  • Inside translate, toplevel is a local variable. You need to make it global if you wish to access it outside of translate and you aren't using classes.