Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ttk.combobox force post/open

I am trying to extend the ttk combobox class to allow autosuggestion. the code I have far works well, but I would like to get it to show the dropdown once some text has been entered without removing focus from the entry part of the widget.

The part I am struggling with is finding a way to force the dropdown, in the python docs I cannot find any mention of this, however in the tk docs I did find a post method I believe is supposed to do this, except it doesn't seem to be implemented in the python wrapper.

I also tried generating a down arrow key event once the autosuggest has taken place, however while this does show the dropdown it removes focus, and trying to set the focus after this event doesn't seem to work either (focus does not return)

Is anyone aware of a function I can use to achieve this?

The code I have is for python 3.3 using only standard libs:

class AutoCombobox(ttk.Combobox):
    def __init__(self, parent, **options):
        ttk.Combobox.__init__(self, parent, **options)
        self.bind("<KeyRelease>", self.AutoComplete_1)
        self.bind("<<ComboboxSelected>>", self.Cancel_Autocomplete)
        self.bind("<Return>", self.Cancel_Autocomplete)
        self.autoid = None

    def Cancel_Autocomplete(self, event=None):
        self.after_cancel(self.autoid) 

    def AutoComplete_1(self, event):
        if self.autoid != None:
            self.after_cancel(self.autoid)
        if event.keysym in ["BackSpace", "Delete", "Return"]:
            return
        self.autoid = self.after(200, self.AutoComplete_2)

    def AutoComplete_2(self):
        data = self.get()
        if data != "":
            for entry in self["values"]:
                match = True
                try:
                    for index in range(0, len(data)):
                        if data[index] != entry[index]:
                            match = False
                            break
                except IndexError:
                    match = False
                if match == True:
                    self.set(entry)
                    self.selection_range(len(data), "end")
                    self.event_generate("<Down>",when="tail")
                    self.focus_set()
                    break
            self.autoid = None
like image 418
James Kent Avatar asked Aug 31 '14 01:08

James Kent


1 Answers

You do not need to inherit ttk.Combobox for this event; simply use event_generate to force the dropdown:

box = Combobox(...)
def callback(box):
    box.event_generate('<Down>')
like image 130
Jun Avatar answered Oct 02 '22 22:10

Jun