首页 > 解决方案 > Tkinter 不会将图像文件更新为新目录中的一个

问题描述

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

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

标签: pythontkintertkphotoimage

解决方案


我认为你应该在函数中更改这一行:

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

你写了==,但你应该写=

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


推荐阅读