是否可以創建一個組合框,並在列表中使用最近的項目進行更新?Tkinter - 如何使用自動填充功能創建組合框
例如:
A = ttk.Combobox()
A['values'] = ['Chris', 'Jane', 'Ben', 'Megan']
然後鍵入「CHR」進入組合框,我希望它在「克里斯」自動填寫。
是否可以創建一個組合框,並在列表中使用最近的項目進行更新?Tkinter - 如何使用自動填充功能創建組合框
例如:
A = ttk.Combobox()
A['values'] = ['Chris', 'Jane', 'Ben', 'Megan']
然後鍵入「CHR」進入組合框,我希望它在「克里斯」自動填寫。
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)
的AutoCompleteComboBox是一個真正的美女的確,上面的回答涉及到從Python代碼給定的值的列表獲取。我正在加強答案,包括從SQLite提取的數據並顯示到組合框中:
if __name__ == '__main__':
#test_list = ('apple', 'banana', 'CranBerry', 'dogwood', 'alpha', 'Acorn', 'Anise', 'crannotberry')
#test(test_list)
connection = sqlite3.connect('my_sqliteDB')
cur = connection.cursor()
cur.execute("select stock_item_name from inventory")
sqloutput = cur.fetchall() #This contains the SQL output in format [(u'data1',), (u'data2',), (u'data3',)]
sqloutput_2 = [item[0] for item in sqloutput] #This is manipulated to the format [u'data1',u'data2',u'data3']
test_list = tuple(map(str, sqloutput_2)) #This will remove the unicode data and final format [data1,data2,data3]
test(test_list) #The final format works with values in DB.
這並沒有真正回答這個問題。這個問題的答案與數據來源無關。 –
同意,這個問題已經被@sloth恰當地回答了,我發現它非常有用。我希望我的補充對任何停止並打算使用動態數據輸入的人都有用。 – mdabdullah
謝謝你!那正是我需要的! – TheBeardedBerry