Tkinter tkMessageBox disables Tkinter key bindings

社会主义新天地 提交于 2020-01-14 03:10:11

问题


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

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

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


回答1:


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.

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.

For example:

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

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

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.



来源:https://stackoverflow.com/questions/48983443/tkinter-tkmessagebox-disables-tkinter-key-bindings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!