Search code examples
pythontkinteroptionmenu

Can you have a TKinter drop down menu that can jump to an entry by typing?


I have my OptionMenu setup but it's a very long list (every FBS football team) and takes forever to scroll through. Is there a way that I can setup the menu so that I can start typing a team name and it jumps to that section of the OptionMenu? Also, if there's a way to automatically select it when enter is pressed, that would be helpful as well.


Solution

  • You would have to catch each keypress, find the first item in the list that begins with the letter, and set the variable. In the code below "five" is set no matter which key is pressed as an example.

    import sys
    if sys.version_info[0] < 3:
        import Tkinter as tk     ## Python 2.x
    else:
        import tkinter as tk     ## Python 3.x
    
    master = tk.Tk()
    master.geometry("125x100")
    
    def key_in(event):
        ch=event.char.lower()
        print("key_in", ch)
        if "a" <= ch <= "z":
            variable.set("five")
        if event.keysym=="Return":
            print("Enter key pressed")
    
    def ok(arg):
        print("ok called", variable.get())
    
    variable = tk.StringVar(master)
    options=("one", "two", "three", "four", "five")
    op=tk.OptionMenu(master, variable, *options, command=ok)
    op.grid()
    variable.set("two")
    
    op.bind_all('<Key>', key_in)
    op.focus_set()
    
    tk.Button(master, text="Exit", bg="red",
              command=master.quit).grid(row=1)
    
    master.mainloop()