是否有任何可以嵌套的Tkinter Widgets如OptionMenu?

时间:2014-06-23 01:10:39

标签: python drop-down-menu tkinter nested optionmenu

我正在尝试使用类似OptionMenu的列表选择器,但我希望有嵌套选项。我希望它们就像嵌套菜单(File-> Save)一样,但我需要对它进行网格化。

如果这是不可能的(没有编写自定义小部件),我将最终有两个选择器,第一个选择“主菜单”,第二个处理“子菜单”,但我真的喜欢避免这样做。

2 个答案:

答案 0 :(得分:4)

Am optionmenu只是一个便利功能,可以创建菜单按钮和菜单。你可以很容易地做到这一点。这是一个例子:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        items = {"one": ["a","b","c"],
                 "two": ["d","e","f"],
                 "three": ["g","h","i"]}

        self.the_value = tk.StringVar()
        self.the_value.set("a")

        self.menubutton = tk.Menubutton(self, textvariable=self.the_value, indicatoron=True)
        self.topMenu = tk.Menu(self.menubutton, tearoff=False)
        self.menubutton.configure(menu=self.topMenu)

        for key in sorted(items.keys()):
            menu = tk.Menu(self.topMenu)
            self.topMenu.add_cascade(label=key, menu=menu)
            for value in items[key]:
                menu.add_radiobutton(label=value, variable = self.the_value, value=value)

        self.menubutton.pack()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

答案 1 :(得分:2)

改进上述代码以支持更长的菜单。享受递归。

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):

        def create_menu( top_info, top_menu, value_var):
            if isinstance(top_info, dict):
                print "Evaluating dictionary with keys:"
                for key in top_info.keys():
                    print 'Key:' + key
                    menu = tk.Menu(top_menu)
                    top_menu.add_cascade(label=key, menu=menu)
                    create_menu(top_info[key], menu, value_var)
                return
            else:
                print "Evaluating list of values:"
                for value in top_info:
                    print 'Value:' + value
                    top_menu.add_radiobutton(label=value, variable = value_var, value=value)
                return

        tk.Frame.__init__(self, parent)

        items = {"one": {"a":["aa","aaa","aaaa"],"b":["bb","bb"],"c":["cc"] },
                 "two": ["d","e","f"],
                 "three": ["g","h","i"]}

        self.the_value = tk.StringVar()
        self.the_value.set("a")

        self.menubutton = tk.Menubutton(self, textvariable=self.the_value, indicatoron=True)
        self.topMenu = tk.Menu(self.menubutton, tearoff=False)
        self.menubutton.configure(menu=self.topMenu)

        create_menu(items, self.topMenu, self.the_value)

        self.menubutton.pack()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()