简体   繁体   中英

Python, Tk and OptionMenu: how to sort a drop down list?

I want to make a drop down list with tk and OptionMenu. I want to show a string to the user ("10 us", "40 us"...) and return a number (0, 1,...) which is a parameter that I send to a variable. It works well, but it's not sorted. I want to sort the list like the variable "lst1".

在此处输入图片说明

It should be:

  • 10 us
  • 20 us
  • 40 us
  • 80 us

     lst1 = {"10 us": 0, "20 us": 1, "40 us": 2, "80 us": 3, "160 us": 4, "320 us": 5, "640 us": 6, "1.28 ms": 7, "2.56 ms": 8, "5.12 ms": 9, "10.24 ms": 10} var_tc = StringVar() var_tc.set("40 us") list_tc = OptionMenu(frame, var_tc, *lst1.keys()) list_tc.config(takefocus=1) list_tc.grid(row=10, column=1, padx=2, pady=10) param.tc = lst1[var_tc.get()] 

Could you help me, please? :)

The issue is that you're using a dictionary as a list, and dictionaries don't have any notion of order. Two ways you could do it; both are pretty straightforward.

Way 1: Just use sorted keys

You don't have to change much, just when you pass in lst1.keys() , you instead pass in sorted(lst1.keys()) , since keys() returns a list and you can give a sorted one of those.

Way 2: Use a dictionary that keeps order

One of the python standard libraries is collections , which contains many containers of varying usefulness. One of these is the OrderedDict , a dictionary that keeps the order in which you enter things. You would import it as from collections import OrderedDict , and initialize it as any other object - lst1 = OrderedDict([("10us",0), ("20us",1), ...])

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