对于每个获奖项目,我想在GUI上显示其对应的图片。目前,我正在编写一堆在if语句中显示的代码以实现此目的。我确定我可以使用某种循环来减少代码量,但是目前还不确定如何实现。
在每次不获奖的情况下删除图像时,我也遇到问题。我当前解决此问题的尝试显示在底部else语句中提供的代码中。
chance_of_drop = random.randint(1,100)
if chance >= chance_of_drop:
winner = np.random.choice(Items, p=probabilities)
drop['text'] = "You've recieved a drop: " + winner
if winner == Items[0]:
Loot_IMG = PhotoImage(file=Images[0])
reward_img = Label(GUI, image = Loot_IMG, background = bg_color)
reward_img.Loot_IMG = Loot_IMG #
reward_img.grid(row = 3, column=1, sticky = N)
elif winner == Items[1]:
Loot_IMG = PhotoImage(file=Images[1])
reward_img = Label(GUI, image = Loot_IMG, background = bg_color)
reward_img.Loot_IMG = Loot_IMG #
reward_img.grid(row = 3, column=1, sticky = N)
elif winner == Items[2]:
Loot_IMG = PhotoImage(file=Images[2])
reward_img = Label(GUI, image = Loot_IMG, background = bg_color)
reward_img.Loot_IMG = Loot_IMG #
reward_img.grid(row = 3, column=1, sticky = N)
# AND SO ON.....
#print("You've recieved a drop:", winner)
else:
luck['text'] = "You are unlucky"
#REMOVING IMAGE DOES NOT WORK
Loot_IMG = PhotoImage(file="")
reward_img = Label(GUI, image = Loot_IMG, background = bg_color)
reward_img.Loot_IMG = Loot_IMG #
reward_img.grid(row = 3, column=1, sticky = N)
此外,我还将提供我在函数中进一步构建的两个列表:
Images = ["loot/Dexterous_prayer_scroll.png", "loot/Arcane_prayer_scroll.png",
"loot/Twisted_buckler.png", "loot/Dragon_hunter_crossbow.png",
"loot/Dinh's_bulwark.png", "loot/Ancestral_hat.png", "loot/Ancestral_robe_top.png",
"loot/Ancestral_robe_bottom.png", "loot/Dragon_claws.png", "loot/Elder_maul.png",
"loot/Kodai_insignia.png", "loot/Twisted_bow.png"]
# indivdual drop rates
Items = ["Dexterous prayer scroll", "Arcane prayer scroll",
"Twisted buckler", "Dragon hunter crossbow",
"Dinh's bulwark", "Ancestral hat", "Ancestral robe top",
"Ancestral robe bottom", "Dragon claws",
"Elder maul", "Kodai insignia", "Twisted bow"]
答案 0 :(得分:0)
您可以使用内置的zip()
函数以及类似的方法来排除重复的代码:
task lockDependencies {
dependsOn = ['dependencies','--update-locks *:*']
}
还要注意,tkinter if chance >= chance_of_drop:
winner = np.random.choice(Items, p=probabilities)
drop['text'] = "You've recieved a drop: " + winner
for item, image in zip(Items, Images):
if winner == item:
Loot_IMG = PhotoImage(file=image)
reward_img = Label(GUI, image=Loot_IMG, background=bg_color)
reward_img.Loot_IMG = Loot_IMG #
reward_img.grid(row=3, column=1, sticky=N)
break
else:
try:
reward_img.destroy() # Remove any existing Label.
except NameError:
pass # Doesn't exist, ignore.
类仅支持PhotoImage
,.gif
或.pgm
格式的图像。要加载.ppm
图像,您将需要使用Python Imaging Library(PIL)子模块的ImageTk.PhotoImage类。
更新为备注:
Tk 8.6 added built-in support for the .png
图像文件格式,因此您可能不需要使用PIL。