将鼠标悬停在按钮上时更改按钮图像tkinter

2024-10-04 01:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

当鼠标悬停在按钮上时,如何更改图像? 我需要当您将鼠标悬停在按钮1或2上时,图片会发生变化:

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

悬停

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

Tags: 图像image图片root按钮filephoto2photo1
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:32

Tkinter有“enter”和“leave”事件,您必须将它们绑定到某个函数,并且可以使用config方法更改图像

下面是一个演示:


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

如果您希望许多按钮都具有这种效果。我建议您创建自己的按钮,继承Button

这里有一个例子

Thx至@furas建议。这是更新的类

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)

如何使用: 只需在img1和img2参数中指定图像路径

以下是一个例子:

img = r'path1' 
img2 = r'path2'

btn = Btn(root, img1=img, img2=img2)
btn.pack()

相关问题 更多 >