Python 使 Tkinter 小部件成为焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3842220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:58:14  来源:igfitidea点击:

Make Tkinter widget take focus

pythonuser-interfacetkinter

提问by Ali

I have a script that uses Tkinter to pop up a window with a message. How do I make sure it takes focus so the user doesn't miss it and explicitly has to dismiss the window. the code is :

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

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

采纳答案by ars

You can use focus_forcemethod. See the following:

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

But note the the documentation:

但请注意文档:

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.

w.focus_force()

强制输入焦点到小部件。这是不礼貌的。最好等待窗口管理器给你焦点。另请参阅下面的 .grab_set_global()。

Update: It should work on root. For example, try running the following code. It will create a window and you can switch focus. After 5 seconds, it will try to grab the focus.

更新:它应该适用于root. 例如,尝试运行以下代码。它将创建一个窗口,您可以切换焦点。5 秒后,它会尝试抓住焦点。

from Tkinter import *

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

回答by Ido Fishler

What worked for me was:

对我有用的是:

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

I found this and some other way to do it in win32 here

我在这里在 win32 中找到了这个和其他一些方法