1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import tkinter as tk
class Widget(tk.Frame):
def __init__(self, master, words):
super().__init__(master)
self.words = words
self.word_selected = None
vcmd = (self.register(self._entry_validate), '%P')
entry = tk.Entry(self, validate='key', vcmd=vcmd)
entry.pack()
self.listbox = listbox = tk.Listbox(self)
listbox.insert('end', *words)
listbox.pack()
listbox.bind('<<ListboxSelect>>', self._on_selection)
def _entry_validate(self, P):
hits = [ w for w in self.words if w.startswith(P) ]
if not hits:
return False
listbox = self.listbox
if len(hits) == 1:
values = listbox.get(0, 'end')
ix = values.index(hits[0])
listbox.selection_set(ix)
else:
listbox.delete(0, 'end')
listbox.insert('end', *hits)
return True
def _on_selection(self, event):
ix = self.listbox.curselection()[0]
self.word_selected = self.listbox.get(ix)
self.event_generate('<<Selected>>')
def get_selected(self):
return self.word_selected
if __name__ == '__main__':
words = ("bonjour", "bonsoir", "bordel", "bondé", "bondir", "bottes")
root = tk.Tk()
w = Widget(root, words)
def gotit(event):
print(w.get_selected())
w.bind('<<Selected>>', gotit)
w.pack()
tk.mainloop() |
Partager