根据下拉菜单中的选项,如何在tkinter中动态填充选项小部件?

2024-05-01 21:48:43 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

由于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))                         
        ...

希望它有用 顺便说一下,布莱恩·奥克利给出的答案真的很有用

OptionMenu小部件只不过是一个创建与菜单关联的menubton的便利类。您可以通过"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()

相关问题 更多 >