簡體   English   中英

當您在 hover 上更改按鈕圖像 tkinter

[英]Change button images when you hover over them tkinter

將鼠標懸停在按鈕上時如何更改圖像? 我需要的是,當您在按鈕 1 或 2 上使用 hover 時,圖片會發生變化:

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

在 hover

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

Tkinter 具有“進入”和“離開”事件,您必須將其綁定到某些 function 並且您可以使用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 class。

這是一個例子。

感謝@furas 的建議。 這是更新的 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)

使用方法:在img1和img2參數中指定你的圖片路徑即可

這是一個例子:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM