Search code examples
pythonsortingtkinteroptionmenu

Sort a Tkinter optionmenu alphabetically?


I'm trying to make an OptionMenu in Tkinter that lists it's data Alphabetically, but I have no idea how.

This is my code for the OptionMenu data set. (This will expand as I develop the program).

data={
'Actually Additions Atomic Reconstructor',
'Advanced Mortars',
'Artisan Worktables',
'Extra Utilities Crusher',
'Extra Utilities Resonator',
'Initial Inventory',
'JEI Hide',
'JEI RemoveAndHide',
'Ore Dictionary Add',
'Ore Dictionary Create',
'Ore Dictionary Remove',
'Seed Drops'
}

And this is my code for the OptionMenu.

var = tkinter.StringVar()
var.set('Advanced Mortars')
p = tkinter.OptionMenu(window, var, *data)
p.config(font='Helvetica 12 bold')
p.pack()

Every time I run the code and open the OptionMenu, everything is scrambled randomly. How do I sort this alphabetically?


Solution

  • Since data is a set, which is an unordered collection in python, the data will always be scrambled. Since data already looks sorted, an easy way to fix this is to change data to a list, which is an ordered collection:

    data=[
         'Actually Additions Atomic Reconstructor',
         'Advanced Mortars',
         ...
         ]
    

    If your data has to be a set to begin with, you could also sort it beforehand with sorted():

    data = sorted(data)
    

    Your code runs fine when I run this:

    from tkinter import *
    
    data={
          'Actually Additions Atomic Reconstructor',
          'Advanced Mortars',
          'Artisan Worktables',
          'Extra Utilities Crusher',
          'Extra Utilities Resonator',
          'Initial Inventory',
          'JEI Hide',
          'JEI RemoveAndHide',
          'Ore Dictionary Add',
          'Ore Dictionary Create',
          'Ore Dictionary Remove',
          'Seed Drops'
         }
    
    data = sorted(data)
    
    master = Tk()
    
    var = StringVar(master)
    var.set('Advanced Mortars')
    p = OptionMenu(master, var, *data)
    p.config(font='Helvetica 12 bold')
    p.pack()