-1
我想要做的一個彈出列表:請與Tkinter的
- 讓一個按鈕。
- 如果將鼠標懸停在上面,會出現頂層,如果刪除光標,則頂層消失。
- 如果將光標從按鈕移動到此頂層,則不會(!)消失,並且如果將光標移動到其他位置,它最終會消失。
爲此,我創建了2個類(按鈕和頂層)。我試着結合輸入和離開他們兩個,但是這會導致兩個問題:
- 如果從按鍵移動光標,頂層應該被摧毀,但它與func_1創建和銷燬與func_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()
這是我所能做的最多。感謝任何幫助。
如果你至少包含了一點解釋你做了什麼,那麼你的答案會更好。否則,我們不得不閱讀代碼並逐行比較原始代碼以查看更改內容。 –