tk 后无法输入 [英] No input possible after tk

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

问题描述

如果有这段代码:

import Tkinter as tk
import tkFileDialog

menu = tk.Tk()
res = tkFileDialog.askopenfilename() # un-/comment this line
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)

res = menu.mainloop()

注意:askopenfilename 只是一个虚拟输入.所以只需关闭它即可进入 TK 的(现在被阻止的)主窗口.

Note: the askopenfilename is just a dummy input. So Just close it to get to the (now blocked) main window of TK.

当我评论 askopenfilename 时,一切正常.但是有了它,我无法在条目中输入数据.

When I comment the askopenfilename everything works fine. But with the it, I can not enter data in the entry.

这只发生在 Windoze 环境中.askopenfilename 似乎窃取了主 TK 窗口的焦点.单击一个完全不同的窗口并再次返回到 TK 窗口后,就可以输入了.

This only happens with Windoze environments. The askopenfilename seems to steal the focus for the main TK window. After clicking a totally different window and back again in the TK window, input is possible.

推荐答案

我以前看过有关此问题的报告,我认为这是 Windows 上的一个已知错误.在打开对话框之前,您需要让 mainloop 启动.

I've seen reports of this before, I think it's a known bug on windows. You need to let mainloop start before you open a dialog.

如果您希望应用程序首次启动时出现对话框,您可以使用 afterafter_idle 让它在 mainloop 启动后运行

If you want the dialog to appear when the app first starts up you can use after or after_idle to have it run after mainloop starts up.

例如:

menu = tk.Tk()
...
def on_startup():
    res = tkFileDialog.askopenfilename()

menu.after_idle(on_startup)
menu.mainloop()

如果您不希望在对话框之后执行任何其他 GUI 代码,请将除创建根窗口之外的所有代码移动并调用 mainloopon_startup 或其他一些函数.

If you don't want any other GUI code to execute until after the dialog, move all your code except for the creation of the root window and call to mainloop into on_startup or some other function.

例如:

def main(filename):
    label = tk.Label(None, text="abc")
    label.grid(row=0, column=0, sticky=tk.W)
    entry = tk.Entry(None)
    entry.grid(row=0, column=1, sticky=tk.EW)

def on_startup():
    res = tkFileDialog.askopenfilename()
    main(filename)

root = Tk()
root.after_idle(on_startup)

这篇关于tk 后无法输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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