【问题标题】:Tkinter OptionMenu refocuses on itself after command is called to create new ToplevelTkinter OptionMenu 在调用命令以创建新的 Toplevel 后重新聚焦于自身
【发布时间】: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 版本?

标签: python tkinter


【解决方案1】:

您可以在创建Toplevel 的任何地方使用此Toplevel_name.focus_set() 方法。此方法适用于任何小部件,它将键盘焦点移动到特定小部件,这意味着发送到应用程序的所有键盘事件都将路由到该小部件。

有关基本小部件方法的完整列表,请参阅https://effbot.org/tkinterbook/widget.htm

希望对你有所帮助, 干杯!

【讨论】:

  • 感谢您的回答!但是,这对我不起作用。在我移动光标之前,新的顶层窗口似乎需要一段时间。当我移动光标时,焦点会回到根。 .focus_set() 没有帮助,因为在新窗口已经获得焦点时调用了该行。
猜你喜欢
  • 2016-12-07
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多