问题
So I just started messing around with Python on Linux, using Tkinter. I'm trying to make Cntrl+C stop execution by using the KeyboardInterrupt Exception, but when i press it nothing happens for a while. Eventually it "takes" and exits. A little bit of reading suggests this might have to do with threading or something, but i'm so new to this stuff i'm really not sure where to begin.
#! /usr/bin/python
import sys
from Tkinter import *
try:
root = Tk()
root.mainloop()
except:
print "you pressed control c"
sys.exit(0)
I hate to be the noob that only wants the quick-fix, so if your answer is as simple as pointing me to the right documentation, that'd be wonderful.
回答1:
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()
回答2:
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()
来源:https://stackoverflow.com/questions/13784232/keyboardinterrupt-taking-a-while