tkinter 选项菜单 - 即时更新选项 [英] tkinter option menu - update options on fly
问题描述
我正在使用 Tkinter 和 Python 2.7.6 创建一个 GUI.
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")
在用户选择一个目录后,我调用一个函数 onEnterDir()
,然后它会获取该目录中的文件列表.所以,我有一个名为 dirFiles
的变量中的文件列表.
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
.
我想要的是使用此 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?
我的问题与这里的其他人不同,因为我只想更新 self.dropdown
显示的项目列表.它不依赖于任何其他小部件.我有一个想要放入的内容的 Python 列表.我该怎么做?
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?
推荐答案
您可以在 您在问题中提到的答案:
例如:
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()
这篇关于tkinter 选项菜单 - 即时更新选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!