Billy Cao
Billy Cao

Reputation: 371

Tkinter mainloop() not quitting after closing window

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')

Upvotes: 6

Views: 5558

Answers (1)

Novel
Novel

Reputation: 13729

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')

Upvotes: 3

Related Questions