Alteros
Alteros

Reputation: 71

How can I make windows show up one at a time in python tkinter?

How can I make windows show up one at a time with tkinter? For example, if I typed in 6 as an input, and called a function with a button, I need it to show me 6 windows, but one at a time. It will only prompt me the next window after pressing a button from the previous one.

I tried using a for loop to loop through the range of the input, and create new windows with a button based on that range, but the problem is that they all show up at the same time:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.title("Multiple windows")

def multiplewindows():
    for i in range(int(number.get())):
        tempwindow = Toplevel()
        tempwindow.title(f"Window {i+1}")
        tempbutton = Button(tempwindow, text=f"Button {i+1}")
        tempbutton.pack(padx=10, pady=10)

number = Entry(root, width=5)
number.pack(padx=10, pady=10)
button = Button(root, text="Show", command=multiplewindows)
button.pack(padx=10, pady=10)

root.mainloop()

Is there any way to pause the for loop and allow it to continue after pressing the button in the newly created window?

Upvotes: 0

Views: 272

Answers (2)

Thingamabobs
Thingamabobs

Reputation: 8042

The easiest way to do this is like acw1668 was recommanded with the builtin method of tkinter that is calld with wait_window().

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.title("Multiple windows")

def multiplewindows():
    for i in range(int(number.get())):
        tempwindow = Toplevel()
        tempwindow.title(f"Window {i+1}")
        tempbutton = Button(tempwindow, text=f"Button {i+1}", command=tempwindow.destroy)
        tempbutton.pack(padx=10, pady=10)
        tempwindow.wait_window()

number = Entry(root, width=5)
number.pack(padx=10, pady=10)
button = Button(root, text="Show", command=multiplewindows)
button.pack(padx=10, pady=10)



root.mainloop()

Here we have created a function with a forloop that waits until the window is destroyed and added a command to the Button to destroy the window.

Upvotes: 0

imxitiz
imxitiz

Reputation: 3987

I think you don't need for loop to do this

def multiplewindows():
  j=int(number.get())
  tempwindow = Toplevel()
  tempwindow.title(f"Window {j}")
  tempbutton = Button(tempwindow, text=f"Button {j}")
  tempbutton.pack(padx=10, pady=10)

And if you want to use for loop to do this

def multiplewindows():
  j=int(number.get())
  for i in range(int(number.get())):
    if (i+1)==j:
      tempwindow = Toplevel()
      tempwindow.title(f"Window {j}")
      tempbutton = Button(tempwindow, text=f"Button {j}")
      tempbutton.pack(padx=10, pady=10)

Upvotes: 1

Related Questions