Python Forum
[tkinter] color change for hovering over button
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[tkinter] color change for hovering over button
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):

def onEnter(event):

root = tk.Tk()

b.bind('<Leave>', onLeave)
b.bind('<Enter>', onEnter)

This works on enter
import tkinter as tk

root = tk.Tk()
btn = tk.Button(text='Button', activebackground='red').pack()
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()
btn = tk.Button(text='Button')
btn['font'] = 'sans 18 normal'
btn.bind('<Leave>', on_leave)
btn.bind('<Enter>', on_enter)

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

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter - How can I remove the background borders from ttk.Button? TurboC 4 231 Oct-18-2020, 10:58 AM
Last Post: TurboC
  Tkinter menu font size -method to change tonycat 2 298 Oct-11-2020, 02:43 AM
Last Post: tonycat
  tkinter | Button color text on Click Maryan 2 230 Oct-09-2020, 08:56 PM
Last Post: Maryan
  Tkinter - How can I change the default Notebook border color? TurboC 4 283 Oct-06-2020, 10:35 PM
Last Post: TurboC
  [Tkinter] Trying to change font size w/o changing button size python63 3 1,443 Aug-05-2020, 01:04 AM
Last Post: Larz60+
  [Tkinter] button command tkinter Heyjoe 6 1,321 Jul-30-2020, 07:06 PM
Last Post: deanhystad
  [PyQt] Increase text size and change color based on temp pav1983 5 397 Jun-22-2020, 10:52 PM
Last Post: menator01
  tkinter button help Gina92 10 721 May-27-2020, 08:17 AM
Last Post: Gina92
  TKINTER - Change font color for night or day Ayckinn 2 691 May-24-2020, 09:25 PM
Last Post: Ayckinn
  How to make button text bold in Tkinter? scratchmyhead 2 688 May-16-2020, 02:53 AM
Last Post: scratchmyhead

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020