Search on blog:

Tkinter: How to open only one Toplevel window

To have only one Toplevel window you can disable button which open this Toplevel window and enable it when you close this Toplevel window

You can use button['state'] to set it 'disable' or 'normal'

You needs window.protocol("WM_DELETE_WINDOW", function) to execute function when you use button [X] to close window.

import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---

def close_top():

    single_top.destroy()

    b['state'] = 'normal'

def open_top():
    global single_top

    b['state'] = 'disable'

    single_top = tk.Toplevel(root)
    l = tk.Label(single_top, text='TopLevel')
    l.pack()
    single_top.protocol("WM_DELETE_WINDOW", close_top)  # assign to closing button [X]

# --- main ---

root = tk.Tk()

b = tk.Button(root, text='TOP', command=open_top)
b.pack()

root.mainloop()

Other method is to create global variable for Toplevel window and assign None at start. When you click button then you create window only when variable is None and then you assign new window to this variable so next time it will be not None. When you close Toplevel window then you have to again set this variable None

This method can be used for different objects (not only in GUI) - ie. it can be used to have only one active bullet in game.

This method can be used also with list and len() to have few windows - ie. always not more then 3 windows.

import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---

def close_top():
    global single_top

    single_top.destroy()
    single_top = None

def open_top():
    global single_top

    if single_top is None:
        single_top = tk.Toplevel(root)
        l = tk.Label(single_top, text='TopLevel')
        l.pack()
        single_top.protocol("WM_DELETE_WINDOW", close_top)  # assign to closing button [X]
    else:
        print("Toplevel already exists")

# --- main ---

single_top = None

root = tk.Tk()

b = tk.Button(root, text='TOP', command=open_top)
b.pack()

root.mainloop()

Notes:

Stackoverflow: Open only one Tk.Toplevel window

If you like it
Buy a Coffee