[英]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()
So, I created hundred buttons over here and wanted them to change color when the mouse hovers over them, I did this as per the inte.net to create events and bind them with the buttons.所以,我在这里创建了一百个按钮,并希望它们在鼠标悬停在它们上面时改变颜色,我按照 inte.net 这样做来创建事件并将它们与按钮绑定。
My problem is I created hundred buttons using for-loop, so I added the binding code in the loop.我的问题是我使用 for 循环创建了一百个按钮,所以我在循环中添加了绑定代码。 The result of this was that if I hover the mouse over any Button only the 100th hover changes color.
这样做的结果是,如果我 hover 将鼠标悬停在任何按钮上,只有第 100 个 hover 会改变颜色。 I also placed the hovering code outside the loop but that does nothing
我还将悬停代码放在循环之外,但这什么也没做
How do I change color of button over hover for each button in this case.在这种情况下,如何为每个按钮更改超过 hover 的按钮颜色。
Thank you谢谢
The event object that is passed to the bound function has a reference to the widget that received the event, under the attribute widget
.传递给绑定 function 的事件 object 在属性
widget
下具有对接收该事件的小部件的引用。 You can use that to change the attribute of the button.您可以使用它来更改按钮的属性。
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.