【问题标题】:Tkinter - How to create a combo box with autocompletionTkinter - 如何创建具有自动完成功能的组合框
【发布时间】:2012-08-31 03:50:19
【问题描述】:

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

例如:

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

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

【问题讨论】:

    标签: python tkinter autocomplete


    【解决方案1】:

    是的,可以使用以下示例轻松完成,取自here

    from ttkwidgets.autocomplete import AutocompleteEntry
    from tkinter import *
    
    countries = [
            'Antigua and Barbuda', 'Bahamas','Barbados','Belize', 'Canada',
            'Costa Rica ', 'Cuba', 'Dominica', 'Dominican Republic', 'El Salvador ',
            'Grenada', 'Guatemala ', 'Haiti', 'Honduras ', 'Jamaica', 'Mexico',
            'Nicaragua', 'Saint Kitts and Nevis', 'Panama ', 'Saint Lucia', 
            'Saint Vincent and the Grenadines', 'Trinidad and Tobago', 'United States of America'
            ]
    
    ws = Tk()
    ws.title('PythonGuides')
    ws.geometry('400x300')
    ws.config(bg='#f25252')
    
    frame = Frame(ws, bg='#f25252')
    frame.pack(expand=True)
    
    Label(
        frame, 
        bg='#f25252',
        font = ('Times',21),
        text='Countries in North America '
        ).pack()
    
    entry = AutocompleteEntry(
        frame, 
        width=30, 
        font=('Times', 18),
        completevalues=countries
        )
    entry.pack()
    
    ws.mainloop()
    

    【讨论】:

      【解决方案2】:

      tkinter wiki 包含用于自动完成文本框的 code,但由于您想要一个组合框,您可以使用 this 代码(您正在寻找 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)
      

      【讨论】:

      • 这适用于英文字符,但几乎所有 tkinter 中的绑定方法都无法处理非英文字符。视窗 7
      • 我解决了非英文字母问题,方法是创建一个字典,输出为chr(event.keycode),每个非英文字母作为键,字母作为值。然后我在自动完成功能减速的正下方添加了行if event.keysym == '??': event.keysym = dict[chr(event.keycode)]。也许它不是一个很好的解决方案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2013-11-25
      • 2015-11-26
      • 1970-01-01
      相关资源
      最近更新 更多