Tkinter: Check if window is already open

Question:

This is my very easy code:

def test():
   if window.winfo_exists():
       pass
   else:    
       window = Toplevel(root)

root = Tk()
button = Button(root, text="Test", command=test)
button.pack()
root.mainloop()

I basically just want to check if the window the button opens is already open. If this is the case, the button will do nothing. The problem with my code is that I get a "UnboundLocalError: local variable ‘window’ referenced before assignment" error when I check the window.

I already searched for hours for a suitable solution. Here is the idea that did not work:

Creating a seperate boolean and set to True, if window is open

  • The Problem here is that when I close the window, I wont be able to set the boolean back to False. So I just wont be able to open the window again, when I closed it earlier.

Does anybody know a suitable solution for my problem? Thank you in advance 🙂

Asked By: Silh0uett3

||

Answers:

Your variable window in if window.winfo_exists() is non-existent, so Python thinks your window variable already exists, but the function can’t see it.

Because the variable doesn’t exist, you can’t see it, so the next code will help you up.

from tkinter import *

def test():
    # trying code for errors/exceptions
    try:
        global window
        if window.winfo_exists():   # python will raise an exception there if variable doesn't exist
            pass
        else:
            window = Toplevel(root)
    except NameError:               # exception? we are now here.  
        window = Toplevel(root)
    else:                           # no exception and no window? creating window.
        if window.winfo_exists() == False:
            window = Toplevel(root)

root = Tk()
button = Button(root, text="Test", command=test)
button.pack()
root.mainloop()

Thank me later!
EDIT: this is now working

Answered By: stysan

I just figured it out by myself. I had to use protocols to get the option to open the window again after I closed it:

def test():
   def on_closing():
       dict_windows["window"] = False
       window.destroy()

   if dict_windows["window"] == True:
       pass
   else:
       window = Toplevel(root)
       window.protocol("WM_DELETE_WINDOW", on_closing)
       dict_windows["window"] = True

dict_windows = {
    "window" : False
}   

root = Tk()
button = Button(root, text="Test", command=test)
button.pack()
root.mainloop()

I made a dictionary to store all the windows booleans (in case I add more windows in the future).

Answered By: Silh0uett3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.