3

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')
E_net4
  • 27,810
  • 13
  • 101
  • 139
Billy Cao
  • 335
  • 4
  • 15
  • We're going to need a [mcve]. – Bryan Oakley Nov 14 '21 at 05:15
  • @BryanOakley you see the problem is this is NOT reproducible, but completely random. If you insist on an example, just: from tkinter import *, root = Tk(), mainloop() – Billy Cao Nov 14 '21 at 05:17
  • If we can't reliably reproduce the problem, we're not going to be able to help. I've started and stopped tkinter programs no doubt thousands if not tens of thousands of times and I've never seen this. – Bryan Oakley Nov 14 '21 at 05:36
  • I just had this issue and it reproduces 100% of the time on my computer but idk what causes it – Rainb Jul 20 '22 at 06:12

1 Answers1

1

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')
Novel
  • 13,406
  • 2
  • 25
  • 41
  • I currently do not have any other windows but I would like to keep the ability to do that in future, thus I used the mainloop(). I will try your solution and see if it happens again. Thanks! – Billy Cao Nov 14 '21 at 06:20
  • `root.mainloop()` vs `tkinter.mainloop()` doesn't matter in this case since the OP has only a single root window. – Bryan Oakley Nov 14 '21 at 16:51
  • 2
    hi the same issue happened again even with your solution, i think it's somehwere else in my code but its more than 2000 lines and i really have no idea what could have caused it...it happened on multiple systems including windows 10 and windows 11 – Billy Cao Nov 15 '21 at 17:08