使Tkinter小部件成为焦点

2024-04-26 17:49:57 发布

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

我有一个脚本,它使用Tkinter弹出一个带有消息的窗口。如何确保它获得焦点,以便用户不会错过它,并明确地必须关闭窗口。代码是:

root = Tk()
to_read = "Stuff" 
w = Label(root, text=to_read)
w.pack()
root.mainloop()

Tags: to代码text用户脚本消息readtkinter
2条回答

对我有用的是:

root.wm_attributes("-topmost", 1)
root.focus_force()

我在win32here中找到了这个和其他方法

您可以使用focus_force方法。请参见以下内容:

但请注意文档:

w.focus_force()

Force the input focus to the widget. This is impolite. It's better to wait for the window manager to give you the focus. See also .grab_set_global() below.

更新:它应该在root上工作。例如,尝试运行以下代码。它将创建一个窗口,你可以切换焦点。5秒后,它会试图抓住焦点。

from Tkinter import *

root = Tk()
root.after(5000, lambda: root.focus_force())
root.mainloop()

相关问题 更多 >