I have took your code and made some changes here:
import os
from PIL import ImageTk, Image
import tkinter
root = tkinter.Tk()
folder_list = os.listdir(r"C:\Users\Teknoloji\Desktop\Phyton\Jack\Selam")
def Imagen(img_path):
img = ImageTk.PhotoImage(Image.open(f'images/{img_path}'))
#label = tkinter.Label(image=img)
image.whatever = img #keeping a reference, can be anything
image.itemconfigure('image',image=img)
image.pack()
for i in folder_list:
button = tkinter.Button(root,text=i,command=lambda i=i:Imagen(i),width=10)
button.pack(pady=5)
image = tkinter.Canvas(root,width=300,height=300)
image.create_image(120,120,tag='image')
root.mainloop()
What all have I done?
I've removed some unwanted part from your code, like unnecessary looping inside of function and also it seems like your not using your label to display image instead using canvas
, either way ive made sure that it does not overwrite the existing image, when you press button.
Also I have passed the image path as a parameter onto the function which opens the image, so that lambda
can have a parameter to pass on to the function.
How does the loop button work?
(Taken from here)
This may look magical, but here's what's happening. When you use that lambda to define your function, the open_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying "I should look for what the value of the variable i is at the time that I am called". Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop.
Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later.
Do let me know if this works.
Do let me know if you have any doubts or error regarding this.
Cheers