Tkinter 不会将图像文件更新为新目录中的一个

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

我正在尝试创建一个顶部带有图像图标的按钮,该按钮应将图标切换为按钮在单击时调用的函数中指定的图像。但是,该按钮在点击时与原始图像保持原样,没有任何错误消息,是不是我遗漏了什么?

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

我认为您应该更改函数中的这一行:

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

你写了 == 但你应该写 =.

您的语法意味着您正在使用 False return 而不是变量减速进行声明。

首先,在你的代码中,这部分导致错误:

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

==操作用于比较
然后关于你的功能。在你创建一个按钮(或 tkinter 中的其他东西)之后,你应该使用 .config 来改变它的一些属性。
您可以编写此代码以更改图标:

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