python - 如何在 Windows 中的 python 3 中正确地将焦点传递给消息框或从消息框传递焦点?

标签 python windows python-3.x tkinter

我正尝试在 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/

相关文章:

python - 如何使用可变补丁大小的 tf.random_crop 定义形状?

python - 使用 -m 运行 python 脚本时,为什么不调用 __init__.py?

ruby-on-rails - 在 Windows 7 上安装 ImageMagick 和 rmagick

Windows 中的 Java 文档打印

Python 3 运算符.div?

python - 当自定义命名空间为对象时,未设置默认 argparse 参数值

python - django websocket在循环中异步发送消息

python - 如何将Meteor链接到Opencv python

windows - 重新启动 Windows 7 时 Trayicon 丢失

python - 删除错误字符 "\xC2"python字符串