У меня есть этот код:
from tkinter import *
import os
import glob
from PIL import Image, ImageTk
root = Tk()
tkvar = StringVar()
# Directory
directory = "C:/Users/label/Desktop/test folder/"
choices = glob.glob(os.path.join(directory, "*jpg")) # all choices ending with .jpg in the directory above
# Images, placing the image onto canvas
def change_dropdown():
imgpath = tkvar.get()
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#widgets
msg1 = Label(root, text = "Choose here")
msg1.grid(column = 0, row = 0)
popupMenu = OptionMenu(root, tkvar, *choices) #Dropdown menu of all sign off Sheets that need signing
popupMenu.grid(row=1, column=0)
display_label = label2 = Label(root, image=None)
display_label.grid(row=2, column=0, rowspan = 200)
open_button = Button(root, text="Open", command=change_dropdown) # opens the directory and opens selected image
open_button.grid(row=20, column=0)
root.mainloop()
Что он делает:
Это простое приложение, которое позволяет мне щелкнуть каталоги откройте изображение.
Моя проблема:
Если я удаляю один из файлов .jpg
из папки, как я могу обновить значения optionMenu, чтобы они соответствовалитекущая папка? Потому что, если я удаляю файл при запуске скрипта, меню параметров не обновляется автоматически
Вот код, который я пробовал из Обновление OptionMenu из списка , но это не такничего не обновлять ..
from tkinter import *
import os
import glob
from PIL import Image, ImageTk
root = Tk()
tkvar = StringVar()
# Directory
directory = "C:/Users/label/Desktop/test folder/"
choices = glob.glob(os.path.join(directory, "*jpg")) # all choices ending with - to sign.jpg in the directory above
tkvar.set('...To Sign Off...') # set the default option
# Images, placing the image onto canvas
def change_dropdown():
imgpath = tkvar.get()
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
#widgets
msg1 = Label(root, text = "Choose here")
msg1.grid(column = 0, row = 0)
popupMenu = OptionMenu(root, tkvar, *choices) #Dropdown menu of all sign off Sheets that need signing
popupMenu.grid(row=1, column=0)
display_label = label2 = Label(root, image=None)
display_label.grid(row=2, column=0, rowspan = 500)
open_button = Button(root, text="Open", command=change_dropdown) # opens the directory and opens selected image
open_button.grid(row=502, column=0)
def update_option_menu():
menu = popupMenu["menu"]
menu.delete(0, "end")
for string in choices:
menu.add_command(label=string,
command=lambda value=string: tkvar.set(value))
update_button = Button(root, text='Update option menu', command=update_option_menu)
update_button.grid(column=0, row=2)
root.mainloop()