KeyboardInterrupt需要一段时间 [英] KeyboardInterrupt taking a while

查看:404
本文介绍了KeyboardInterrupt需要一段时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我刚刚开始使用Tkinter在Linux上使用Python.我试图通过使用KeyboardInterrupt异常使Cntrl + C停止执行,但是当我按下它时,一段时间没有任何反应.最终,它接管"并退出.一些阅读表明这可能与线程或某些东西有关,但是我对这些东西很陌生,我真的不确定从哪里开始.

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.

推荐答案

这有点问题,因为在一般情况下,调用mainloop方法后,您将依靠Tcl来处理事件.由于您的应用程序什么也不做,因此Tcl没有任何反应,尽管它最终会处理其他事件(如您所注意到的,这可能需要一些时间).避免这种情况的一种方法是使Tcl/Tk做一些事情,安排人工事件,如下所示:

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()

这篇关于KeyboardInterrupt需要一段时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆