0

For a school project i am designing an application in Tkinter. It will be an exam question browser that will allow students to view question papers. Currently i am trying to find a way to dynamically embed images from a list into a text widget. The following code is what i am currently using to find a solution.

from tkinter import *
from PIL import Image, ImageTk

im = []
im.append("mary.jpg")
im.append("sherm.jpg")
im.append("bean.jpg")
class Window(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)

        self.master = master
        self.start_window()

    def start_window(self):
        self.master.title("question browser")
        self.pack(fill=BOTH, expand=1)

        D = Text(self)
        x = 0
        for i in (im):
            imgs = Image.open(im[x])
            mi = ImageTk.PhotoImage(imgs)
            D.image_create(END, image = mi)
            x = x + 1

        D.pack()
        D.config(state=DISABLED)

root = Tk()

app = Window(root)
root.mainloop()  

no error message is being output, just a blank box. which i believe is due to the fact that i am not keeping a reference to the image. i am struggling to find a solution to this problem, since the actual program will be working with lots of images. therefore it is not possible to create a global variable to store a reference to each individual image (e.g: Global Variable = Image.open("image.jpg")). help would be greatly appreciated.

I can install other modules if required.

L.jakob
  • 21
  • 3

1 Answers1

1

the following code now works, the solution was to create a ...global array... (i guess that's what it's called) and then, during the for i in (im) loop - after mi = ImagesTk.PhotoImage(imgs)- I appended the variable "mi" to the global list.

from tkinter import *
from PIL import Image, ImageTk

images = []

class Window(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)

        self.master = master
        self.start_window()

    def start_window(self):
        self.master.title("question browser")
        self.pack(fill=BOTH, expand=1)

        im = []
        im.append("mary.jpg")
        im.append("sherm.jpg")
        im.append("bean.jpg")
        D = Text(self)
        x = 0
        for i in (im):
            imgs = Image.open(im[x])
            mi = ImageTk.PhotoImage(imgs)
            images.append(mi)
            D.image_create(END, image = mi)
            x = x + 1
        D.pack()
        D.config(state=DISABLED)

root = Tk()

app = Window(root)
root.mainloop()
L.jakob
  • 21
  • 3
  • 2
    You should also be able to create your `images` list as an attribute to your frame as well, in its `__init__`. – Nae Jan 29 '18 at 20:41