0

The following code prompts for the filename of an image, and then when the display button is pressed, it displays the image. If the “print(xyz)” line is uncommented, it throws an error that xyz is undefined, but the image does get displayed. If the line is commented, it of course does not throw an error, but the image does not display. Any line of code there that throws an error allows the image to be displayed. Any help will be greatly appreciated!

Wayne

from tkinter import *
from PIL import ImageTk,Image

def sho_pic():
    fname = image_entry.get()
    photo = Image.open(f"C:\inetpub\wwwroot\web_gift\{fname}")
    myimage = ImageTk.PhotoImage(photo)
    canvas.create_image(300, 300, image=myimage)

    #print(xyz)  <-----------------------

window = Tk()
window.geometry('800x500')
canvas = Canvas(window,width=1000, height=1000)
canvas.pack()

label_image = Label(text="Image Filename: ")
label_image.place(x=20,y=20)

image_entry = Entry(width=32)
image_entry.place(x=150,y=20)

display_button = Button(window, command=sho_pic, text="Display")
display_button.place(x=350,y=20)

window.mainloop()
Barmar
  • 741,623
  • 53
  • 500
  • 612
UliB
  • 1
  • it is because when it throws an error while running that function it doesn't finish so the image doesn't get garbage collected, so basically You need to keep a reference to that image for example append it to a list outside that function. This is the issue: [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) – Matiiss Jun 17 '21 at 18:18
  • A thousand thanks! I'll learn this language yet! – UliB Jun 17 '21 at 19:04

0 Answers0