Tkinter tkMessageBox禁用Tkinter按键绑定 [英] Tkinter tkMessageBox disables Tkinter key bindings

查看:106
本文介绍了Tkinter tkMessageBox禁用Tkinter按键绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的示例:

Here's a very simple example:

from Tkinter import *
import tkMessageBox

def quit(event):
  exit()

root = Tk()
root.bind("<Escape>", quit)
#tkMessageBox.showinfo("title", "message")
root.mainloop()

如果按原样正确运行代码 ,则在按 Esc 时,程序将终止.现在,如果我取消注释tkMessageBox行,则在关闭消息框后,绑定将丢失",即按 Esc 不会执行任何操作.这是在Python 2.7中发生的.您能验证一下这是否也在发生吗?让我知道您的Python版本.

If I run the code exactly as it is, the program will terminate when Esc is hit. Now, if I un-comment the tkMessageBox line, the binding is "lost" after closing the message box, i.e. pressing Esc won't do anything anymore. This is happening in Python 2.7. Can you please verify if this is happening also to you? And let me know about your Python version.

这是绕过"问题的一种方法.这是一种不同的方法,但可能会有所帮助:

Here is a way to "by-pass" the problem. It's a different approach, but it might help:

from Tkinter import *
import tkMessageBox

def msg_test():
  tkMessageBox.showinfo("title", "message")

def quit(event):
  exit()

root = Tk()
root.bind("<Escape>", quit)
btn = Button(root, text="Check", command=msg_test); btn.pack()
root.mainloop()

通过单击按钮使用tkMessageBox不会影响键绑定,即,按 Esc 继续起作用.

Using tkMessageBox via a button click, doesn't affect key binding, i.e. pressing Esc continues to work.

推荐答案

如果我理解此问题,则在调用mainloop之前先调用tkMessageBox.showInfo() 会出现不良行为.如果是这样,我认为这是Windows上tkinter中的一个已知错误.

If I understand the problem, you get the bad behavior if you call tkMessageBox.showInfo() before calling mainloop. If that is so, I think this is a known bug in tkinter on windows.

解决方案很简单:不要那样做.如果您需要在程序的开始显示一个对话框,请使用after安排它在mainloop启动之后显示,或者在显示该对话框之前调用update.

The solution is simple: don't do that. If you need a dialog to show at the very start of your program, use after to schedule it to appear after mainloop has started, or call update before displaying the dialog.

例如:

root = Tk()
root.after_idle(msg_test)
root.mainloop()


原始错误是在很久以前报告的,而tk错误数据库已经移动了一到两次,所以我很难找到原始问题的链接.这是2000/2001年提到的一个问题: https://core.tcl.tk /tk/tktview?name = 220431ffff (请参见错误报告最底部的注释).


The original bug was reported quite some time ago, and the tk bug database has moved once or twice so I'm having a hard time finding a link to the original issue. Here's one issue from 2000/2001 that mentions it: https://core.tcl.tk/tk/tktview?name=220431ffff (see the comments at the very bottom of the bug report).

该报告声称它已得到修复,但是也许它又出现了,或者您的tkinter版本足够老而仍然存在该错误.

The report claims it was fixed, but maybe it has shown up again, or maybe your version of tkinter is old enough to still have the bug.

这篇关于Tkinter tkMessageBox禁用Tkinter按键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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