0

我在一个文件夹中有三个图像:Image1、Image2、Image3,我创建了一个带有如下图像的选项菜单:

在此处输入图像描述

如果我插入另一个 image4 而不是 image1 并单击更新按钮,那么我有:

在此处输入图像描述

我无法使用更新文件列表按钮更新图像。我的代码在下面,我不知道如何更新 refresh_list 功能

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()
4

0 回答 0