When Mouse enters or hovers over any widget we can trigger any call back function. Similarly when mouse moves out or Leave the widget we can trigger another call back function.
Tkinter Mouse Enter & Leave events to trigger function to manage the attributes using config()
Using config()
To change any attribute of the widget with the event we are using config() method. Several properties like text, font, background color etc can be changed inside the call back function.
Call back function
Here is one call back function to change the background color and text of a Button and a Label.
def my_callback1(event):
b1.config(text='Welcome',bg='lightgreen')
l2.config(text='Click to register',bg='lightyellow')
Above call back function is triggered when mouse enters over the Button ( b1 )
b1.bind('<Enter>',my_callback1)
Full code is here
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("600x300")
def my_callback1(event):
b1.config(text='Welcome',bg='green')
l2.config(text='click this')
def my_callback2(event):
b1.config(text='Thanks ',bg='gray')
l2.config(text='You left the button')
def my_callback3(event):
l1.config(text='Welcome')
def my_callback4(event):
l1.config(text='Thanks ',bg='lightblue')
b1=tk.Button(my_w,text='I am a Button',font=22)
b1.grid(row=0,column=0,padx=10,pady=10)
str1=tk.StringVar(value='I am entry ')
e1=tk.Entry(my_w,text=str1,font=22,bg='yellow')
e1.grid(row=1,column=0,padx=10,pady=10)
l1=tk.Label(my_w,text='I am Label',font=22,bg='lightgreen')
l1.grid(row=2,column=0,padx=10,pady=10)
l2=tk.Label(my_w,text='Message area',font=22,bg='yellow')
l2.grid(row=3,column=0,padx=10,pady=10)
b1.bind('<Enter>',my_callback1) # Mouse enters the button
b1.bind('<Leave>',my_callback2) # Mouse leaves the button
e1.bind('<Enter>',lambda event:str1.set('Data here')) # entry
l1.bind('<Enter>',my_callback3) # Mouse enters the Label
l1.bind('<Leave>',my_callback4) # Mouse leaves the Label
my_w.mainloop()
Mouse enter & Leave event over a Label
Mouse entry and leave event on Tkiner Label to update attributes by using config()