'Selecting specific items from lists
I am trying to make "Who's that Pokemon" in Python. I have uploaded different image files to my folder. Some are silhouette versions of the pokemon, while others show the actual Pokemon. I put the names of these image files into two seperate lists. One list is for silhouette images; the other is for non-silhouette images.
I am trying to figure out how I can select an name from one of the lists while at the same time making sure it matches up with the final product. For example, if I pick a Pikachu sliouette, how do I make it so that when I click on the awnser, it shows the image of Pikachu instead of a different Pokemon?
Here is my code:
import tkinter as tk
from PIL import ImageTk,Image
import random
#pop up window creation
window = tk.Tk()
window.title("Who's that Pokemon? AP CSP Project by Ethan Wong")
window.wm_geometry("850x500")
#list of silo image name files
silo_list = ['pikachusilo.png', 'rowletsilo.png', 'dugtriosilo.png']
#noraml list (non-silo images)
non_silo_list = ['pikachu.png', 'rowlet.png', 'dugtrio.png']
silo_pick = random.choice(silo_list)
normal_pick = random.choice(non_silo_list)
#silo images (opens up the silo images)
silo_image = ImageTk.PhotoImage(Image.open(silo_pick)) #google.com (image source)
silo = tk.Label(image=silo_image)
silo.pack()
#normal (non-silo images)
normal_image = ImageTk.PhotoImage(Image.open(normal_pick))
normal = tk.Label(image=normal_image)
#how the button works (displays the normal image)
def clickfoward():
normal.pack()
#button atempt
fowardbutton = tk.Button(window, text="see the answer!", command=clickfoward)
fowardbutton.pack()
window.mainloop()
But, I'm not sure what to do from here.
Solution 1:[1]
Like this:
images = [
('pikachu.png','pikachusilo.png'),
('rowlet.png','rowletsilo.png'),
('dugtrio.png','dugtriosilo.png')
]
Alternatively, if you STRICTLY follow that naming rule, where the silhouette name is the full image with "silo" added before the dot, you can easily generate one from the other.
Solution 2:[2]
You can use zip() to bind the image of the Pokemon with its corresponding silouette image.
Change this:
silo_pick = random.choice(silo_list)
normal_pick = random.choice(non_silo_list)
to
silo_pick, normal_pick = random.choice(zip(silo_list, non_silo_list))
zip() programmatically generates the list of 2-tuples (as seen in Tim Roberts's answer), and then the LHS assigns the first element of that tuple to silo_pick, the second to normal_pick.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
