pythontkinterkeyboardinterrupt

tkinter: KeyboardInterrupt taking a while


Using Tkinter with Python on Linux, I'm trying to make Ctrl+C stop execution by using the KeyboardInterrupt Exception, but when I press it nothing happens for a while. Eventually it "takes" and exits. Example program:

import sys
from Tkinter import *

try: 
    root = Tk()
    root.mainloop()
except:
    print("you pressed control c")
    sys.exit(0)

How can the program react quicker?


Solution

  • That is a little problematic because, in a general way, after you invoke the mainloop method you are relying on Tcl to handle events. Since your application is doing nothing, there is no reason for Tcl to react to anything, although it will eventually handle other events (as you noticed, this may take some time). One way to circumvent this is to make Tcl/Tk do something, scheduling artificial events as in:

    from Tkinter import Tk
    
    def check():
        root.after(50, check) # 50 stands for 50 ms.
    
    root = Tk()
    root.after(50, check)
    root.mainloop()