Python tkinter:获取 OptionMenu 下拉列表中的条目数 [英] Python tkinter: Getting the number of entries in an OptionMenu dropdown list

查看:62
本文介绍了Python tkinter:获取 OptionMenu 下拉列表中的条目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数创建一个 OptionMenu 小部件的所有属性的格式良好的列表.然而,需要混杂,因为 OptionMenu 没有具有菜单大小"'属性(保存下拉列表中的元素数量).

The function below creates a nicely formatted list of all attributes of an OptionMenu widget. However a kludge is needed because OptionMenu does not having a "Menu size"' attribute (that holds the number of elements inside the dropdown list).

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

How do I extract this value from the widget so I can eliminate the kludge (and show the attributes of EVERY entry in the drop-down menu) ?

顺便说一句,该函数没有列出(非标准)Optionmenu命令"选项的内容.有关此选项的信息,请参阅 tkinter OptionMenu 问题(错误?):GUI 和程序值未保持同步(python 3.x) )

BTW, The function does not list the contents of the (non-standard) Optionmenu "command" option. For info on this option see the accepted answer to 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

EDIT 20180117:这是基于@nae 的回答的修复 - 将 kludge 行替换为:

EDIT 20180117: Here's the fix, based on the answer by @nae - replace the kludge line with:

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

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

And as per comment by @furas, sample code now uses [ -1 ] in the formatted print statements.

推荐答案

基于菜单总索引计数并来自源代码,OptionMenu*values 存储为 Menu 项的事实:

Based on Menu total index counts and from the source code, the fact that OptionMenu's *values are stored as Menu items:

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 的菜单选项提取 'Menu Size',如下所示:

One can extract the 'Menu Size' using .index('end') for OptionMenu's menu option like the following:

import tkinter as tk

root = tk.Tk()

opt_var = tk.IntVar()
opt = tk.OptionMenu(root, opt_var, 3, 2, 3, 5, 4)
opt.pack()

print(opt['menu'].index('end') + 1) # basically len(*values) + len(value)

root.mainloop()

这篇关于Python tkinter:获取 OptionMenu 下拉列表中的条目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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