0

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

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

2 回答 2

1

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

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

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

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

于 2020-07-26T07:07:09.467 回答
0

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

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()
于 2020-07-26T07:29:13.413 回答