0

I have a problem trying to display an image using Tkinter. I have 3 files in a folder called filename1, filename2 and filename3. I want to display them by using two different buttons. filename1 is supposed to be shown without clicking a button, and then filename2 and filename3 should be shown by clicking the other buttons. However, this doesn't work.

What ends up happening, is that only filename3 is loading, and none of the button works. I have no idea why this is happening. This is the code I've tried:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

root.geometry("1000x500")
root.resizable(width=True, height=True)

def open_img(name):
    filepath = fr"C:\Users\me\Desktop\folder/{name}.jpg"
    img = Image.open(filepath)
    img = img.resize((1000, 500), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.grid(row = 2, column=1)

open_img(filename1)    
    
btn1 = Button(root, text='open image1', command=open_img("filename2")).grid(row=3, column=1)
btn2 = Button(root, text='open image2', command=open_img("filename3")).grid(row=4, column=1)
    
root.mainloop()

This is the result, and filename3 is only shown. The buttons do not work. What am I doing wrong here?

enter image description here

peterlravn
  • 43
  • 8
  • You know that `btn1` and `btn2` will always be `None`. For more info read [this](https://stackoverflow.com/a/66385069/11106801) – TheLizzard Mar 06 '21 at 22:58

1 Answers1

1

When you create the buttons you run the command because you end it with paranthesis.

command=open_img("filename2")

To assign a function with a parameter you can use a lambda function:

command=lambda: open_img("filename2")
figbeam
  • 7,001
  • 2
  • 12
  • 18