我正尝试在 Python 3 中使用带有 Tkinter 的消息框来请求用户的名称。以下精简代码会生成这样一个消息框,并在关闭时正确传递值,但消息框会在主窗口后面弹出。如果我将消息框移出,输入名称作为名称,然后单击“确定”,主窗口就会更新,但会隐藏在所有其他打开的窗口后面。
一位 friend 试图在 Mac 上重现该问题,但代码的行为符合预期。
如何使消息框显示在顶部并在开始时获得焦点,以及如何在消息框关闭时正确地将焦点移至主窗口?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter
import tkinter.simpledialog
root = tkinter.Tk()
playerNameVar = tkinter.StringVar()
playerNameVar.set(tkinter.simpledialog.askstring("Name", \
"Name?",parent=root))
playerLabel = tkinter.Label(root,textvariable = playerNameVar)
playerLabel.grid()
root.mainloop()
最佳答案
"How do I make the message box show up on top with focus at the beginning, and how do I correctly hand focus to the main window when the message box is closed?"
我不认为你可以在不将 tkinter 解包到它的 Tcl 的情况下使消息框显示在焦点之上,但是你可以轻松地将 root
设置为 lower
在显示对话框之前本身:
root.lower()
您可以在调用对话行之后简单地调用 focus_set
。有关完整示例,请参见下面的代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter
import tkinter.simpledialog
root = tkinter.Tk()
root.lower()
playerNameVar = tkinter.StringVar()
playerNameVar.set(tkinter.simpledialog.askstring("Name", \
"Name?",parent=root))
root.focus_set()
#root.tkraise() # this is optional
playerLabel = tkinter.Label(root,textvariable = playerNameVar)
playerLabel.grid()
root.mainloop()
关于python - 如何在 Windows 中的 python 3 中正确地将焦点传递给消息框或从消息框传递焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48352645/