Aug-08-2022, 05:03 PM
Hi,
I'm trying to define 5 labels as a list of labels. The reason I want to do this is that later I can iterate through the labels with a for loop in order to make updates.
This is the code that works:
I'm trying to define 5 labels as a list of labels. The reason I want to do this is that later I can iterate through the labels with a for loop in order to make updates.
This is the code that works:
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title('some text') root.geometry('1200x800') root.configure(background='green') def resize_cards(card): our_card_img = Image.open(card) # open the image our_card_resized_image = our_card_img.resize((150, 218)) # resize the image global our_card_image our_card_image = ImageTk.PhotoImage(our_card_resized_image) # output the card return our_card_image # return the card backImage = resize_cards(f'images/pokerCards/backOfCard/back1.png') cardLabel1 = Label(root, image=backImage, bg='snow') cardLabel1.grid(sticky = W, row=0, column=0, pady=20, padx=20) cardLabel2 = Label(root, image=backImage, bg='snow') cardLabel2.grid(sticky = W, row=0, column=1, pady=20, padx=20) cardLabel3 = Label(root, image=backImage, bg='snow') cardLabel3.grid(sticky = W, row=0, column=2, pady=20, padx=20) cardLabel4 = Label(root, image=backImage, bg='snow') cardLabel4.grid(sticky = W, row=0, column=3, pady=20, padx=20) cardLabel5 = Label(root, image=backImage, bg='snow') cardLabel5.grid(sticky = W, row=0, column=4, pady=20, padx=20) root.mainloop()this code does not work:
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title('some text') root.geometry('1200x800') root.configure(background='green') global cardLabel #cardLabel = [] def resize_cards(card): our_card_img = Image.open(card) # open the image our_card_resized_image = our_card_img.resize((150, 218)) # resize the image global our_card_image our_card_image = ImageTk.PhotoImage(our_card_resized_image) # output the card return our_card_image # return the card for f in range(5): global cardLabel, backImage cardLabel = [] backImage = resize_cards(f'images/pokerCards/backOfCard/back1.png') cardLabel[f] = Label(root, image=backImage, bg='snow') cardLabel[f].grid(sticky = W, row=0, column=f, pady=20, padx=20) root.mainloop()It returns the following error:
Error:cardLabel[f] = Label(root, image=backImage, bg='snow')
IndexError: list assignment index out of range
Thanks