Sort a Tkinter optionmenu alphabetically? Sort a Tkinter optionmenu alphabetically? tkinter tkinter

Sort a Tkinter optionmenu alphabetically?


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


Thankfully, this solution is fairly simple and intuitive. All you have to do is add in a sorted() when you pass the argument:

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

Just make sure you put the sorted() inside the * splat operator as sorted() needs to be applied to a list such as your data variable but with sorted(*data)it actually treats *data as a bunch of individual variables so sorted()won’t work.