Tkinter不会将映像文件更新为新目录中的映像文件

2024-10-03 04:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个按钮,上面有一个图像图标,它应该将图标切换到按钮单击时调用的函数中指定的图像。但是,当按下按钮时,按钮与原始图像保持不变,没有错误消息,是否有我遗漏的内容

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

Tags: 图像imagebuttononedrive按钮usersfile图标
2条回答

首先,在您的代码中,此部分会导致错误:

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

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

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

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

您的语法意味着您正在使用假返回而不是变量来生成语句

相关问题 更多 >