Python Forum
[tkinter] color change for hovering over button - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/Forum-Python-Coding)
+--- Forum: GUI (https://python-forum.io/Forum-GUI)
+--- Thread: [tkinter] color change for hovering over button (/Thread-tkinter-color-change-for-hovering-over-button)



[tkinter] color change for hovering over button - teacher - Jul-04-2020

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()



RE: [tkinter] color change for hovering over button - menator01 - Jul-04-2020

This works on enter
import tkinter as tk

root = tk.Tk()
btn = tk.Button(text='Button', activebackground='red').pack()
root.mainloop()



RE: [tkinter] color change for hovering over button - teacher - Jul-04-2020

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.


RE: [tkinter] color change for hovering over button - menator01 - Jul-04-2020

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()



RE: [tkinter] color change for hovering over button - teacher - Jul-04-2020

Thank you menator01. That's more like what I was looking for.