Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Thomas Shields Avatar asked Dec 09 '12 03:12

Thomas Shields


Video Answer


1 Answers

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()
like image 194
mmgp Avatar answered Sep 30 '22 14:09

mmgp