Tkinter has 'enter' and 'leave' events which you have to bind to some function and you can change the image using the config
method.
Here is a demonstration:
from tkinter import *
from PIL import Image, ImageTk
def onEnter(event):
global img
img = ImageTk.PhotoImage(Image.open(r'img2'))
btn.config(image=img)
def onLeave(event):
global img
img = ImageTk.PhotoImage(Image.open(r'img1'))
btn.config(image=img)
root = Tk()
img = ImageTk.PhotoImage(Image.open(r'img1'))
btn = Button(root, image=img)
btn.pack()
btn.bind('<Enter>', onEnter)
btn.bind('<Leave>', onLeave)
root.mainloop()
If you want this effect for many buttons. I would suggest you create your own button inheriting the Button
class.
Here is an example.
Thx to @furas suggestion. Here is the updated class
class Btn(Button):
def __init__(self, root, img1, img2, *args, **kwargs):
super().__init__(root, *args, **kwargs)
self.img = ImageTk.PhotoImage(Image.open(img1))
self.img2 = ImageTk.PhotoImage(Image.open(img2))
self['image'] = self.img
self.bind('<Enter>', self.enter)
self.bind('<Leave>', self.leave)
def enter(self, event):
self.config(image=self.img2)
def leave(self, event):
self.config(image=self.img)
How to use:
Just specify your image path in the img1 and img2 parameter
Here is an example:
img = r'path1'
img2 = r'path2'
btn = Btn(root, img1=img, img2=img2)
btn.pack()