我正在为一个学校项目编写一个程序,现在需要检查按钮上的图像,以便通过if命令运行它,如下所示:
root=Tk()
flag = PhotoImage(file='flag.png')
box = PhotoImage(file='box.png')
def function(event):
if(button.cget('image')==flag):
button.config(image=box)
else:
button.config(image=flag)
button=Button(root)
button.config(image=box)
button.bind('<ButtonRelease>', function)
button.pack()
root.mainloop()
我希望它能在每次我点击按钮时在flag和box之间改变图像,但是它只是在我第一次单击时将图像更改为flag,并且对于其余的点击没有响应
试试这个代码
您只需要以
if(button.cget('image')==str(flag)):
的形式进行测试(注意,str()
添加到图像中)。image
选项只是一个字符串,包含Tcl/Tk环境中自动生成的image对象的名称;Python image对象转换为这个字符串,但不包含实现字符串比较所需的代码,因此需要显式地进行转换。在相关问题 更多 >
编程相关推荐