forked from slightlynybbled/tk_tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidgets.py
More file actions
567 lines (434 loc) · 15.1 KB
/
widgets.py
File metadata and controls
567 lines (434 loc) · 15.1 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import logging
import tkinter as tk
import tkinter.ttk as ttk
from typing import List, Union
logger = logging.getLogger(__name__)
class SmartWidget(ttk.Frame):
"""
Superclass which contains basic elements of the 'smart' widgets.
"""
def __init__(self, parent):
self._parent = parent
super().__init__(self._parent)
self._var = None
def add_callback(self, callback: callable):
"""
Add a callback on change
:param callback: callable function
:return: None
"""
def internal_callback(*args):
try:
callback()
except TypeError:
callback(self.get())
self._var.trace("w", internal_callback)
def get(self):
"""
Retrieve the value of the dropdown
:return: the value of the current variable
"""
return self._var.get()
def set(self, value):
"""
Set the value of the dropdown
:param value: a string representing the
:return: None
"""
self._var.set(value)
class SmartOptionMenu(SmartWidget):
"""
Classic drop down entry with built-in tracing variable.::
# create the dropdown and grid
som = SmartOptionMenu(root, ['one', 'two', 'three'])
som.grid()
# define a callback function that retrieves
# the currently selected option
def callback():
print(som.get())
# add the callback function to the dropdown
som.add_callback(callback)
:param data: the tk parent frame
:param options: a list containing the drop down options
:param initial_value: the initial value of the dropdown
:param callback: a function
"""
def __init__(
self,
parent,
options: list,
initial_value: str = None,
callback: callable = None,
):
super().__init__(parent)
self._var = tk.StringVar()
self._var.set(initial_value if initial_value else options[0])
self.option_menu = tk.OptionMenu(self, self._var, *options)
self.option_menu.grid(row=0, column=0)
if callback is not None:
def internal_callback(*args):
try:
callback()
except TypeError:
callback(self.get())
self._var.trace("w", internal_callback)
class SmartSpinBox(SmartWidget):
"""
Easy-to-use spinbox. Takes most options that work with a normal SpinBox.
Attempts to call your callback function - if assigned - whenever there
is a change to the spinbox.::
# create a callback function
def callback(value):
print('the new value is: ', value)
# create the smart spinbox and grid
ssb = SmartSpinBox(root, from_=0, to=5, callback=callback)
ssb.grid()
:param parent: the tk parent frame
:param entry_type: 'str', 'int', 'float'
:param callback: python callable
:param options: any options that are valid for tkinter.SpinBox
"""
def __init__(
self, parent, entry_type: str = "float", callback: callable = None, **options
):
"""
Constructor for SmartSpinBox
"""
self._parent = parent
super().__init__(self._parent)
sb_options = options.copy()
if entry_type == "str":
self._var = tk.StringVar()
elif entry_type == "int":
self._var = tk.IntVar()
elif entry_type == "float":
self._var = tk.DoubleVar()
else:
raise ValueError('Entry type must be "str", "int", or "float"')
sb_options["textvariable"] = self._var
self._spin_box = tk.Spinbox(self, **sb_options)
self._spin_box.grid()
if callback is not None:
def internal_callback(*args):
try:
callback()
except TypeError:
callback(self.get())
self._var.trace("w", internal_callback)
class SmartCheckbutton(SmartWidget):
"""
Easy-to-use check button. Takes most options that work with
a normal CheckButton. Attempts to call your callback
function - if assigned - whenever there is a change to
the check button.::
# create the smart spinbox and grid
scb = SmartCheckbutton(root)
scb.grid()
# define a callback function that retrieves
# the currently selected option
def callback():
print(scb.get())
# add the callback function to the checkbutton
scb.add_callback(callback)
:param parent: the tk parent frame
:param callback: python callable
:param options: any options that are valid for tkinter.Checkbutton
"""
def __init__(self, parent, callback: callable = None, **options):
self._parent = parent
super().__init__(self._parent)
self._var = tk.BooleanVar()
self._cb = tk.Checkbutton(self, variable=self._var, **options)
self._cb.grid()
if callback is not None:
def internal_callback(*args):
try:
callback()
except TypeError:
callback(self.get())
self._var.trace("w", internal_callback)
class SmartListBox(SmartWidget):
"""
Easy-to-use List Box. Takes most options that work with
a normal CheckButton. Attempts to call your callback
function - if assigned - whenever there is a change to
the list box selections.::
# create the smart spinbox and grid
scb = SmartListBox(root, options=['one', 'two', 'three'])
scb.grid()
# define a callback function that retrieves
# the currently selected option
def callback():
print(scb.get_selected())
# add the callback function to the checkbutton
scb.add_callback(callback)
:param parent: the tk parent frame
:param options: any options that are valid for tkinter.Checkbutton
:param on_select_callback: python callable
:param selectmode: the selector mode (supports "browse" and "multiple")
"""
def __init__(
self,
parent,
options: List[str],
width: int = 12,
height: int = 5,
on_select_callback: callable = None,
selectmode: str = "browse",
):
super().__init__(parent=parent)
self._on_select_callback = on_select_callback
self._values = {}
r = 0
self._lb = tk.Listbox(
self, width=width, height=height, selectmode=selectmode, exportselection=0
)
self._lb.grid(row=r, column=0, sticky="ew")
[self._lb.insert("end", option) for option in options]
self._lb.bind("<<ListboxSelect>>", lambda _: self._on_select())
r += 1
clear_label = tk.Label(self, text="clear", fg="blue")
clear_label.grid(row=r, column=0, sticky="ew")
clear_label.bind("<Button-1>", lambda _: self._clear_selected())
def _on_select(self):
self.after(200, self.__on_select)
def _clear_selected(self):
for i in self._lb.curselection():
self._lb.selection_clear(i, "end")
while len(self._values):
self._values.popitem()
if self._on_select_callback is not None:
values = list(self._values.keys())
try:
self._on_select_callback(values)
except TypeError:
self._on_select_callback()
def __on_select(self):
value = self._lb.get("active")
if self._lb.cget("selectmode") == "multiple":
if value in self._values.keys():
self._values.pop(value)
else:
self._values[value] = True
else:
while len(self._values):
self._values.popitem()
self._values[value] = True
if self._on_select_callback is not None:
values = list(self._values.keys())
try:
self._on_select_callback(values)
except TypeError:
self._on_select_callback()
def add_callback(self, callback: callable):
"""
Associates a callback function when the user makes a selection.
:param callback: a callable function
"""
self._on_select_callback = callback
def get_selected(self):
return list(self._values.keys())
def select(self, value):
options = self._lb.get(0, "end")
if value not in options:
raise ValueError("Not a valid selection")
option = options.index(value)
self._lb.activate(option)
self._values[value] = True
class BinaryLabel(ttk.Label):
"""
Displays a value binary. Provides methods for
easy manipulation of bit values.::
# create the label and grid
bl = BinaryLabel(root, 255)
bl.grid()
# toggle highest bit
bl.toggle_msb()
:param parent: the tk parent frame
:param value: the initial value, default is 0
:param options: prefix string for identifiers
"""
def __init__(
self, parent, value: int = 0, prefix: str = "", bit_width: int = 8, **options
):
self._parent = parent
super().__init__(self._parent, **options)
self._value = value
self._prefix = prefix
self._bit_width = bit_width
self._text_update()
def get(self):
"""
Return the current value
:return: the current integer value
"""
return self._value
def set(self, value: int):
"""
Set the current value
:param value:
:return: None
"""
max_value = int("".join(["1" for _ in range(self._bit_width)]), 2)
if value > max_value:
raise ValueError(
"the value {} is larger than "
"the maximum value {}".format(value, max_value)
)
self._value = value
self._text_update()
def _text_update(self):
self["text"] = (
self._prefix
+ str(bin(self._value))[2:].zfill(self._bit_width)[-self._bit_width :]
)
def get_bit(self, position: int):
"""
Returns the bit value at position
:param position: integer between 0 and <width>, inclusive
:return: the value at position as a integer
"""
if position > (self._bit_width - 1):
raise ValueError("position greater than the bit width")
if self._value & (1 << position):
return 1
else:
return 0
def toggle_bit(self, position: int):
"""
Toggles the value at position
:param position: integer between 0 and 7, inclusive
:return: None
"""
if position > (self._bit_width - 1):
raise ValueError("position greater than the bit width")
self._value ^= 1 << position
self._text_update()
def set_bit(self, position: int):
"""
Sets the value at position
:param position: integer between 0 and 7, inclusive
:return: None
"""
if position > (self._bit_width - 1):
raise ValueError("position greater than the bit width")
self._value |= 1 << position
self._text_update()
def clear_bit(self, position: int):
"""
Clears the value at position
:param position: integer between 0 and 7, inclusive
:return: None
"""
if position > (self._bit_width - 1):
raise ValueError("position greater than the bit width")
self._value &= ~(1 << position)
self._text_update()
def get_msb(self):
"""
Returns the most significant bit as an integer
:return: the MSB
"""
return self.get_bit(self._bit_width - 1)
def toggle_msb(self):
"""
Changes the most significant bit
:return: None
"""
self.toggle_bit(self._bit_width - 1)
def get_lsb(self):
"""
Returns the least significant bit as an integer
:return: the LSB
"""
return self.get_bit(0)
def set_msb(self):
"""
Sets the most significant bit
:return: None
"""
self.set_bit(self._bit_width - 1)
def clear_msb(self):
"""
Clears the most significant bit
:return: None
"""
self.clear_bit(self._bit_width - 1)
def toggle_lsb(self):
"""
Toggles the least significant bit
:return:
"""
self.toggle_bit(0)
def set_lsb(self):
"""
Sets the least significant bit
:return: None
"""
self.set_bit(0)
def clear_lsb(self):
"""
Clears the least significant bit
:return: None
"""
self.clear_bit(0)
class ByteLabel(BinaryLabel):
"""
Has been replaced with more general BinaryLabel.
Still here for backwards compatibility.
"""
pass
class ScrollableFrame(ttk.Frame):
"""
Add scrollable frame which will automatically adjust to the contents. Note that widgets must be packed or \
gridded on the ``scrollable_frame`` widget contained within the object.
Example:
root = tk.Tk()
sf = ScrollableFrame(root)
sf.pack()
# add a long list of widgets
def add_widget(i):
tk.Label(sf.scrollable_frame, # <--- note that widgets are being added to the scrollable_frame!
text=f'label {i}').grid(sticky='w')
for i in range(40):
sf.after(i*100, lambda i=i: add_widget(i))
root.mainloop()
:param master: the master widget
:param height: an integer specifying the height in pixels
:param args: the arguments to pass along to the frame
:param kwargs: the arguments/options to pass along to the frame
"""
def __init__(
self,
master: Union[tk.Frame, ttk.Frame, tk.Toplevel, tk.Tk],
height: int = 400,
*args,
**kwargs,
):
super().__init__(master, *args, **kwargs)
self._parent = master
self._canvas = tk.Canvas(self, height=height)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=self._canvas.yview)
self.scrollable_frame = ttk.Frame(self._canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self._canvas.configure(
scrollregion=self._canvas.bbox("all"), width=e.width
),
)
self._canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self._canvas.configure(yscrollcommand=scrollbar.set)
self._canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
self._canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
self._canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
if __name__ == "__main__":
root = tk.Tk()
sf = ScrollableFrame(root)
sf.pack()
def add_widget(i):
tk.Label(sf.scrollable_frame, text=f"label {i}").grid(sticky="w")
for i in range(40):
sf.after(i * 100, lambda i=i: add_widget(i))
root.mainloop()