How to bind keypress event for combobox drop-out menu in tkinter Python 3.7

前端 未结 1 788
悲&欢浪女
悲&欢浪女 2020-12-20 08:15

I want to make a feature: when my combobox in tkinter clicked and drop-down menu is opened, when you press any key (for example \'s\'), it selects first element in combobox,

相关标签:
1条回答
  • 2020-12-20 08:52

    As far as I understood, there no way to get popdown menu in Python currently. And you have to do that through TCL. The weak point is ".f.l" part of reference as it depends on internal widgets implementation. There is an example of combobox, wich will select items by first their letter when you press a keyboard button.

    from tkinter import ttk
    import itertools as it
    
    class mycombobox(ttk.Combobox):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            pd = self.tk.call('ttk::combobox::PopdownWindow', self) #get popdownWindow reference 
            lb = pd + '.f.l' #get popdown listbox
            self._bind(('bind', lb),"<KeyPress>",self.popup_key_pressed,None)
    
        def popup_key_pressed(self,evt):
            values = self.cget("values")
            for i in it.chain(range(self.current() + 1,len(values)),range(0,self.current())):
                if evt.char.lower() == values[i][0].lower():
                    self.current(i)
                    self.icursor(i)
                    self.tk.eval(evt.widget + ' selection clear 0 end') #clear current selection
                    self.tk.eval(evt.widget + ' selection set ' + str(i)) #select new element
                    self.tk.eval(evt.widget + ' see ' + str(i)) #spin combobox popdown for selected element will be visible
                    return
    
    0 讨论(0)
提交回复
热议问题