Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - tkinter optionmenu first option vanishes

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The signature of the ttk.OptionMenu command is this:

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

This is the docstring:

"""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.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...