Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

python 3.x - Tkinter, window not closing

I'm creating a game which runs fine but when I close the window it gives this error:

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

To fix it, I added this code, which I got from another question asked here, before the while loop.

x = True
def update_x():
    global x
    x = False

tk.protocol("WM_DELETE_WINDOW", update_x)

The while loop is:

while x == True:
    draw()
    time.sleep(0.1)
    tk.update()

The window doesn't close at all now. What am I doing wrong? I don't really know how to use the mainloop method, is there any way to make it work using the while loop above?

question from:https://stackoverflow.com/questions/65840120/tkinter-window-not-closing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, I am pretty sure when you overwrite the 'WM_DELETE_WINDOW' you should call tk.destroy() at the end of your function (update_x) or the window will not be destroyed. Second of all, if 'x' is always a boolean it is better to say: while x: do_smth() rather than while x == True and while not x instead of while x == False. If you still have problems after these changes there are two things you can do: Firstly, you can check if the window exists then update it like so: if tk.winfo_exists(): tk.update() or maybe at the end of your new protocol function (update_x), instead of tk.destroy() you can write tk.quit() to safely exit the program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...