Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter mainloop() not quitting after closing window

Tags:

python

tkinter

This is NOT a duplicate of Python tkinter mainloop not quitting on closing the window

I have an app that builds on tkinter. I observed at sometimes after I close the window using the X button, the code will not execute past the mainloop() line. This happens completely randomly about 10% of chance. Rest of the time, it works like a charm. I would like to ask if there are any way to force it. As I said, the code blocks on the mainloop() line, thus calling sys.exit() after it does not help.

I am using Python 3.9.8.

This is not 100% reproducible, but here is something that might trigger the problem:

from tkinter import *
root = Tk()
Label(root, 'hi').pack()
mainloop()
print('exited')
like image 474
Billy Cao Avatar asked Aug 04 '26 23:08

Billy Cao


2 Answers

My first thought is to use root.mainloop() instead of tkinter.mainloop(). This makes a difference if you are using several windows.

That said, I did see this a long time ago on some old OSes. Never figured out the reason, so I just wrote my own quit function, like this:

import tkinter as tk

def _quit():
    root.quit()
    root.destroy() 

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", _quit)
tk.Label(root, 'hi').pack()
root.mainloop()
print('exited')
like image 125
Novel Avatar answered Aug 07 '26 12:08

Novel


I had similar issues, and it was caused by an embedded matplotlib plot.

Running the following when quitting resolved the issue.

plt.close("all")
like image 24
user3439124 Avatar answered Aug 07 '26 13:08

user3439124



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!