Tkinter文件对话框中断条目小部件

2024-10-02 08:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

当应用程序调用^ {< CD1>},^ {< CD2>}字段没有正确聚焦时。你知道吗

详细说明:

初始化tkinter应用程序时,entry字段在默认情况下处于启用状态。它们的状态是tk.ENABLED,可以通过使用tab滚动字段来关注它们,最重要的是,可以单击它们来选择字段。你知道吗

出于某种原因,调用tkinter.filedialog会破坏此行为。如果调用tkinter.filedialog的方法,例如askdirectoryaskopenfile()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()

在这里,如果BR8KFalse,则代码的行为正常;如果BR8KTrue,则代码的行为不正确。你知道吗

(注意:在生产环境中,这将是面向对象的。这个问题在面向对象的环境中仍然存在。)


Tags: 代码用户importtrue应用程序环境tkinter状态
1条回答
网友
1楼 · 发布于 2024-10-02 08:27:42

这是由于在第一次到达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()

相关问题 更多 >

    热门问题