Python ttk.combobox 强制发布/打开

Jam*_*ent 6 python combobox tkinter ttk python-3.x

我正在尝试扩展 ttk 组合框类以允许自动建议。我的代码运行良好,但我想让它在输入一些文本后显示下拉列表,而无需从小部件的输入部分移除焦点。

我正在努力解决的部分是找到一种强制下拉的方法,在 python 文档中我找不到任何提及这一点,但是在 tk 文档中我确实找到了一个我认为应该这样做的 post 方法,除非它没有t 似乎是在 python 包装器中实现的。

我还尝试在自动建议发生后生成向下箭头键事件,但是虽然这确实显示了下拉列表,但它会移除焦点,并且在此事件之后尝试设置焦点似乎也不起作用(焦点不返回)

有没有人知道我可以用来实现这一目标的功能?

我拥有的代码仅适用于仅使用标准库的 python 3.3:

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
Run Code Online (Sandbox Code Playgroud)

Jun*_*Jun 0

该事件不需要继承ttk.Combobox;只需使用 event_generate 强制下拉:

box = Combobox(...)
def callback(box):
    box.event_generate('<Down>')
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案从组合框小部件的文本输入中删除了焦点,这是 OP 的原始问题。 (3认同)