Tkinter Update Button for an Optionmenu with images

197 Views Asked by At

I have three images in a folder: Image1, Image2, Image3 and I created an option menu with images like this:

enter image description here

If I insert another image4 instead of image1 and click update button then I have:

enter image description here

I can't how update the images with update file list button. My code is below and I don't know how update refresh_list function:

import tkinter as tk
import os

root = tk.Tk()

root.geometry("500x500")

tkvar = tk.StringVar()

variable = tk.StringVar()

def change_image(*args):
    # Change image of label accordingly
    label.config(image=photos[int(variable.get()[0])])

pathimages = 'img/' 
files = [os.path.splitext(filename)[0] for filename in os.listdir(pathimages)]


OptionMenu1 = tk.OptionMenu(root, variable, *files)
OptionMenu1.config(font=("Times", 16, "italic"))
OptionMenu1["menu"].config(font=("Times", 16, "italic"))
OptionMenu1.place(x=100,y=130)

variable.trace("w", change_image)

photos = os.listdir("img/")    
photos = list(filter(lambda f: f.endswith('.png'), photos))

photo0 = (photos[0])
photo1 = (photos[1])
photo2 = (photos[2])



# List of photoimages for each image
photos =(tk.PhotoImage(file='img/'+photo0), tk.PhotoImage(file='img/'+photo1), tk.PhotoImage(file='img/'+photo2))
label = tk.Label(root, image=photos[0])
label.place(x=100,y=170)

def refresh_list():
    pathimages2 = 'img/'
    new_list = [os.path.splitext(filename)[0] for filename in os.listdir(pathimages2)]
    OptionMenu1['menu'].delete(0, 'end')
    for item in new_list:             
        OptionMenu1['menu'].add_command(label=item, command=tk._setit(tkvar, item))
        

update_button2 = tk.Button(root, text="Update files list", command=refresh_list, bg='lightgreen', width=25, font=("bold",15))
update_button2.place(x=100,y=25)

root.mainloop()
0

There are 0 best solutions below