简体   繁体   中英

How to open a new Tkinter window in a while loop?

How do I make a new Tkinter window in a while loop?

Tkinter is kind of new to me, so I would like some easy explanations. I would like it to open a Tkinter window in a while loop. Basically, a user says yes to a question, then a new window pops up, and it will ask the question again, and it should pop up again etc... I have some "code" that would basically say what I mean. All of the other questions out there did not really work for me. im stupid and didnt include code

#import modules
import time
import sys
from tkinter import *
from tkinter import ttk
from playsound import playsound
from threading import Thread

win = Tk()

win.geometry("900x350")

def lift_window():
   win.lift()
   win.after(1000, lift_window)

def sound_play():
    playsound('a sound')

while True:
   start = input("make new window? (y/n): ")
   if start == "y":
      Label(win, text="new window!", font=('Aerial 16 italic')).place(x=5, y=140)

      Thread(target = lift_window).start()
      Thread(target = sound_play).start()

      lift_window()
      win.mainloop()
   elif start == "n":
      print("ok")
      sys.exit()

Some error messages I get were

_tkinter.TclError: can't invoke "label" command: application has been destroyed

But that is all.

The error message is worded rather poorly. The "application" it speaks of is just the Tk instance that win points to. It's destroyed when you close the window, so you need to make a new one each time through the loop.

while True:
    start = input("make new window? (y/n): ")
    if start == "y":
        win = Tk()
        win.geometry("900x350")
        Label(win, text="new window!", font=('Aerial 16 italic')).place(x=5, y=140)
        win.mainloop()

Note that win being destroyed will also affect the win.lift and win.after calls in lift_window . I'm not entirely certain what you're trying to do there (you call lift_window twice, once from a new thread, and each call sets a timer to call it again?), so I can't comment on how to fix that part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM