【发布时间】:2020-08-14 09:33:40
【问题描述】:
我正在使用 Tkinter OptionMenu 创建顶层窗口。但是,我发现创建窗口后,如果我稍微移动光标,焦点会回到我的主屏幕(左侧的小屏幕)而不是新创建的 Toplevel。
如果我使用 Button 而不是 OptionMenu 来做同样的事情,新的 Toplevel 窗口会正确地发送到前面。
这是产生错误的代码:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_button()
self.create_dropdown()
def create_button(self):
self.button = tk.Button(self)
self.button["text"] = "Create Toplevel"
# this works correctly, new topmost sent to the top
self.button["command"] = self.create_toplevel
self.button.pack(side="top")
def create_dropdown(self):
self.current_dropdown_option = tk.StringVar(self.master)
self.current_dropdown_option.set("Choose an option")
# this doesn't work correctly, the new Toplevel is sent to the back
self.dropdown = tk.OptionMenu(self.master, self.current_dropdown_option,
"Option 1", command=self.create_toplevel_for_dropdown)
self.dropdown.pack(side="top")
def create_toplevel(self):
self.toplevel = tk.Toplevel(self.master)
self.toplevel.geometry("600x600")
def create_toplevel_for_dropdown(self, arg):
self.toplevel = tk.Toplevel(self.master)
self.toplevel.geometry("600x600")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
我尝试了https://stackoverflow.com/a/36191443/2860949 的解决方案,但它不起作用。
在来自 python.org 的 macOS Catalina 10.15.5、python 3.7.6 上测试。
【问题讨论】:
-
尝试添加一行
self.toplevel.focus_force()? -
@CoolCloud 添加
self.toplevel.focus_force()没有帮助。但是,添加self.toplevel.attributes('-topmost', True)可以,但不允许将小部件移到后面。 -
@CoolCloud 如果我添加
self.toplevel.attributes('-topmost', True)然后在tkinter 窗口通过event.widget.attributes('-topmost', False)获得焦点后删除该属性,则它不起作用。 -
我尝试了代码 onn,我一开始所说的确实对我有用
-
@CoolCloud 奇怪的是我们的结果相互矛盾。我尝试再次添加
self.toplevel.focus_force()行,但它仍然对我不起作用。你能重现我使用原始代码描述的错误吗?你的操作系统是什么,你使用的是哪个 python 版本?