如何改变点击按钮图像?



我为单个按钮创建了两个图像,并且还创建了带有图像的按钮。我想改变按钮图像每当我第一次点击它。例如,当我点击按钮时,我希望按钮图像改变unclickkedimage";ClickedImage" .

我无法在stackoverflow中找到任何类似的问题。

from tkinter import *

class Example(Frame):
def __init__(self, tk=None):
super().__init__()
self.tk = tk
self.init_ui()
def init_ui(self):
self.photoTodo = PhotoImage(file="./Images/TodoUnClicked.png")
Button(self.tk, image=self.photoTodo).pack(side=LEFT)
self.photoStayFocussed = PhotoImage(file="./Images/StayFoccusedUnClicked.png")
Button(self.tk, image=self.photoStayFocussed).pack(side=RIGHT)

def main():
root = Tk()
root.configure(bg='white')
ex = Example(root)
root.title('')
root.iconbitmap('./Images/empty.ico')
root.geometry("400x100+300+300")
root.mainloop()

if __name__ == '__main__':
main()

您可以使用自定义按钮类来完成此操作。

class ImageButton(Button):
def __init__(self, master, image1, image2, *args, **kwargs):
self.unclickedImage = PhotoImage(file = image1)
self.clickedImage = PhotoImage(file = image2)
super().__init__(master, *args, image = self.unclickedImage, **kwargs)
self.toggleState = 1
self.bind("<Button-1>", self.clickFunction)
def clickFunction(self, event = None):
if self.cget("state") != "disabled": #Ignore click if button is disabled
self.toggleState *= -1
if self.toggleState == -1:
self.config(image = self.clickedImage)
else:
self.config(image = self.unclickedImage)

这将小部件主控和第一和第二图像路径作为参数,创建PhotoImage对象,然后用未单击的图像实例化一个按钮。
有一个绑定到<Button-1>,这是左键点击,这改变图像时,按钮被点击。toggleState变量保持跟踪当前图像显示,所以当按钮被点击相反的图像显示。
你可以像这样把它合并到你当前的程序中:

from tkinter import *
class ImageButton(Button):
def __init__(self, master, image1, image2, *args, **kwargs):
self.unclickedImage = PhotoImage(file = image1)
self.clickedImage = PhotoImage(file = image2)
super().__init__(master, *args, image = self.unclickedImage, **kwargs)
self.toggleState = 1
self.bind("<Button-1>", self.clickFunction)
def clickFunction(self, event = None):
if self.cget("state") != "disabled": #Ignore click if button is disabled
self.toggleState *= -1
if self.toggleState == -1:
self.config(image = self.clickedImage)
else:
self.config(image = self.unclickedImage)
class Example(Frame):
def __init__(self, master, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.init_ui()
def init_ui(self):
ImageButton(self, "./Images/TodoUnClicked.png", "./Images/TodoClicked.png").pack(side=LEFT)
ImageButton(self, "./Images/StayFoccusedUnClicked.png", "./Images/StayFoccusedClicked.png").pack(side=RIGHT)

def main():
root = Tk()
root.configure(bg='white')
ex = Example(root)
ex.pack(fill = "both", expand = True)
root.title('')
root.geometry("400x100+300+300")
root.mainloop()

if __name__ == '__main__':
main()

注意我也固定了你的Example类,因为你没有使用它很正确。当你继承一个tkinter对象时,你将主对象传递给super().__init__,然后使用self作为子对象的父对象。

最新更新