Tkinter filedialog 中断条目小部件
Tkinter filedialog breaks entry widgets
tl;dr:当应用程序调用 tkinter.filedialog
时,entry
字段未正确聚焦。
详细解释:
初始化 tkinter 应用程序时,entry
字段默认启用。它们的状态是 tk.ENABLED
,可以通过使用 tab
滚动字段来关注它们,最重要的是,它们可以被点击到 select 字段。
出于某种原因,此行为已通过调用 tkinter.filedialog
中断。如果调用了tkinter.filedialog
的方法,比如askdirectory
或者askopenfile()
,那么entry
的字段还是会有tk.ENABLED
的状态,后台会正常样式化,但单击输入字段不会插入光标或 select 字段。打字当然不会注册。
这可以通过切换到不同的 window 然后再切换回来来解决。但是,文件对话框 windows(正确地)return 用户直接返回到主 window,因此用户总是看到一个似乎被锁定的主 window向上。
看这个例子:
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
为 False
,则代码行为正常,如果 BR8K
为 True
,则代码行为不正确。
(注意:在生产环境中,这将是面向对象的。问题在面向对象的环境中仍然存在。)
这是一个已知问题,由在首次到达 mainloop() 之前调用对话框 window 引起。
解决此问题的最简单方法是在对话框前添加 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()
tl;dr:当应用程序调用 tkinter.filedialog
时,entry
字段未正确聚焦。
详细解释:
初始化 tkinter 应用程序时,entry
字段默认启用。它们的状态是 tk.ENABLED
,可以通过使用 tab
滚动字段来关注它们,最重要的是,它们可以被点击到 select 字段。
出于某种原因,此行为已通过调用 tkinter.filedialog
中断。如果调用了tkinter.filedialog
的方法,比如askdirectory
或者askopenfile()
,那么entry
的字段还是会有tk.ENABLED
的状态,后台会正常样式化,但单击输入字段不会插入光标或 select 字段。打字当然不会注册。
这可以通过切换到不同的 window 然后再切换回来来解决。但是,文件对话框 windows(正确地)return 用户直接返回到主 window,因此用户总是看到一个似乎被锁定的主 window向上。
看这个例子:
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
为 False
,则代码行为正常,如果 BR8K
为 True
,则代码行为不正确。
(注意:在生产环境中,这将是面向对象的。问题在面向对象的环境中仍然存在。)
这是一个已知问题,由在首次到达 mainloop() 之前调用对话框 window 引起。
解决此问题的最简单方法是在对话框前添加 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()