[英]Want to change color of 100 buttons on hover in tkinter
import tkinter as tk
def on_enter(e):
year_btn.config(background="orange",foreground="white")
def on_leave(e):
year_btn.config(background="white", foreground="black")
window = tk.Tk()
yearnumber=1
for i in range(10):
window.rowconfigure(i,weight=1,minsize=40)
window.columnconfigure(i,weight=1,minsize=40)
for j in range(10):
frame = tk.Frame(padx=5,pady=5)
frame.grid(row=i,column=j,sticky="nsew")
year_btn = tk.Button(text=f"{yearnumber}", master=frame, activebackground="red", activeforeground="white")
year_btn.pack(padx=1, pady=1,fill="both",expand="true")
#year_btn.grid(sticky="nsew")
yearnumber+=1
year_btn.bind('<Enter>', on_enter)
year_btn.bind('<Leave>',on_leave)
window.mainloop()
所以,我在這里創建了一百個按鈕,並希望它們在鼠標懸停在它們上面時改變顏色,我按照 inte.net 這樣做來創建事件並將它們與按鈕綁定。
我的問題是我使用 for 循環創建了一百個按鈕,所以我在循環中添加了綁定代碼。 這樣做的結果是,如果我 hover 將鼠標懸停在任何按鈕上,只有第 100 個 hover 會改變顏色。 我還將懸停代碼放在循環之外,但這什么也沒做
在這種情況下,如何為每個按鈕更改超過 hover 的按鈕顏色。
謝謝
傳遞給綁定 function 的事件 object 在屬性widget
下具有對接收該事件的小部件的引用。 您可以使用它來更改按鈕的屬性。
def on_enter(e):
e.widget.config(background="orange",foreground="white")
#^^^^^^^
def on_leave(e):
e.widget.config(background="white", foreground="black")
#^^^^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.