0

I'm having a weird issue with the tkinter script below. If the outcommented lines are executed, it is showing the image like intended. When I call the function instead, it doesn't. The main window i opened and nothing else happens. 'Function called' is being printed in the Shell though. Am I missing something basic about tkinter and/or functions here? I found some reports about weird behavior with IDLE which I'm using as well, could that be the reason?

Yesterday I had some issues because I called the file tkinter.py, same as the module but in a different folder. Like a few more persons, that resulted in problems opening the scripts with IDLE. I wrote a new file with the code below and the problem persisted.

from tkinter import *
import tkinter as tk
from PIL import Image, ImageTk
from pathlib import Path

window = Tk()

window.title('xy')
window.geometry('600x400')

path = Path("C:/Python/png/")

def function_a():
    print('function called')
    img = Image.open(str(path)+'\\'+'pic'+'.png')
    img = img.resize((300,200), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    background_label = tk.Label(window, image=img)
    background_label.pack()

function_a()

##img = Image.open(str(path)+'\\'+'pic'+'.png')
##img = img.resize((300,200), Image.ANTIALIAS)
##img = ImageTk.PhotoImage(img)
##background_label = tk.Label(window, image=img)
##background_label.pack()

window.mainloop
nbe9
  • 3
  • 2
  • `window.mainloop` needs to be `window.mainloop()`. Also, https://stackoverflow.com/questions/16424091 – Bryan Oakley Apr 05 '20 at 16:09
  • Thank you. Shame on me for not finding that, searched for >1h without using the 'image' tag, that would probably have done it. ;-) – nbe9 Apr 05 '20 at 17:13

1 Answers1

0

The photo img gets removed by garbage collection because it is a local variable. To fix this add background_label.img = img at the end of the function, this stops the image from being removed by garbage collection.