0

I wanted to display a picture .png in tkinter when calling a function (but it could also be with a boolean showOnOff).

This is what I wrote for the moment, but the picture doesn't appear. Do you have any idea ?

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

root = Tk()

def display():
    # Use library PIL to display png picture
    path = '3d.png'
    img = ImageTk.PhotoImage(Image.open(path), Image.ANTIALIAS)
    panel = Label(root, image = img)
    panel.grid(row=1, column=0)

ButtonDisplay = ttk.Button(root, text="Display", command=display)
ButtonDisplay.grid(row=0, column=0)

root.mainloop()
Mo0nKizz
  • 149
  • 7
  • Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – acw1668 Aug 20 '20 at 07:55
  • Just partially because the image that I display is created in the function that I called (which not appear in the code) – Mo0nKizz Aug 20 '20 at 07:58
  • The cause of the issue is the same. – acw1668 Aug 20 '20 at 08:00

1 Answers1

1

The problem is the definition of the image which is only local inside the funtion. If you make the image global, it works:

def display():
    global img
    # Use library PIL to display png picture
    path = '3d.png'
    img = ImageTk.PhotoImage(Image.open(path))
    panel = Label(root, image=img)
    panel.grid(row=1, column=0)
Martin Wettstein
  • 2,771
  • 2
  • 9
  • 15