Search code examples
pythonuser-interfacetkintertoplevel

Create Toplevel tkinter Window after the closure of previous Toplevel window


I have a list of n elements, I need to create a popup menu for each of them. Each popup would contain some checkboxes.

Condition: A new Toplevel popup window must open after the closure of the previous Toplevel window, and not all at the same time

My code:

from tkinter import *

#root gui
root = Tk()
root.title("test")
root.geometry("300x400")

# Need three popup windows
a = ["one", "two", "three"]
b = []

def open():
    for _ in range(len(a)):
        top = Toplevel()
        top.title("selections")
        def next_window():
            top.destroy()
            show() # This function is supposed to show the selections of each popup window on root gui
        for i in range(3):
            b.append(IntVar())
            b[i].set(0) # de selecting all checkboxes intiially
            # checkboxes
            Checkbutton(top, text=a[i], variable=b[i]).pack()
        Button(top, text = "Submit", command=next_window).pack()
        Button(top, text = "skip", command=top.destroy).pack() # this button is used to skip the popup if no selection required

def show():
 # printing selections made on each popup window
 for i in range(3):
  Label(root, text=b[i].get()).pack()

mB = Button(root, text="print selections", command=open).pack()

root.mainloop()

My concern: All three popups are opening at the same time for me now. enter image description here


Solution

  • You need to call top.wait_window() at the end inside the for loop:

    for _ in range(len(a)):
        top = Toplevel(root)
        top.title("selections")
        def next_window():
            top.destroy()
            show() # This function is supposed to show the selections of each popup window on root gui
        for i in range(3):
            b.append(IntVar())
            b[i].set(0) # de selecting all checkboxes intiially
            # checkboxes
            Checkbutton(top, text=a[i], variable=b[i]).pack()
        Button(top, text = "Submit", command=next_window).pack()
        Button(top, text = "skip", command=top.destroy).pack() # this button is used to skip the popup if no selection required
        top.grab_set() # route all events to this window
        top.wait_window() # wait for current window to close