0

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()
James P.
  • 41
  • 5
  • Not function also the option menu – James P. Apr 22 '21 at 13:37
  • 1
    @TheLizzard `tk._setit` is a class, not a function. Its behavior is similar to `partial()`. – acw1668 Apr 22 '21 at 14:44
  • Not function also the option menu that I build after click update button – James P. Apr 22 '21 at 14:48
  • You have used another tkinter `StringVar` (`tkvar`) for the updated file list but without using `.trace()` on it (like on `variable`). – acw1668 Apr 22 '21 at 15:21
  • @acw1668 My bad. Also wouldn't that be bad practise because in the doc string it says that it is internal so it should be used by OP – TheLizzard Apr 22 '21 at 15:50
  • I changed tkvar with variable and the new optionmenu function. When I write command=tk._setit(variable.trace("w", change_image), item) give me an error: str object as no attribute set – James P. Apr 23 '21 at 07:31
  • I think it should be `command=tk._setit(variable, item, change_image)`. – acw1668 Apr 26 '21 at 05:44

0 Answers0