-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.py
73 lines (60 loc) · 2.33 KB
/
autocomplete.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import tkinter as tk
import tkinter.ttk as ttk
import json
import requests
import threading
import urllib.parse
class SystemAutocompleteCombobox(ttk.Combobox):
def __init__(self, *args, **kwargs):
ttk.Combobox.__init__(self, *args, **kwargs)
self.completion_list = []
self.hits = []
self.hit_index = 0
self.position = 0
self.bind('<KeyRelease>', self.handle_keyrelease)
self['values'] = self.completion_list
def set_completion_list(self, completion_list):
self.completion_list = sorted(completion_list, key=str.lower)
self.hits = []
self.hit_index = 0
self.position = 0
self.bind('<KeyRelease>', self.handle_keyrelease)
self['values'] = self.completion_list
def autocomplete(self, delta=0):
if delta:
self.delete(self.position, tk.END)
else:
self.position = len(self.get())
hits = []
for element in self.completion_list:
if element.lower().startswith(self.get().lower()):
hits.append(element)
if hits != self.hits:
self.hit_index = 0
self.hits = hits
if hits == self.hits and self.hits:
self.hit_index = (self.hit_index + delta) % len(self.hits)
if self.hits:
self.delete(0, tk.END)
self.insert(0, self.hits[self.hit_index])
self.select_range(self.position, tk.END)
def handle_keyrelease(self, event):
threading.Thread(target=self.update_completion_list).start()
if event.keysym == "BackSpace":
self.delete(self.index(tk.INSERT), tk.END)
self.position = self.index(tk.END)
if event.keysym == "Left":
if self.position < self.index(tk.END):
self.delete(self.position, tk.END)
else:
self.position = self.position - 1
self.delete(self.position, tk.END)
if event.keysym == "Right":
self.position = self.index(tk.END)
if len(event.keysym) == 1:
self.autocomplete()
def update_completion_list(self):
self.set_completion_list(
json.loads(requests.get(
f"https://www.spansh.co.uk/api/systems?q={urllib.parse.quote_plus(self.get())}").text))
print(self.completion_list)