-2

I have a simple GUI tryout where I want to display few images on my screen. I start with setting the window with gray squares allover it and resizing the desired image and now I want to put it on the frame:

img = [img_resize(yellow_square, img_size), "text"]

base_panel = Label(root, image = img[0])
base_txt   = Label(root, text =  img[1])
base_panel.grid(row = x, column = y)
base_txt.grid  (row = x, column = y)
...
for im in ls:
    panel = Label(root, image = im[0])
    panel.grid(row = x+im[1][1], column = y+im[1][2])    

    txt = Label(root, text =  im[2])
    txt.grid(row = x+im[1][1], column = y+im[1][2], sticky = 'S')

ls is a list [image (using Image.open(img)), location offset, text]

When I copy these lines to my main script, it all goes well and I get the desired images

but when trying to do so from a function, I only get the text part to work

I guess something is wrong with my image = ... but I don't understand what, as I have the code working after I just copied these lines to main. The main has another image, so maybe this is affecting somehow?

This is the code from main:

for im in background: # background is a list of gray squares
# some manipulation an a,b

panel = Label(root, image = im)
panel.grid(row = a, column = b)

Here should come the function call or the lines themselves

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

1 Answers1

1

This is a common problem. You have to keep a reference to the image, or else python deletes it from memory. If you aren't in a function then the variable is a global variable, which keeps the reference. But in a function you need to do something like this:

panel = Label(root)
panel.img = im[0]
panel.config(image = panel.img)
Novel
  • 13,406
  • 2
  • 25
  • 41
  • string don't need the same handle? why? – CIsForCookies Jun 04 '17 at 06:16
  • Because strings are immutable. – Novel Jun 04 '17 at 06:28
  • another thing (unrelated). How is it that I can use _root_ safely from within the function without declaring first _global root_? – CIsForCookies Jun 04 '17 at 08:18
  • 1
    You can *read* global variables anywhere in the code without any special steps. Python basically assumes they are constants. You only need to declare `global` when you want to write the variable. But you shouldn't be using globals for reading or writing. Global variables are a known evil in all programming languages. Get away from them – Novel Jun 04 '17 at 16:47