如何根据下拉菜单中的选择动态填充 tkinter 中的选项小部件? [英] How can I dynamic populate an option widget in tkinter depending on a choice from a drop down menu?

查看:23
本文介绍了如何根据下拉菜单中的选择动态填充 tkinter 中的选项小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题如下:我有几个文件,我制作了一个带有名称的下拉菜单,接下来我需要的是一个选项菜单,只要选择文件名以显示来自特定文件作为选项.要清楚,我的问题只是关于如何在选择下拉选项时更改选项菜单.感谢您的帮助.

my problem is the following: I have several files and I have made a drop down menu with the names,the next thing I need is an option menu which can be changed whenever a file name is selected to show some data from the specific file as option.To be clear,my question is only about how to make the option menu change when a choice from the drop down is selected.Thanks for any help.

推荐答案

OptionMenu 小部件只不过是一个创建与菜单关联的菜单按钮的便利类.您可以通过 "menu" 属性访问此菜单.唯一的技巧是知道菜单项应该做什么,这只不过是设置关联变量的值.

The OptionMenu widget is nothing more than a convenience class that creates a menubutton that is associated with a menu. You can get at this menu via the "menu" attribute. The only trick is to knowing what the menu items should do, which is nothing more than setting the value of the associated variable.

这是一个例子:

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()

这篇关于如何根据下拉菜单中的选择动态填充 tkinter 中的选项小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆