tl;dr: 当应用程序调用时tkinter.filedialog
, entry
字段无法正确聚焦。
长解释:
初始化 tkinter 应用程序时,entry
默认情况下启用字段。他们的状态是tk.ENABLED
,可以通过滚动字段来关注它们tab
,最重要的是,可以单击它们来选择字段。
由于某种原因,此行为通过调用被破坏tkinter.filedialog
。如果一种方法tkinter.filedialog
被称为,例如askdirectory
or askopenfile()
, the entry
场仍将有tk.ENABLED
状态,并且背景将被正确设置样式,但单击输入字段将不会插入光标或选择该字段。当然,打字不会注册。
这可以通过切换到不同的窗口然后切换回来来解决。然而,文件对话框窗口(正确地)将用户直接返回到主窗口,因此用户总是看到一个似乎被锁定的主窗口。
看这个例子:
import tkinter as tk
from tkinter import filedialog
BR8K = True
root = tk.Tk()
if BR8K:
filedialog.askdirectory()
entry = tk.Entry(root, takefocus=True, highlightthickness=2)
entry.grid(sticky="WE")
root.mainloop()
在这里,如果以下情况,代码将正常运行:BR8K
is False
,并且错误地如果BR8K
is True
.
(注意:在生产环境中,这将是面向对象的。该问题在面向对象的环境中仍然存在。)
这是由于在第一次到达 mainloop() 之前调用对话框窗口而导致的已知问题。
解决这个问题最简单的方法是添加update_idletask()
在对话框之前。
尝试这个:
import tkinter as tk
from tkinter import filedialog
BR8K = True
root = tk.Tk()
# By adding this you avoid the focus breaking issue of calling dialog before the mainloop() has had its first loop.
root.update_idletasks()
if BR8K:
filedialog.askdirectory()
entry = tk.Entry(root, takefocus=True, highlightthickness=2)
entry.grid(sticky="WE")
root.mainloop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)