gpt4 book ai didi

python - 使用 tkinter 编辑文本时显示下拉组合框

转载 作者:行者123 更新时间:2023-12-04 10:44:40 24 4
gpt4 key购买 nike

是否可以在打开下拉菜单时使组合框可编辑?我还没有找到任何解决方案。我想让它更像 Google 搜索,但使用 ComboBox。

最佳答案

Question: Show Combobox PopdownWindow, while editing text

这个例子扩展了一个 ttk.Combobox到以下内容:

  • 在输入时显示 PopdownWindow
  • 在按键 '<Down>' 上打开 PopdownWindow
  • 在按下按键时关闭 PopdownWindow '<Up' , 如果在 Listbox 中的第一项

引用:


  1. 继承自 ttk.Combox

    import tkinter as tk
    import tkinter.ttk as ttk


    class Combobox(ttk.Combobox):
  2. 辅助函数,映射内部ToplevelListboxtkinter目的。

    WARNING: This uses Tk/Tcl internals, which could change without notice.
    This may working only with the tested Tk/Tcl version!

    def _tk(self, cls, parent):
    obj = cls(parent)
    obj.destroy()
    if cls is tk.Toplevel:
    obj._w = self.tk.call('ttk::combobox::PopdownWindow', self)
    else:
    obj._w = '{}.{}'.format(parent._w, 'f.l')
    return obj
  3. 初始化对象,获取内部引用并绑定(bind)到按键事件

    def __init__(self, parent, **kwargs):
    super().__init__(parent, **kwargs)
    self.popdown = self._tk(tk.Toplevel, parent)
    self.listbox = self._tk(tk.Listbox, self.popdown)

    self.bind("<KeyPress>", self.on_keypress, '+')
    self.listbox.bind("<Up>", self.on_keypress)
  4. 用于显示或隐藏 PopdownWindow 并设置键盘焦点的按键处理程序。

    def on_keypress(self, event):
    if event.widget == self:
    state = self.popdown.state()

    if state == 'withdrawn' \
    and event.keysym not in ['BackSpace', 'Up']:
    self.event_generate('<Button-1>')
    self.after(0, self.focus_set)

    if event.keysym == 'Down':
    self.after(0, self.listbox.focus_set)

    else: # self.listbox
    curselection = self.listbox.curselection()

    if event.keysym == 'Up' and curselection[0] == 0:
    self.popdown.withdraw()

    Usage:

    class App(tk.Tk):
    def __init__(self):
    super().__init__()

    values = ('one', 'two', 'three', 'four', 'five', 'six', 'seven')

    self.cb = Combobox(self, value=values)
    self.cb.grid(row=0, column=0)


    if __name__ == "__main__":
    App().mainloop()

    使用 Python 测试:3.5 - 'TclVersion':8.6 'TkVersion':8.6

关于python - 使用 tkinter 编辑文本时显示下拉组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com