Python 特金特。Can';t生成图像名称后,使用图像标签显示图像
我已经编写了一个简单的tkinter GUI,当按下按钮时,它会将图像和标签更改为比萨饼或汉堡的图像和标签Python 特金特。Can';t生成图像名称后,使用图像标签显示图像,python,tkinter,Python,Tkinter,我已经编写了一个简单的tkinter GUI,当按下按钮时,它会将图像和标签更改为比萨饼或汉堡的图像和标签 import tkinter as tk root=tk.Tk() root.title("Sausage To Burger Or Pizza") #Variables FoodName=tk.StringVar() FoodName.set("Sausage") #Images Sausage=tk.PhotoImage(file="Sausage.png") Burger=tk.Ph
import tkinter as tk
root=tk.Tk()
root.title("Sausage To Burger Or Pizza")
#Variables
FoodName=tk.StringVar()
FoodName.set("Sausage")
#Images
Sausage=tk.PhotoImage(file="Sausage.png")
Burger=tk.PhotoImage(file="Burger.png")
Pizza=tk.PhotoImage(file="Pizza.png")
#Labels
FoodLabel=tk.Label(root,textvariable=(FoodName))
FoodLabel.grid(row=1,column=1)
FoodImageLabel=tk.Label(root,image=Sausage)
FoodImageLabel.grid(row=2,column=1)
def change_food():
import random
Food = ["Burger","Pizza"]
num= random.randrange(len(Food))
FoodName.set(Food[num])
FoodImageLabel.configure(image=Food[num])
#Button
ChangeButton=tk.Button(root,text="change",command=change_food)
ChangeButton.grid(row=3,column=1)
此代码产生此错误
在处理上述异常期间,发生了另一个异常:
_tkinter.TclError: image "Pizza" doesn't exist
尽管“Pizza.png”与代码文件存在于同一个文件中。将图像(
香肠
,汉堡
,比萨饼
)保存在dict中。然后使用食品[num]
在dict中查找图像。列表中的图像(“香肠.png”)或实体?如图像={'Pizza':tk.PhotoImage(file=“Pizza.png”),“香肠”:tk.PhotoImage(file=“香肠.png”)}
然后配置(image=images[Food[num]])
。