Home > Blockchain >  How to change Tkinter button image on click?
How to change Tkinter button image on click?

Time:09-17

I have two images for a single button and also I created buttons with images. I would like to change the button image whenever I first click it. For example when I click the button I want button image to change "UnclickedImage" to "ClickedImage".

I could not be able to find any similar question in 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()

CodePudding user response:

You could do this with a custom button class.

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)

This takes the widget master and the first and second image paths as arguments, creates the PhotoImage objects and then instantiates a button with the unclicked image.
There is a binding to <Button-1>, which is left click, and this changes the image when the button is clicked. The toggleState variable keeps track of the current image showing so when the button is clicked the opposite image is shown.
You can incorporate this in to your current program like this:

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

Note I also fixed your Example class as you weren't using it quite right. When you inherit a tkinter object, you pass the master to super().__init__ and then use self as the parent of the children.

  • Related