I have jpegs of all 52 cards that I'd like to use for a game of BlackJack. This is the code I have now to open an image, but if I were to do this for every card, it would take me over 200 lines.
ace = Image.open("filepath")
ace = ace.resize((50,75), Image.ANTIALIAS)
ace = ImageTk.PhotoImage(ace)
acelabel = Label(image = ace)
I've tried using a loop like the following, but then it doesn't actually affect the ace variable and instead raises an error.
ace = Image.open("File Path")
card_deck = [ace]
for i in card_deck:
i = i.resize((50,75), Image.ANTIALIAS)
i = ImageTk.PhotoImage(i)
acelabel = Label(image = ace)
Does anyone have any solutions?
CodePudding user response:
There's nothing special you need to do, just do it like you would create strings or numbers or any other sort of object. It might look something like this:
cards = ["ace", "queen", "king", ...]
images = {}
labels = {}
for card_name in cards:
filename = f"{card_name}.png"
image = Image.open(filename)
image = image.resize((50, 75), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
label = Label(image=image)
images[card] = image
labels[card] = label
Then, you can reference the images and labels like images['ace']
, labels['ace']
, etc.