简体   繁体   中英

Tkinter - Only show filled values of an array in a OptionMenu

I've the following code:

self.array_lt = ['foo', 'bar', '', 'moo']
var = StringVar()
self.menult = OptionMenu(randomwindow, var, *self.array_lt)
self.menult.config(width=30)
self.menult.grid(row=0, column=0, padx=(5,5), pady=(5,5))

This shows me a OptionMenu with the four values, foo , bar , (the empty space) and moo .

How can I show the OptionMenu without showing the empty value of the array? In another words, I want to show only foo , bar and moo on the OptionMenu and ignore the empty space.

The array_ly is just an example, I would like to have something general to ignore always the blank spaces.

Thanks in advance.

You can use filter with None as the filter function to filter out values that would evaluate to False when interpreted as a boolean:

>>> filter(None, ["1", 0, " ", "", None, True, False, "False"])
['1', ' ', True, 'False']

Use this when you pass the list to the OptionMenu

self.menult = OptionMenu(randomwindow, var, *filter(None, self.array_lt))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM