0
# UI Framework
1
2
Widget-based GUI toolkit with layout management, styling, and event handling for creating desktop-like web applications using Python. The UI framework provides high-level components that abstract HTML/CSS complexity.
3
4
## Capabilities
5
6
### Base Widget System
7
8
Foundation classes for all UI components with common functionality.
9
10
```python { .api }
11
class Widget:
12
"""
13
Base class for all UI widgets.
14
"""
15
16
def __init__(self, parent: 'Widget' = None):
17
"""
18
Initialize widget.
19
20
Args:
21
parent: Parent widget for hierarchical layout
22
"""
23
24
def bind(self, event: str, callback: Callable) -> 'Widget':
25
"""
26
Bind event handler to widget.
27
28
Args:
29
event: Event type ('click', 'change', etc.)
30
callback: Event handler function
31
32
Returns:
33
Self for method chaining
34
"""
35
36
def pack(self, **options) -> None:
37
"""
38
Pack widget using layout manager.
39
40
Args:
41
**options: Layout options (side, fill, expand, etc.)
42
"""
43
44
def place(self, x: int = 0, y: int = 0, width: int = None, height: int = None) -> None:
45
"""
46
Place widget at absolute position.
47
48
Args:
49
x: X coordinate
50
y: Y coordinate
51
width: Widget width
52
height: Widget height
53
"""
54
55
def grid(self, row: int = 0, column: int = 0, **options) -> None:
56
"""
57
Place widget in grid layout.
58
59
Args:
60
row: Grid row
61
column: Grid column
62
**options: Grid options (rowspan, columnspan, sticky, etc.)
63
"""
64
65
def show(self) -> None:
66
"""Show widget."""
67
68
def hide(self) -> None:
69
"""Hide widget."""
70
71
def destroy(self) -> None:
72
"""Remove widget from interface."""
73
74
# Properties
75
width: int # Widget width
76
height: int # Widget height
77
x: int # X position
78
y: int # Y position
79
visible: bool # Visibility state
80
enabled: bool # Enabled state
81
```
82
83
### Styling Classes
84
85
Comprehensive styling system for widget appearance and layout.
86
87
```python { .api }
88
class Border:
89
"""Border styling configuration."""
90
91
def __init__(self, width: int = 1, style: str = 'solid', color: str = 'black', radius: int = 0):
92
"""
93
Configure border appearance.
94
95
Args:
96
width: Border width in pixels
97
style: Border style ('solid', 'dashed', 'dotted', etc.)
98
color: Border color
99
radius: Border radius for rounded corners
100
"""
101
102
class Font:
103
"""Font styling configuration."""
104
105
def __init__(self, family: str = 'Arial', size: int = 12, weight: str = 'normal', style: str = 'normal'):
106
"""
107
Configure font appearance.
108
109
Args:
110
family: Font family name
111
size: Font size in pixels
112
weight: Font weight ('normal', 'bold', etc.)
113
style: Font style ('normal', 'italic', etc.)
114
"""
115
116
class Padding:
117
"""Padding and margin configuration."""
118
119
def __init__(self, top: int = 0, right: int = None, bottom: int = None, left: int = None):
120
"""
121
Configure spacing around widget.
122
123
Args:
124
top: Top padding/margin
125
right: Right padding/margin (defaults to top)
126
bottom: Bottom padding/margin (defaults to top)
127
left: Left padding/margin (defaults to right)
128
"""
129
```
130
131
### Container Widgets
132
133
Layout containers for organizing other widgets.
134
135
```python { .api }
136
class Frame(Widget):
137
"""
138
Container widget for grouping other widgets.
139
"""
140
141
def __init__(self, parent: Widget = None, **options):
142
"""
143
Create frame container.
144
145
Args:
146
parent: Parent widget
147
**options: Frame options (border, background, etc.)
148
"""
149
150
class Box(Widget):
151
"""
152
Flexible box layout container.
153
"""
154
155
def __init__(self, parent: Widget = None, direction: str = 'vertical', **options):
156
"""
157
Create box layout.
158
159
Args:
160
parent: Parent widget
161
direction: Layout direction ('vertical', 'horizontal')
162
**options: Box options (spacing, alignment, etc.)
163
"""
164
165
class Bar(Frame):
166
"""
167
Toolbar/statusbar widget.
168
"""
169
170
def __init__(self, parent: Widget = None, orientation: str = 'horizontal'):
171
"""
172
Create toolbar.
173
174
Args:
175
parent: Parent widget
176
orientation: Bar orientation ('horizontal', 'vertical')
177
"""
178
```
179
180
**Usage:**
181
```python
182
from browser.ui import Frame, Box, Border, Font
183
184
# Create main container
185
main_frame = Frame(
186
border=Border(width=2, style='solid', color='gray'),
187
background='lightgray'
188
)
189
190
# Create vertical layout
191
content_box = Box(main_frame, direction='vertical', spacing=10)
192
193
# Create horizontal toolbar
194
toolbar = Bar(main_frame, orientation='horizontal')
195
```
196
197
### Input Widgets
198
199
Interactive widgets for user input and data entry.
200
201
```python { .api }
202
class Button(Widget):
203
"""
204
Clickable button widget.
205
"""
206
207
def __init__(self, text: str = "", parent: Widget = None, **options):
208
"""
209
Create button.
210
211
Args:
212
text: Button text
213
parent: Parent widget
214
**options: Button options (font, color, etc.)
215
"""
216
217
def click(self) -> None:
218
"""Programmatically click button."""
219
220
# Properties
221
text: str # Button text
222
enabled: bool # Enabled state
223
224
class Entry(Widget):
225
"""
226
Single-line text input widget.
227
"""
228
229
def __init__(self, value: str = "", parent: Widget = None, **options):
230
"""
231
Create text entry.
232
233
Args:
234
value: Initial text value
235
parent: Parent widget
236
**options: Entry options (placeholder, maxlength, etc.)
237
"""
238
239
def get(self) -> str:
240
"""Get current text value."""
241
242
def set(self, value: str) -> None:
243
"""Set text value."""
244
245
def clear(self) -> None:
246
"""Clear text content."""
247
248
def select_all(self) -> None:
249
"""Select all text."""
250
251
# Properties
252
value: str # Current text value
253
placeholder: str # Placeholder text
254
readonly: bool # Read-only state
255
256
class Text(Widget):
257
"""
258
Multi-line text widget.
259
"""
260
261
def __init__(self, content: str = "", parent: Widget = None, **options):
262
"""
263
Create text area.
264
265
Args:
266
content: Initial text content
267
parent: Parent widget
268
**options: Text options (rows, cols, wrap, etc.)
269
"""
270
271
def insert(self, position: str, text: str) -> None:
272
"""Insert text at position."""
273
274
def delete(self, start: str, end: str = None) -> None:
275
"""Delete text range."""
276
277
def get(self, start: str = None, end: str = None) -> str:
278
"""Get text content or range."""
279
280
# Properties
281
content: str # Text content
282
wrap: str # Text wrapping ('none', 'word', 'char')
283
```
284
285
**Usage:**
286
```python
287
from browser.ui import Button, Entry, Text, Font
288
289
def create_form():
290
# Create form elements
291
name_entry = Entry(placeholder="Enter your name")
292
email_entry = Entry(placeholder="Enter email address")
293
294
message_text = Text(
295
content="Type your message here...",
296
rows=5,
297
cols=40,
298
wrap='word'
299
)
300
301
submit_btn = Button(
302
text="Submit Form",
303
font=Font(size=14, weight='bold')
304
)
305
306
# Handle form submission
307
def handle_submit(event):
308
name = name_entry.get()
309
email = email_entry.get()
310
message = message_text.get()
311
312
if name and email and message:
313
print(f"Form submitted: {name}, {email}")
314
# Process form data
315
else:
316
print("Please fill all fields")
317
318
submit_btn.bind('click', handle_submit)
319
320
return [name_entry, email_entry, message_text, submit_btn]
321
```
322
323
### Display Widgets
324
325
Widgets for displaying information and media content.
326
327
```python { .api }
328
class Label(Widget):
329
"""
330
Text display widget.
331
"""
332
333
def __init__(self, text: str = "", parent: Widget = None, **options):
334
"""
335
Create text label.
336
337
Args:
338
text: Display text
339
parent: Parent widget
340
**options: Label options (font, color, alignment, etc.)
341
"""
342
343
# Properties
344
text: str # Display text
345
alignment: str # Text alignment ('left', 'center', 'right')
346
347
class Image(Widget):
348
"""
349
Image display widget.
350
"""
351
352
def __init__(self, src: str = "", parent: Widget = None, **options):
353
"""
354
Create image widget.
355
356
Args:
357
src: Image source URL
358
parent: Parent widget
359
**options: Image options (alt, width, height, etc.)
360
"""
361
362
def load_image(self, src: str) -> None:
363
"""Load new image."""
364
365
# Properties
366
src: str # Image source
367
alt: str # Alternative text
368
```
369
370
### Selection Widgets
371
372
Widgets for choosing from multiple options.
373
374
```python { .api }
375
class Listbox(Frame):
376
"""
377
List selection widget.
378
"""
379
380
def __init__(self, parent: Widget = None, **options):
381
"""
382
Create listbox.
383
384
Args:
385
parent: Parent widget
386
**options: Listbox options (multiple, height, etc.)
387
"""
388
389
def insert(self, index: int, item: str) -> None:
390
"""Insert item at index."""
391
392
def delete(self, index: int) -> None:
393
"""Delete item at index."""
394
395
def select(self, index: int) -> None:
396
"""Select item by index."""
397
398
def get_selection(self) -> list[int]:
399
"""Get selected item indices."""
400
401
def get_items(self) -> list[str]:
402
"""Get all items."""
403
404
# Properties
405
selection: list[int] # Selected indices
406
multiple: bool # Allow multiple selection
407
408
class Checkbuttons(Frame):
409
"""
410
Checkbox group widget.
411
"""
412
413
def __init__(self, options: list[str], parent: Widget = None, **kwargs):
414
"""
415
Create checkbox group.
416
417
Args:
418
options: List of checkbox labels
419
parent: Parent widget
420
**kwargs: Group options
421
"""
422
423
def get_checked(self) -> list[str]:
424
"""Get checked option labels."""
425
426
def set_checked(self, labels: list[str]) -> None:
427
"""Set checked options."""
428
429
class Radiobuttons(Frame):
430
"""
431
Radio button group widget.
432
"""
433
434
def __init__(self, options: list[str], parent: Widget = None, **kwargs):
435
"""
436
Create radio button group.
437
438
Args:
439
options: List of radio button labels
440
parent: Parent widget
441
**kwargs: Group options
442
"""
443
444
def get_selected(self) -> str:
445
"""Get selected option label."""
446
447
def set_selected(self, label: str) -> None:
448
"""Set selected option."""
449
```
450
451
**Usage:**
452
```python
453
from browser.ui import Listbox, Checkbuttons, Radiobuttons
454
455
def create_selection_widgets():
456
# Create listbox with items
457
item_list = Listbox(multiple=True)
458
item_list.insert(0, "Item 1")
459
item_list.insert(1, "Item 2")
460
item_list.insert(2, "Item 3")
461
462
# Create checkbox group
463
features = Checkbuttons([
464
"Enable notifications",
465
"Auto-save documents",
466
"Dark theme",
467
"Advanced features"
468
])
469
470
# Create radio button group
471
priority = Radiobuttons([
472
"Low priority",
473
"Medium priority",
474
"High priority",
475
"Critical"
476
])
477
478
def get_selections():
479
selected_items = [item_list.get_items()[i] for i in item_list.get_selection()]
480
checked_features = features.get_checked()
481
selected_priority = priority.get_selected()
482
483
print("Selected items:", selected_items)
484
print("Checked features:", checked_features)
485
print("Priority:", selected_priority)
486
487
return item_list, features, priority
488
```
489
490
### Dialog Widgets
491
492
Modal dialogs and popup windows for user interaction.
493
494
```python { .api }
495
class Dialog(Widget):
496
"""
497
Modal dialog widget.
498
"""
499
500
def __init__(self, title: str = "", parent: Widget = None, **options):
501
"""
502
Create modal dialog.
503
504
Args:
505
title: Dialog title
506
parent: Parent widget
507
**options: Dialog options (modal, resizable, etc.)
508
"""
509
510
def show_modal(self) -> None:
511
"""Show dialog as modal."""
512
513
def close(self) -> None:
514
"""Close dialog."""
515
516
def add_button(self, text: str, callback: Callable) -> Button:
517
"""Add button to dialog."""
518
519
# Properties
520
title: str # Dialog title
521
modal: bool # Modal state
522
523
class EntryDialog(Dialog):
524
"""
525
Dialog with text entry field.
526
"""
527
528
def __init__(self, title: str = "", prompt: str = "", parent: Widget = None):
529
"""
530
Create entry dialog.
531
532
Args:
533
title: Dialog title
534
prompt: Entry prompt text
535
parent: Parent widget
536
"""
537
538
def get_value(self) -> str:
539
"""Get entered value."""
540
541
class InfoDialog(Dialog):
542
"""
543
Information display dialog.
544
"""
545
546
def __init__(self, title: str = "", message: str = "", parent: Widget = None):
547
"""
548
Create info dialog.
549
550
Args:
551
title: Dialog title
552
message: Information message
553
parent: Parent widget
554
"""
555
556
# Convenience functions
557
def Info(message: str, title: str = "Information") -> None:
558
"""Show information dialog."""
559
560
def Confirm(message: str, title: str = "Confirm") -> bool:
561
"""Show confirmation dialog."""
562
563
def Prompt(message: str, title: str = "Input", default: str = "") -> str:
564
"""Show input prompt dialog."""
565
```
566
567
**Usage:**
568
```python
569
from browser.ui import Dialog, EntryDialog, InfoDialog, Info, Confirm, Prompt
570
571
def show_dialogs():
572
# Simple info dialog
573
Info("Operation completed successfully!")
574
575
# Confirmation dialog
576
if Confirm("Are you sure you want to delete this item?"):
577
print("Item deleted")
578
579
# Input prompt
580
name = Prompt("Please enter your name:", default="Anonymous")
581
if name:
582
print(f"Hello, {name}!")
583
584
# Custom dialog
585
settings_dialog = Dialog("Settings", modal=True)
586
587
# Add content to dialog
588
content_frame = Frame(settings_dialog)
589
590
theme_label = Label("Theme:", content_frame)
591
theme_radio = Radiobuttons(["Light", "Dark"], content_frame)
592
593
def save_settings():
594
selected_theme = theme_radio.get_selected()
595
print(f"Theme set to: {selected_theme}")
596
settings_dialog.close()
597
598
def cancel_settings():
599
settings_dialog.close()
600
601
settings_dialog.add_button("Save", save_settings)
602
settings_dialog.add_button("Cancel", cancel_settings)
603
604
settings_dialog.show_modal()
605
```
606
607
### Layout Management
608
609
Advanced layout systems for complex interfaces.
610
611
```python { .api }
612
class GridLayout:
613
"""
614
Grid-based layout manager.
615
"""
616
617
def __init__(self, rows: int, columns: int):
618
"""
619
Create grid layout.
620
621
Args:
622
rows: Number of rows
623
columns: Number of columns
624
"""
625
626
def add_widget(self, widget: Widget, row: int, column: int,
627
rowspan: int = 1, columnspan: int = 1) -> None:
628
"""Add widget to grid position."""
629
630
class BoxLayout:
631
"""
632
Linear box layout manager.
633
"""
634
635
def __init__(self, direction: str = 'vertical'):
636
"""
637
Create box layout.
638
639
Args:
640
direction: Layout direction ('vertical', 'horizontal')
641
"""
642
643
def add_widget(self, widget: Widget, flex: int = 0) -> None:
644
"""Add widget with flex weight."""
645
```
646
647
## Complete Application Example
648
649
```python
650
from browser.ui import *
651
652
class TodoApp:
653
def __init__(self):
654
self.setup_ui()
655
self.todos = []
656
657
def setup_ui(self):
658
# Main window
659
self.window = Frame(
660
border=Border(width=1, color='gray'),
661
background='white'
662
)
663
664
# Title
665
title = Label(
666
"Todo Application",
667
font=Font(size=18, weight='bold'),
668
alignment='center'
669
)
670
671
# Input section
672
input_frame = Frame(self.window)
673
self.todo_entry = Entry(placeholder="Enter new todo...")
674
add_button = Button("Add Todo")
675
add_button.bind('click', self.add_todo)
676
677
# Todo list
678
self.todo_list = Listbox(self.window, height=300)
679
680
# Action buttons
681
button_frame = Frame(self.window)
682
complete_btn = Button("Mark Complete")
683
delete_btn = Button("Delete")
684
clear_btn = Button("Clear All")
685
686
complete_btn.bind('click', self.mark_complete)
687
delete_btn.bind('click', self.delete_todo)
688
clear_btn.bind('click', self.clear_all)
689
690
# Layout
691
title.pack(fill='x', pady=10)
692
693
input_frame.pack(fill='x', padx=10, pady=5)
694
self.todo_entry.pack(side='left', fill='x', expand=True)
695
add_button.pack(side='right', padx=(10, 0))
696
697
self.todo_list.pack(fill='both', expand=True, padx=10, pady=5)
698
699
button_frame.pack(fill='x', padx=10, pady=5)
700
complete_btn.pack(side='left')
701
delete_btn.pack(side='left', padx=(10, 0))
702
clear_btn.pack(side='right')
703
704
def add_todo(self, event):
705
text = self.todo_entry.get().strip()
706
if text:
707
self.todos.append({"text": text, "completed": False})
708
self.update_list()
709
self.todo_entry.clear()
710
711
def update_list(self):
712
self.todo_list.clear()
713
for i, todo in enumerate(self.todos):
714
status = "✓ " if todo["completed"] else "○ "
715
self.todo_list.insert(i, status + todo["text"])
716
717
def mark_complete(self, event):
718
selection = self.todo_list.get_selection()
719
if selection:
720
index = selection[0]
721
self.todos[index]["completed"] = True
722
self.update_list()
723
724
def delete_todo(self, event):
725
selection = self.todo_list.get_selection()
726
if selection and Confirm("Delete selected todo?"):
727
index = selection[0]
728
del self.todos[index]
729
self.update_list()
730
731
def clear_all(self, event):
732
if self.todos and Confirm("Clear all todos?"):
733
self.todos.clear()
734
self.update_list()
735
736
# Run application
737
app = TodoApp()
738
app.window.show()
739
```
740
741
This comprehensive UI framework enables creation of sophisticated desktop-style applications in web browsers using familiar widget concepts and Python syntax, while automatically handling HTML/CSS generation and browser compatibility.