pythontkintertk-toolkitphotoimage

Tkinter won't update image file to one in a new directory


I'm trying to create a button with an image icon on top of it which should switch icons to an image specified in a function the button calls when its clicked. The button however just stays as it is with the original image when hit with no error messages, is there something I'm missing out on?

from tkinter import *

sampleW = Tk()
sampleW.geometry("250x250")
sampleW.title("god help me")

def imageSwitch():
    icon1Directory == PhotoImage(file = r"C:\Users\txvpa\OneDrive\Desktop\hentai\Atom Projects\The Bread Exchange\bread man.png") # new image directory
    print("button has been pressed")

icon1Directory = PhotoImage(file = r"C:\Users\txvpa\OneDrive\Desktop\hentai\Atom Projects\The Bread Exchange\plus_black.png") # original image directory
icon1_photoImage = icon1Directory.subsample(7, 7)

button = Button(sampleW, relief = "ridge", padx = 70, pady = 5,image = icon1_photoImage, command = imageSwitch)
button.grid(column = 0, row = 0)

sampleW.mainloop()

Solution

  • first of all, in your code, this part causes errors:

    icon1Directory == PhotoImage(file = r"C:\Users\txvpa\OneDrive\Desktop\hentai\Atom Projects\The Bread Exchange\bread man.png") # new image directory
    

    the == operation is for comparison.
    then about your function. after you create a button(or something else in tkinter), you should use .config to change some properties of it.
    you can code this to change the icon:

    from tkinter import *
    sampleW = Tk()
    sampleW.geometry("250x250")
    sampleW.title("god help me")
    
    def imageSwitch():
        icon2 = PhotoImage(file=r'C:\Users\txvpa\OneDrive\Desktop\hentai\Atom Projects\The Bread Exchange\bread man.png')
        button.config(image=icon2)
        button.image = icon2
    
    icon = PhotoImage(file=r'C:\Users\txvpa\OneDrive\Desktop\hentai\Atom Projects\The Bread Exchange\plus_black.png')
    button = Button(sampleW, relief = "ridge", padx = 70, pady = 5,image = icon, command = imageSwitch)
    button.grid(column = 0, row = 0)
    sampleW.mainloop()