9

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?

Udi
  • 29,222
  • 9
  • 96
  • 129
Thomas Shields
  • 8,874
  • 5
  • 42
  • 77

2 Answers2

10

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()
mmgp
  • 18,901
  • 3
  • 53
  • 80
  • Thanks, especially for the explanation of the problem. I sort of guessed Tcl had taken over, but I wasn't sure, and I didn't know how to intervene. Thanks! – Thomas Shields Dec 09 '12 at 03:20
  • Complementing from the comments: focusing a Tkinter window emits events to be handled, so it takes the chance to handle other pending events. – mmgp Dec 09 '12 at 03:23
0

According to Guido van Rossum, this is because you are stuck in the Tcl/Tk main loop, while the signal handlers are only handled by the Python interpreter.

You can work around the problem, by binding Ctrl-c to a callback function:

import sys
import Tkinter as tk

def quit(event):
    print "you pressed control c"
    root.quit()

root = tk.Tk()
root.bind('<Control-c>', quit)
root.mainloop()
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 8
    That will only work if your current focus is the Tkinter window, and then press control-c there. It doesn't solve the case where you control-c in the shell. – mmgp Dec 09 '12 at 03:21