I'm creating a GUI using Tkinter with Python 2.7.6.
I have a drop down menu, created and initially disabled with the following code:
self.dropdown = Tkinter.OptionMenu(self, self.dropdownVar, "Select SED...")
self.dropdown.grid(column=0,row=1)
self.dropdown.configure(state="disabled")
After a user selects a directory, I call a function onEnterDir()
which then gets a list of files in that directory. So, I have a list of files in a variable called dirFiles
.
What I want is to then update the options in the dropdown menu with the items in this dirFiles
list. How would I do this?
My question is different to others on here because I just want to update the list of items self.dropdown
displays. It's not dependent on any other widget. I have a python list of things I want to put in. How do I do this?
You can use the same technique in the answer you mentioned in question:
For example:
import os
from functools import partial
from Tkinter import *
from tkFileDialog import askdirectory
def onEnterDir(dropdown, var):
path = askdirectory()
if not path:
return
filenames = os.listdir(path)
dropdown.configure(state='normal') # Enable drop down
menu = dropdown['menu']
# Clear the menu.
menu.delete(0, 'end')
for name in filenames:
# Add menu items.
menu.add_command(label=name, command=lambda name=name: var.set(name))
# OR menu.add_command(label=name, command=partial(var.set, name))
root = Tk()
dropdownVar = StringVar()
dropdown = OptionMenu(root, dropdownVar, "Select SED...")
dropdown.grid(column=0, row=1)
dropdown.configure(state="disabled")
b = Button(root, text='Change directory',
command=lambda: onEnterDir(dropdown, dropdownVar))
b.grid(column=1, row=1)
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With