如何获取按钮图像地址

2024-04-20 10:34:55 发布

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

我正在为一个学校项目编写一个程序,现在需要检查按钮上的图像,以便通过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,并且对于其余的点击没有响应


Tags: 项目图像imageboxconfigifpngfunction
2条回答

试试这个代码

root=Tk()

flag = PhotoImage(file='Denaro.gif')

box = PhotoImage(file='Andre.gif')

def function(event):
    if(button.cget('image')=='pyimage1'):
        button.config(image=box)
    else:
        button.config(image=flag)


button=Button(root)
button.config(image=box)
button.bind('<ButtonRelease>', function)
button.pack()
root.mainloop()

您只需要以if(button.cget('image')==str(flag)):的形式进行测试(注意,str()添加到图像中)。image选项只是一个字符串,包含Tcl/Tk环境中自动生成的image对象的名称;Python image对象转换为这个字符串,但不包含实现字符串比较所需的代码,因此需要显式地进行转换。在

相关问题 更多 >