![](/img/trans.png)
[英]How do I populate tkinter drop-down box with data retrieved from my SQLite database?
[英]How can I dynamic populate an option widget in tkinter depending on a choice from a drop down menu?
我的問題如下:我有幾個文件,我已經創建了一個帶有名稱的下拉菜單,接下來我需要的是一個選項菜單,只要選擇文件名以顯示特定文件中的某些數據,就可以更改選項。要清楚,我的問題只是關於如何在選擇下拉選項時更改選項菜單。感謝任何幫助。
OptionMenu小部件只不過是一個便利類,可以創建與菜單相關聯的菜單按鈕。 您可以通過"menu"
屬性訪問此菜單。 唯一的技巧是知道菜單項應該做什么,這只不過是設置相關變量的值。
這是一個例子:
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.om_variable = tk.StringVar(self)
b1 = tk.Button(self, text="Colors", width=8, command=self.use_colors)
b2 = tk.Button(self, text="Sizes", width=8, command=self.use_sizes)
self.om = tk.OptionMenu(self, self.om_variable, ())
self.om.configure(width=20)
self.use_colors()
b1.pack(side="left")
b2.pack(side="left")
self.om.pack(side="left", fill="x", expand=True)
def _reset_option_menu(self, options, index=None):
'''reset the values in the option menu
if index is given, set the value of the menu to
the option at the given index
'''
menu = self.om["menu"]
menu.delete(0, "end")
for string in options:
menu.add_command(label=string,
command=lambda value=string:
self.om_variable.set(value))
if index is not None:
self.om_variable.set(options[index])
def use_colors(self):
'''Switch the option menu to display colors'''
self._reset_option_menu(["red","orange","green","blue"], 0)
def use_sizes(self):
'''Switch the option menu to display sizes'''
self._reset_option_menu(["x-small", "small", "medium", "large"], 0)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
由於OptionMenu提供了一個命令選項,我建議繼續引用已經給出的命令(如果有的話)並以這種方式將其傳遞給新選項:
參加,變量基於以前的答案
def __init__(self, *args, **kwargs):
...
self.command=kwargs['command']
...
def _reset_option_menu(options, index=None):
...
menu.add_command(label=string,
command=lambda:self.command(),
value=self.om_variable.set(string))
...
希望它有任何用途Btw,真的很有用Bryan Oakley給出的答案,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.