简体   繁体   中英

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.

My problem is I created hundred buttons using for-loop, so I added the binding code in the loop. The result of this was that if I hover the mouse over any Button only the 100th hover changes color. 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.

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 . 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")
    #^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM