我想做什么:
为此,我创建了2个类(按钮和顶层)。我尝试将 Enter 和保留绑定到他们两个,但这会导致2个问题:
这就是我现在所拥有的:
import tkinter as tk
class PopupButton(tk.Button):
def __init__(self, *args, **kwargs):
tk.Button.__init__(self, *args, **kwargs)
self.bind("<Enter>", self.button_enter)
self.bind("<Leave>", self.button_leave)
def button_enter(self, event):
self.configure(bg="grey")
toplevel = Popup(root, bg="lightblue")
toplevel.overrideredirect(1)
x = root.winfo_x()
y = root.winfo_y()
toplevel.geometry("100x100+{}+{}".format(x+160, y+485))
def button_leave(self, event):
self.configure(bg="black")
pass
# problem here
class Popup(tk.Toplevel):
def __init__(self, *args, **kwargs):
tk.Toplevel.__init__(self, *args, **kwargs)
self.bind("<Enter>", self.toplevel_enter)
self.bind("<Leave>", self.toplevel_leave)
def toplevel_enter(self, event):
pass
# problem here
def toplevel_leave(self, event):
self.destroy()
root = tk.Tk()
root.configure(bg="white")
root.geometry("400x600")
button = PopupButton(root, text="Hover over me", font="courier 20", bg="black", fg="white")
button.pack(side="bottom")
root.mainloop()
这是我能做的最多。感谢任何帮助。
答案 0 :(得分:0)
我接受了问题中给出的代码并修改了button_leave
方法,以便当光标离开按钮时,仅当光标没有覆盖时才会销毁顶层(我使用{{1}方法知道光标在哪个小部件中)。我还删除了winfo_containing
方法,因为这里不需要它。
toplevel_enter