0

I'm trying to show picture using Tkinter, Python

It's working well in plain code, but is not in function

Code:

import time
from tkinter import *
from PIL import Image, ImageTk

def test():
    global imageTk # fixes the problem
    size = (100, 100)
    picture = Image.open("C:\download\picture.jpg")
    picture = picture.resize(size)
    imageTk = ImageTk.PhotoImage(picture)
    canvas.create_image(60, 60, anchor=CENTER, image=imageTk)
    
tk = Tk()
canvas = Canvas(tk, width=1000, height=1000)
canvas.pack()


# doesn't show image
test()

tk.mainloop()

Why code in test() function is not working, but the same code in main part is?

P.S. I checked this question: Why does Tkinter image not show up if created in a function?

Adding global to image variable to save it from GC is a solution

  • I added global word to save variables from GC, but it doesn't help Did I this in the wrong way? – Dmitry Vinogradov Jul 05 '22 at 16:43
  • How do you know if it's working or not? You mentioned the code at the top level of your script (not within your function) IS working. Have you tried removing the working part (everything under `# shows image` except for `tk.mainloop()`) after adding `global`s? – Axe319 Jul 05 '22 at 16:50
  • 1
    Yes, you are right. If I remove the second part or rename variables in it, the function is working well Thanks! – Dmitry Vinogradov Jul 05 '22 at 16:57

1 Answers1

0

I checked this question: Why does Tkinter image not show up if created in a function??

Adding global to image variable to save it from GC is a solution

Thanks, Axe319