我正在使用AutocompleteComboboxfromttkwidgets.autocomplete作為我的選擇小部件。雖然所有功能都很好(比如能夠在輸入時過濾串列),但我希望能夠輸入它,但只能從可用選項中輸入,即,我不應該輸入自定義值。我嘗試使用 state=readonly 但它不允許我輸入組合框。任何解決方案將不勝感激。
uj5u.com熱心網友回復:
由于您沒有提供示例代碼并且 tkinter 沒有提供默認的自動完成組合,我假設您使用的是AutocompleteComboboxfrom ttkwidgets.autocomplete。
要僅獲取有效條目(沒有自定義條目),您必須重新實作AutocompleteCombobox類的自動完成方法。
邏輯很簡單:檢查當前用戶輸入是否在自動完成串列中。如果不是,請洗掉最后一個字符并再次顯示最后一個自動完成建議。
我使用此來源的示例代碼作為我的答案的基礎。
這是實作自定義的代碼片段MatchOnlyAutocompleteCombobox:
from tkinter import *
from ttkwidgets.autocomplete import AutocompleteCombobox
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='#8DBF5A')
class MatchOnlyAutocompleteCombobox(AutocompleteCombobox):
def autocomplete(self, delta=0):
"""
Autocomplete the Combobox.
:param delta: 0, 1 or -1: how to cycle through possible hits
:type delta: int
"""
if delta: # need to delete selection otherwise we would fix the current position
self.delete(self.position, 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 not _hits:
# No hits with current user text input
self.position -= 1 # delete one character
self.delete(self.position, END)
# Display again last matched autocomplete
self.autocomplete(delta)
return
# 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, END)
self.insert(0, self._hits[self._hit_index])
self.select_range(self.position, END)
frame = Frame(ws, bg='#8DBF5A')
frame.pack(expand=True)
Label(
frame,
bg='#8DBF5A',
font=('Times', 21),
text='Countries in North America '
).pack()
entry = MatchOnlyAutocompleteCombobox(
frame,
width=30,
font=('Times', 18),
completevalues=countries
)
entry.pack()
ws.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439064.html
