I'm writing a program in Python using the tkinter library so that I can display 4 images from a specified path, however the images do not properly load. There is a large space where the images should've loaded, however there isn't actually an image there (see attached screenshots). I'm using ImageTk
and Image
from the PIL
import since I read that's how to do it on another post, however it didn't work for me.
Here is some related code: (background info: program for Arabic letters lol)
# imports
from tkinter import *
from PIL import ImageTk,Image
import random
# variables
letters = ["yaa", "ghayn", "waaw", "ayn", "haa", "khaa", "miim", "7aa", "kaaf",
"jiim", "qaaf", "baa", "faa", "alif", "nuun", "siin", "lam", "zay",
"thaa-1", "raa", "taa-1", "thaal", "daad", "daal", "saad", "thaa-2",
"shiin", "taa-2"] # a list of letters to be used later in the program
# GUI class
class Gui:
def __init__(self):
self.root = Tk(); self.root.title("Letter Learning")
self.setup() # calls the setup function to load all the labels etc
def setup(self):
# top
Label(self.root, text="Generate a new letter:").grid(row=0,column=0)
Button(self.root, text="click me", command=self.pickLetter).grid(row=0,column=1)
def pickLetter(self):
label = {}
letter = random.choice(letters)
path = [f"letters\\{letter}-{x}.jpg" for x in range(4)]
print(path)
for x in range(4):
label[f"image{x}"] = ImageTk.PhotoImage(Image.open(path[x])) # reference to the image
Label(self.root, image=label[f"image{x}"]).grid(row=2, column=x) # putting the image in
As you can see, I used a for loop to iterate over my files (they're saved as <letter-0>
, <letter>-1
etc) and put a label in the window. I saved a reference of the image in a dictionary, as another post said to keep a reference of images that you use, however nothing shows up.
Here is before/after of me loading the images: