Python Forum

Full Version: [tkinter] color change for hovering over button
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The following code will not work as intended. It only turns yellow when leaving the button but not red when entering. What am I missing?

import tkinter as tk

def onLeave(event):
    b.config(bg='yellow')

def onEnter(event):
    b.config(bg='red')
    

root = tk.Tk()
root.minsize(100,100)

b=tk.Button(root)
b.pack() 
b.bind('<Leave>', onLeave)
b.bind('<Enter>', onEnter)

root.mainloop()
This works on enter
import tkinter as tk

root = tk.Tk()
btn = tk.Button(text='Button', activebackground='red').pack()
root.mainloop()
Thanks for the reply. It works but I cannot explain to my students why my original code doesn't work. With activebackground you don't need the <Enter> bind at all.
I'm contemplating using tkinter to teach gui's but issues like this don't give me confidence in the toolkit. Is this typical for tkinter?

BTW, I searched for the reason my code does not work. I suspect it's not redrawing the widget after the color change. Someone said one should call .update() on the widget but that did not help. Even .update() and .update_idletasks() on the root window did not work.
Using bind events
#! /usr/bin/env python3

import tkinter as tk

def on_leave(event):
    btn['bg'] = 'yellow'

def on_enter(event):
    btn['activebackground'] = 'blue'

root = tk.Tk()
root.geometry('200x200')
btn = tk.Button(text='Button')
btn['font'] = 'sans 18 normal'
btn.pack()
btn.bind('<Leave>', on_leave)
btn.bind('<Enter>', on_enter)
root.mainloop()
Thank you menator01. That's more like what I was looking for.