0

I was trying to show the image when I clicked the button however it failed( the program does not report an error but the image is still not displayed). I'm sure I put the right path to the picture. This is code

import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
def def_btn1():
    image1 = Image.open("csdl.png")
    image1 = image1.resize((710, 400), Image.ANTIALIAS)
    test = ImageTk.PhotoImage(image1)
    lbl2 = tk.Label(image=test)
    lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command=def_btn1)
btn1.pack()
window = tk.mainloop()

I want when I click the button the image will show in the program. Thank you!

Ngoc Anh
  • 21
  • 4

1 Answers1

1

You need to add lbl2.image = test for the image to not be destroyed by tkinter, you new code should be this -

import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk() # You might want to move this line below your functions, with the other global variables
def def_btn1():
    image1 = Image.open("csdl.png")
    image1 = image1.resize((710, 400), Image.ANTIALIAS)
    test = ImageTk.PhotoImage(image1)
    lbl2 = tk.Label(image=test)
    lbl2.image = test # You need to have this line for it to work, otherwise it is getting rid of the image. the varibale after the '=' must be the same as the one calling "ImageTk.PhotoImage"
    lbl2.pack()
btn1 = tk.Button(text="click to show", relief=tk.RIDGE, width=15, font=(12),command= lambda : def_btn1()) # adding 'lambda :' stops the function from running straight away, it will only run if the button is pressed
btn1.pack()
window = tk.mainloop()
t0mas
  • 127
  • 14