Search code examples
pythontkinterwindowtoplevel

Check if a Toplevel window is open from outer function in python tkinter


What I want to to do is to avoid opening the same window if it's already open. So, I have a window and a button, and a button that opens another window, I want to click the button again and if the second window it's already open, change the focus to the second window or if it's not open, open it.

I tried with secondwindow.winfo_exists() but due that the function of the button that launches the second window is out the secondwindow function, it returns me that my secondwindow is not defined.

Way apart of this, I added a second button to check if the second window is created instead of checking calling the same function again.

Any way to do this? This is part of the code I have used:

def startwind1():
    wind1 = tk.Tk()
    wind1.title('Window 1')
    w1button1 = ttk.Button(wind1,text='Launch Window 2',command=startwind2).pack()
    w1button2 = ttk.Button(wind1,text='Check if Window 2 exists',command=checkwind2).pack()
    wind1.mainloop()

def startwind2():
    wind2 = tk.Toplevel()
    wind2.title('Window 2')

def checkwind2():
    if wind2.winfo_exists() == 1:
        print('Window 2 exists')
    else:
        print('Window 2 not exists )

Hope you can help me!


Solution

  • Inside startwind2 you have to use global wind2 to assign window to global variable and then it will be available in other functions.

    It also need to create wind2 = None so variable will be available even before you create window.

    import tkinter as tk
    from tkinter import ttk
    
    wind2 = None
    
    def startwind1():
        #global wind2
        #wind2 = None
    
        wind1 = tk.Tk()
        wind1.title('Window 1')
    
        w1button1 = ttk.Button(wind1,text='Launch Window 2', command=startwind2)
        w1button1.pack()
    
        w1button2 = ttk.Button(wind1,text='Check if Window 2 exists',command=checkwind2)
        w1button2.pack()
    
        wind1.mainloop()
    
    def startwind2():
        global wind2
    
        wind2 = tk.Toplevel()
        wind2.title('Window 2')
    
    def checkwind2():
        if (wind2 is not None) and wind2.winfo_exists():
            print('Window 2 exists')
        else:
            print('Window 2 not exists')
    
    startwind1()