首页 > 解决方案 > 使用命令更改图像的文件路径

问题描述

我写了一些代码,它需要出生日期并计算正确的中国星座动物(老鼠、狗等)。我想添加一个 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 变量,以便显示的图像从兔子变为老虎

标签: filetkinterphotoimage

解决方案


您可以使用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)

推荐阅读