tkinter optionmenu 第一个选项消失 [英] tkinter optionmenu first option vanishes

查看:35
本文介绍了tkinter optionmenu 第一个选项消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ttk optionmenu 小部件从下拉列表中的所有值开始.选择任何值后,列表中的第一个值消失,永远不会重新出现...

A ttk optionmenu widget starts out with all of its values in the dropdown. Upon selecting any value, the first value in the list vanishes, never to reappear...

有人知道为什么吗?这是小部件设计的特征吗?请尝试以下操作:

Does anyone know why? Is this a feature of the widget's design? Try it with the following:

import tkinter.ttk as ttk
import tkinter as tk

a = tk.Tk()

options = ['1', '2', '3']
value = tk.StringVar()

masterframe = ttk.Frame()
masterframe.pack()

dropdown = ttk.OptionMenu(masterframe, value, *options)
dropdown.pack()

a.mainloop()

注意 - 另一个用户在这里问了同样的问题:OptionMenu单击时不会显示第一个选项(Tkinter)

Note - another user asked the same question here: OptionMenu won't show the first option when clicked (Tkinter)

他们似乎找到了解决方法,但不明白为什么会这样.

They seem to've found a workaround, but not understood why it was happening.

更新:实际上这种行为只在使用 ttk 小部件时出现.tk 小部件工作正常(虽然看起来很丑).

UPDATE: actually this behaviour only appears when using the ttk widget. The tk widget works fine (albeit looking very ugly).

推荐答案

ttk.OptionMenu 命令的签名是这样的:

The signature of the ttk.OptionMenu command is this:

def __init__(self, master, variable, default=None, *values, **kwargs):

这是文档字符串:

"""构造一个主题的 OptionMenu 小部件,以 master 为父级,资源 textvariable 设置为变量,初始选择的值由默认参数指定,菜单值由*值和其他关键字.

"""Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords.

注意值列表之前的 default 选项.不要在值列表中添加一个空白项,而是添加您想要的任何值作为默认值:

Notice the default option which comes before the list of values. Instead of adding a blank item to the list of values, add whichever value you want as the default:

options = ['1', '2', '3']
dropdown = ttk.OptionMenu(masterframe, value, options[1], *options)

这篇关于tkinter optionmenu 第一个选项消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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