当前位置: 首页 > 面试题库 >

Tkinter-如何使用自动补全功能创建一个组合框

崔绍辉
2023-03-14
问题内容

是否可以创建一个在您键入时使用列表中最接近的项目进行更新的组合框?

例如:

A = ttk.Combobox()
A['values'] = ['Chris', 'Jane', 'Ben', 'Megan']

然后,您在组合框中键入“ Chr”,我希望它自动填写“ Chris”。


问题答案:

tkinter
Wiki包含一个自动完成文本框的代码,但是由于您需要一个组合框,因此可以使用此代码(您正在寻找AutocompleteCombobox)。

"""
tkentrycomplete.py

A Tkinter widget that features autocompletion.

Created by Mitja Martini on 2008-11-29.
Updated by Russell Adams, 2011/01/24 to support Python 3 and Combobox.
Updated by Dominic Kexel to use Tkinter and ttk instead of tkinter and tkinter.ttk
   Licensed same as original (not specified?), or public domain, whichever is less restrictive.
"""
import sys
import os
import Tkinter
import ttk

__version__ = "1.1"

# I may have broken the unicode...
Tkinter_umlauts=['odiaeresis', 'adiaeresis', 'udiaeresis', 'Odiaeresis', 'Adiaeresis', 'Udiaeresis', 'ssharp']

class AutocompleteEntry(Tkinter.Entry):
        """
        Subclass of Tkinter.Entry that features autocompletion.

        To enable autocompletion use set_completion_list(list) to define
        a list of possible strings to hit.
        To cycle through hits use down and up arrow keys.
        """
        def set_completion_list(self, completion_list):
                self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
                self._hits = []
                self._hit_index = 0
                self.position = 0
                self.bind('<KeyRelease>', self.handle_keyrelease)

        def autocomplete(self, delta=0):
                """autocomplete the Entry, delta may be 0/1/-1 to cycle through possible hits"""
                if delta: # need to delete selection otherwise we would fix the current position
                        self.delete(self.position, Tkinter.END)
                else: # set position to end so selection starts where textentry ended
                        self.position = len(self.get())
                # collect hits
                _hits = []
                for element in self._completion_list:
                        if element.lower().startswith(self.get().lower()):  # Match case-insensitively
                                _hits.append(element)
                # if we have a new hit list, keep this in mind
                if _hits != self._hits:
                        self._hit_index = 0
                        self._hits=_hits
                # only allow cycling if we are in a known hit list
                if _hits == self._hits and self._hits:
                        self._hit_index = (self._hit_index + delta) % len(self._hits)
                # now finally perform the auto completion
                if self._hits:
                        self.delete(0,Tkinter.END)
                        self.insert(0,self._hits[self._hit_index])
                        self.select_range(self.position,Tkinter.END)

        def handle_keyrelease(self, event):
                """event handler for the keyrelease event on this widget"""
                if event.keysym == "BackSpace":
                        self.delete(self.index(Tkinter.INSERT), Tkinter.END)
                        self.position = self.index(Tkinter.END)
                if event.keysym == "Left":
                        if self.position < self.index(Tkinter.END): # delete the selection
                                self.delete(self.position, Tkinter.END)
                        else:
                                self.position = self.position-1 # delete one character
                                self.delete(self.position, Tkinter.END)
                if event.keysym == "Right":
                        self.position = self.index(Tkinter.END) # go to end (no selection)
                if event.keysym == "Down":
                        self.autocomplete(1) # cycle to next hit
                if event.keysym == "Up":
                        self.autocomplete(-1) # cycle to previous hit
                if len(event.keysym) == 1 or event.keysym in Tkinter_umlauts:
                        self.autocomplete()

class AutocompleteCombobox(ttk.Combobox):

        def set_completion_list(self, completion_list):
                """Use our completion list as our drop down selection menu, arrows move through menu."""
                self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
                self._hits = []
                self._hit_index = 0
                self.position = 0
                self.bind('<KeyRelease>', self.handle_keyrelease)
                self['values'] = self._completion_list  # Setup our popup menu

        def autocomplete(self, delta=0):
                """autocomplete the Combobox, delta may be 0/1/-1 to cycle through possible hits"""
                if delta: # need to delete selection otherwise we would fix the current position
                        self.delete(self.position, Tkinter.END)
                else: # set position to end so selection starts where textentry ended
                        self.position = len(self.get())
                # collect hits
                _hits = []
                for element in self._completion_list:
                        if element.lower().startswith(self.get().lower()): # Match case insensitively
                                _hits.append(element)
                # if we have a new hit list, keep this in mind
                if _hits != self._hits:
                        self._hit_index = 0
                        self._hits=_hits
                # only allow cycling if we are in a known hit list
                if _hits == self._hits and self._hits:
                        self._hit_index = (self._hit_index + delta) % len(self._hits)
                # now finally perform the auto completion
                if self._hits:
                        self.delete(0,Tkinter.END)
                        self.insert(0,self._hits[self._hit_index])
                        self.select_range(self.position,Tkinter.END)

        def handle_keyrelease(self, event):
                """event handler for the keyrelease event on this widget"""
                if event.keysym == "BackSpace":
                        self.delete(self.index(Tkinter.INSERT), Tkinter.END)
                        self.position = self.index(Tkinter.END)
                if event.keysym == "Left":
                        if self.position < self.index(Tkinter.END): # delete the selection
                                self.delete(self.position, Tkinter.END)
                        else:
                                self.position = self.position-1 # delete one character
                                self.delete(self.position, Tkinter.END)
                if event.keysym == "Right":
                        self.position = self.index(Tkinter.END) # go to end (no selection)
                if len(event.keysym) == 1:
                        self.autocomplete()
                # No need for up/down, we'll jump to the popup
                # list at the position of the autocompletion

def test(test_list):
        """Run a mini application to test the AutocompleteEntry Widget."""
        root = Tkinter.Tk(className=' AutocompleteEntry demo')
        entry = AutocompleteEntry(root)
        entry.set_completion_list(test_list)
        entry.pack()
        entry.focus_set()
        combo = AutocompleteCombobox(root)
        combo.set_completion_list(test_list)
        combo.pack()
        combo.focus_set()
        # I used a tiling WM with no controls, added a shortcut to quit
        root.bind('<Control-Q>', lambda event=None: root.destroy())
        root.bind('<Control-q>', lambda event=None: root.destroy())
        root.mainloop()

if __name__ == '__main__':
        test_list = ('apple', 'banana', 'CranBerry', 'dogwood', 'alpha', 'Acorn', 'Anise' )
        test(test_list)


 类似资料:
  • 本文向大家介绍利用Redis如何实现自动补全功能,包括了利用Redis如何实现自动补全功能的使用技巧和注意事项,需要的朋友参考一下 忘了redis从哪个版本开启,能够根据输入的部分命令前缀给出提示,即自动补全。接下来笔者介绍基于redis实现这个很酷的功能。 about sorted set 假设结果中有mara,marabel,marcela。现在我们输入mar,就能得到这三个名字,并且输出结果

  • 问题内容: from Tkinter import * import time #Tkinter stuff 我正在尝试创建一个配方显示,以在Tkinter GUI的屏幕上显示步骤,说明,重量和其他变量。 但是,我不知道如何根据配方的每个新步骤来更新GUI以进行更改,因为必须根据用户输入(从服务器获取)动态更新内容。如何根据步骤的更改实现GUI其他元素的更新? 问题答案: 您可以在(例如)1000

  • 问题内容: 有谁知道如何设置自动完成功能以与python,django和vim完美配合? 我一直在尝试使用pysmell,但是我似乎无法正确设置它(或者也许我不知道它是如何工作的)。现在,我在django目录中运行pysmell(我正在使用中继),并将结果标签移到我的项目目录中,然后我也在项目目录中运行pysmell。但是,Vim不会拾取django标记,并且它们不会自动完成。 有谁知道如何在vi

  • 问题内容: 我有兴趣在JFrame中提供自动补全框。触发机制将基于助记符(我认为),但是我不太确定“自动补全框”应使用什么(我希望在用户按下键时对结果进行过滤)。 您将如何实施?某种JFrame还是JPopupMenu? 我想知道这是如何实现的,所以请不要发布指向可用的[J] Components的链接。 问题答案: Sun的教程“使用Swing组件”中提供了 一个自动完成文本区域 的示例 。 它

  • 问题内容: 有谁知道用Knockout JS模板创建自动完成组合框的最佳方法吗? 我有以下模板: 有时候,这个清单很长,我想让Knockout在jQuery自动完成功能或一些直接的JavaScript代码方面表现出色,但收效甚微。 另外,jQuery.Autocomplete需要输入字段。有任何想法吗? 问题答案: 这是我编写的jQuery UI自动完成绑定。它的目的是镜像,,,与几个新增的选择要

  • 本文向大家介绍基于jquery实现的自动补全功能,包括了基于jquery实现的自动补全功能的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了基于jquery实现的自动补全功能的方法。分享给大家供大家参考。具体实现方法如下: 希望本文所述对大家的jQuery程序设计有所帮助。