问题描述
我已经写了一些代码,它获取出生日期并计算正确的中国星座动物(鼠、狗等)。我想添加一个 gui,当用户点击计算时,gui 会显示适当动物的照片。为此,我想我必须在命令定义中更改图像的文件路径,但找不到方法来做到这一点。我已经尽可能简化了下面的代码:
x = Tk()
x.state('zoomed')
def find_animal():
animal = 'tiger' # I've left out the actual calculation part
picture.place(relx=0.4,rely=0.5)
b = Button(x,text='Calculate',command=find_animal)
b.place(relx=0.5,rely=0.3)
file_path = 'rabbit.png'
pic = PhotoImage(file=file_path)
picture = Label(x,image=pic)
x.mainloop()
我希望做的事情是以某种方式更改 find_animal 函数中的 file_path 变量,以便显示的图像从兔子变为老虎
解决方法
您可以使用 pic.config()
更改 find_animal()
内的图像路径:
def find_animal():
animal = 'tiger' # I've left out the actual calculation part
pic.config(file=animal+".png")
picture.place(relx=0.4,rely=0.5)