Python tkinter:获取OptionMenu下拉列表中的条目数

时间:2018-01-16 20:45:12

标签: python python-3.x tkinter

下面的函数创建一个格式良好的OptionMenu小部件属性列表。但是需要一个kludge,因为OptionMenu 具有“菜单大小”属性(保存下拉列表中的元素数量)。

如何从小部件中提取此值,以便我可以消除kludge(并在下拉菜单中显示每条条目的属性)?

BTW,该功能未列出(非标准)Optionmenu“命令”选项的内容。有关此选项的信息,请参阅tkinter OptionMenu issue (bug?): GUI and program values not kept in lockstep (python 3.x)

的已接受答案
def OptionMenuConfigLister( OptionMenuWidget ) : 
    ''' 
       Uncomment this block to see ALL attributes of the widget
    #
    # Gets the main attributes of the widget (EXCLUDING the attributes for 
    # the  dropdown list and the values in the list)      
    #
    print( " \nOptionMenuWidget.config()\n"  )
    for i, j in enumerate( sorted( OptionMenuWidget.config().items() ) ) :
        print( "   {0:<19} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True )     
    #
    # Gets the attributes of the list portion of the widget (but NOT the entries)   
    #
    print( "\nOptionMenuWidget[ 'menu' ].config().items() :\n" ) 
    for i, j in enumerate( sorted( OptionMenuWidget[ 'menu' ].config().items() ) ) :
        print( "   {0:<18} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True ) 
    '''
    #
    # Get the attributes of each/every entry in the dropdown list
    #
    # TODO: Determine how to get # of items in list          
    #
    for i in range( 0, 1 ) :  ''' <======== KLUDGE '''

        print( "\nOptionMenuWidget[ 'menu' ].entryconfig(" + str( i ) + ").items()) :\n" )
        for _, j in  enumerate( sorted(  
                    OptionMenuWidget[ 'menu' ].entryconfig( i ).items() ) ) :
            print( "   {0:<16} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True )
        print()     
    return

编辑20180117:根据@nae的回答,这是修复 - 用以下代码替换kludge行:

ElementCount = OptionMenuWidget[ 'menu' ].index( 'end' ) + 1
for i in range( 0, ElementCount ) :  

根据@furas的评论,示例代码现在在格式化的打印语句中使用[-1]。

1 个答案:

答案 0 :(得分:2)

根据Menu total index counts和源代码,OptionMenu的{​​{1}}存储为*values项:

Menu

可以使用class OptionMenu(Menubutton): """OptionMenu which allows the user to select a value from a menu.""" def __init__(self, master, variable, value, *values, **kwargs): ... menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu .index('end')的菜单选项提取'菜单大小',如下所示:

OptionMenu