Python Tkinter如何获取按钮图像地址

Python Tkinter如何获取按钮图像地址,python,tkinter,python-idle,Python,Tkinter,Python Idle,我正在为一个学校项目编写一个程序,现在我需要检查按钮上的图像,以便我可以通过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.co

我正在为一个学校项目编写一个程序,现在我需要检查按钮上的图像,以便我可以通过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()
root=Tk()
flag=PhotoImage(file='flag.png')
box=PhotoImage(file='box.png')
def功能(事件):
如果(button.cget('image')==标志):
button.config(image=box)
其他:
button.config(image=flag)
按钮=按钮(根)
button.config(image=box)
按钮绑定(“”,函数)
button.pack()
root.mainloop()
我希望每次单击按钮时,它都会在标志和方框之间更改图像,但它只是在我第一次单击时将图像更改为标志,其余的单击都没有响应。请尝试以下代码

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()
root=Tk()
flag=PhotoImage(file='Denaro.gif')
box=PhotoImage(file='Andre.gif')
def功能(事件):
如果(button.cget('image')=='pyimage1'):
button.config(image=box)
其他:
button.config(image=flag)
按钮=按钮(根)
button.config(image=box)
按钮绑定(“”,函数)
button.pack()
root.mainloop()

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

我相信jasonharper随后的回答是对这一问题的解释和概括,因为str(标志)当前将是“pyimage1”(str(框)将是“pyimage2”)。