简体   繁体   中英

Change button images when you hover over them tkinter

How can I change the image when hovering over the button? I need that when you hover over the button 1 or 2 the picture changes:

Photo1 = (file='Image\ProgrammingButton') 
Photo2 = (file='Image\DesignButton')  
But1 = (root, image=Photo1) 
But2 = (root, image=Photo2)

On hover

Photo1 = (file='Image\ActiveProgrammingButton') 
Photo2 = (file='Image\ActiveDesignButton')

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):
        btn.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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM