Search code examples
pythontkinteroptionmenu

In Python Tkinter, how do I set an OptionMenu to a fixed size shorter than the longest item?


As simple as it sounds, I have an Option menu with some 5 character terms and one very long one. When the long option is selected, the window stretches out and it looks atrocious. Setting the width or sticky=EW only works if that width is greater than the length of the longest term.

Ideally, I'd like to show 15 characters max followed by a "..." if it is longer.

Any ideas? Thanks.


Solution

  • I think you're looking for the more powerful "Combobox" in ttk (also in standard python as simple extensions to Tk).

    As effbot puts it

    The option menu is similar to the combobox

    For example:

    from tkinter.ttk import Combobox # python 3 notation
    combo = Combobox(root,values=['a','aa','aaaaa','aaaaaaa'],width=3)
    

    It will simply cut off the elements that are too long

    (If you're in python 2 it's slightly different to import ttk)

    If you want a nice "..." to appear when cutting off entries, I think you're best bet is to

    elements = ['a','aa','aaaaaaaa']
    simple_values = [ e[:3] + ('...' if len(e) > 3 else '') for e in elements]
    combo = Combobox(root,values=simple_values )
    

    If you need to be able to map between them, use your favorite data structure or reference by index not value in the combobox