0
# File and Dialog Operations
1
2
File operations, dialog widgets, and cross-platform utilities for common application tasks.
3
4
## Capabilities
5
6
### File Dialog Pickers
7
8
Dialog widgets for file and directory selection operations.
9
10
```python { .api }
11
class TTkFileDialogPicker(TTkWidget):
12
def __init__(self, parent=None, **kwargs):
13
"""
14
Initialize a file dialog picker.
15
16
Parameters:
17
- path (str): Initial directory path
18
- filter (str): File filter string
19
- caption (str): Dialog caption
20
"""
21
22
def getOpenFileName(self, caption="", dir="", filter=""):
23
"""
24
Get filename for opening a file.
25
26
Parameters:
27
- caption (str): Dialog title
28
- dir (str): Initial directory
29
- filter (str): File type filter
30
31
Returns:
32
str: Selected filename or empty string if cancelled
33
"""
34
35
def getOpenFileNames(self, caption="", dir="", filter=""):
36
"""
37
Get multiple filenames for opening files.
38
39
Parameters:
40
- caption (str): Dialog title
41
- dir (str): Initial directory
42
- filter (str): File type filter
43
44
Returns:
45
list: List of selected filenames
46
"""
47
48
def getSaveFileName(self, caption="", dir="", filter=""):
49
"""
50
Get filename for saving a file.
51
52
Parameters:
53
- caption (str): Dialog title
54
- dir (str): Initial directory
55
- filter (str): File type filter
56
57
Returns:
58
str: Selected filename or empty string if cancelled
59
"""
60
61
def getExistingDirectory(self, caption="", dir=""):
62
"""
63
Get existing directory path.
64
65
Parameters:
66
- caption (str): Dialog title
67
- dir (str): Initial directory
68
69
Returns:
70
str: Selected directory path
71
"""
72
73
def setPath(self, path):
74
"""Set current directory path."""
75
76
def path(self):
77
"""Get current directory path."""
78
79
def setFilter(self, filter_str):
80
"""Set file filter string."""
81
82
def filter(self):
83
"""Get current file filter."""
84
85
def setCaption(self, caption):
86
"""Set dialog caption."""
87
88
def caption(self):
89
"""Get dialog caption."""
90
91
# Signals
92
fileSelected: pyTTkSignal # Emitted when file is selected
93
filesSelected: pyTTkSignal # Emitted when multiple files are selected
94
95
class TTkFileButtonPicker(TTkButton):
96
def __init__(self, parent=None, **kwargs):
97
"""
98
Initialize a file picker button.
99
100
Parameters:
101
- path (str): Initial file path
102
- filter (str): File filter string
103
- caption (str): Dialog caption
104
- fileMode (int): File selection mode (open, save, directory)
105
"""
106
107
def setPath(self, path):
108
"""Set current file path."""
109
110
def path(self):
111
"""Get current file path."""
112
113
def setFilter(self, filter_str):
114
"""Set file filter."""
115
116
def filter(self):
117
"""Get file filter."""
118
119
def setCaption(self, caption):
120
"""Set dialog caption."""
121
122
def caption(self):
123
"""Get dialog caption."""
124
125
def setFileMode(self, mode):
126
"""Set file selection mode."""
127
128
def fileMode(self):
129
"""Get file selection mode."""
130
131
# Signals
132
fileChanged: pyTTkSignal # Emitted when file selection changes
133
```
134
135
### Message Box Dialogs
136
137
Standard message dialogs for user notifications and confirmations.
138
139
```python { .api }
140
class TTkMessageBox(TTkWindow):
141
def __init__(self, parent=None, **kwargs):
142
"""
143
Initialize a message box dialog.
144
145
Parameters:
146
- title (str): Dialog title
147
- text (str): Main message text
148
- informativeText (str): Additional information text
149
- icon (int): Icon type constant
150
"""
151
152
def setText(self, text):
153
"""Set main message text."""
154
155
def text(self):
156
"""Get main message text."""
157
158
def setInformativeText(self, text):
159
"""Set informative text."""
160
161
def informativeText(self):
162
"""Get informative text."""
163
164
def setDetailedText(self, text):
165
"""Set detailed text (expandable)."""
166
167
def detailedText(self):
168
"""Get detailed text."""
169
170
def setIcon(self, icon):
171
"""Set message box icon."""
172
173
def icon(self):
174
"""Get message box icon."""
175
176
def setStandardButtons(self, buttons):
177
"""Set standard button combination."""
178
179
def standardButtons(self):
180
"""Get standard buttons."""
181
182
def setDefaultButton(self, button):
183
"""Set default button."""
184
185
def defaultButton(self):
186
"""Get default button."""
187
188
def addButton(self, text, role):
189
"""Add custom button."""
190
191
def removeButton(self, button):
192
"""Remove button."""
193
194
def exec(self):
195
"""Execute dialog and return result."""
196
197
# Static convenience methods
198
@staticmethod
199
def information(parent, title, text, buttons=None):
200
"""Show information message."""
201
202
@staticmethod
203
def question(parent, title, text, buttons=None):
204
"""Show question dialog."""
205
206
@staticmethod
207
def warning(parent, title, text, buttons=None):
208
"""Show warning message."""
209
210
@staticmethod
211
def critical(parent, title, text, buttons=None):
212
"""Show critical error message."""
213
214
@staticmethod
215
def about(parent, title, text):
216
"""Show about dialog."""
217
218
# Signals
219
buttonClicked: pyTTkSignal # Emitted when button is clicked
220
```
221
222
### Color Picker Dialogs
223
224
Color selection dialogs for choosing colors interactively.
225
226
```python { .api }
227
class TTkColorButtonPicker(TTkButton):
228
def __init__(self, parent=None, **kwargs):
229
"""
230
Initialize a color picker button.
231
232
Parameters:
233
- color (TTkColor): Initial color
234
- showAlpha (bool): Show alpha channel control
235
"""
236
237
def setColor(self, color):
238
"""Set current color."""
239
240
def color(self):
241
"""Get current color."""
242
243
def setShowAlpha(self, show):
244
"""Show/hide alpha channel control."""
245
246
def showAlpha(self):
247
"""Check if alpha channel is shown."""
248
249
def setColorDialogOptions(self, options):
250
"""Set color dialog options."""
251
252
def colorDialogOptions(self):
253
"""Get color dialog options."""
254
255
# Signals
256
colorChanged: pyTTkSignal # Emitted when color changes
257
258
class TTkColorDialogPicker(TTkWindow):
259
def __init__(self, parent=None, **kwargs):
260
"""
261
Initialize a color dialog picker.
262
263
Parameters:
264
- color (TTkColor): Initial color
265
- showAlpha (bool): Show alpha channel
266
"""
267
268
def setCurrentColor(self, color):
269
"""Set current selected color."""
270
271
def currentColor(self):
272
"""Get current selected color."""
273
274
def selectedColor(self):
275
"""Get final selected color."""
276
277
def setOption(self, option, on=True):
278
"""Set dialog option."""
279
280
def testOption(self, option):
281
"""Test if option is enabled."""
282
283
def setOptions(self, options):
284
"""Set multiple dialog options."""
285
286
def options(self):
287
"""Get current dialog options."""
288
289
def exec(self):
290
"""Execute dialog and return result."""
291
292
# Static convenience method
293
@staticmethod
294
def getColor(initial=None, parent=None, title="", options=0):
295
"""Get color from user selection."""
296
297
# Signals
298
colorSelected: pyTTkSignal # Emitted when color is selected
299
currentColorChanged: pyTTkSignal # Emitted when current color changes
300
```
301
302
### Text Picker Dialogs
303
304
Text input and selection dialogs for string values.
305
306
```python { .api }
307
class TTkTextPicker(TTkWidget):
308
def __init__(self, parent=None, **kwargs):
309
"""
310
Initialize a text picker widget.
311
312
Parameters:
313
- text (str): Initial text
314
- multiline (bool): Allow multiple lines
315
"""
316
317
def setText(self, text):
318
"""Set current text."""
319
320
def text(self):
321
"""Get current text."""
322
323
def setMultiline(self, multiline):
324
"""Enable/disable multiline mode."""
325
326
def isMultiline(self):
327
"""Check if multiline mode is enabled."""
328
329
def setPlaceholderText(self, text):
330
"""Set placeholder text."""
331
332
def placeholderText(self):
333
"""Get placeholder text."""
334
335
def setReadOnly(self, readOnly):
336
"""Set read-only mode."""
337
338
def isReadOnly(self):
339
"""Check if in read-only mode."""
340
341
# Signals
342
textChanged: pyTTkSignal # Emitted when text changes
343
344
class TTkTextDialogPicker(TTkWindow):
345
def __init__(self, parent=None, **kwargs):
346
"""
347
Initialize a text dialog picker.
348
349
Parameters:
350
- title (str): Dialog title
351
- label (str): Input label text
352
- text (str): Initial text
353
"""
354
355
def setLabelText(self, text):
356
"""Set input label text."""
357
358
def labelText(self):
359
"""Get input label text."""
360
361
def setTextValue(self, text):
362
"""Set text value."""
363
364
def textValue(self):
365
"""Get text value."""
366
367
def setInputMode(self, mode):
368
"""Set input mode (normal, password, etc.)."""
369
370
def inputMode(self):
371
"""Get input mode."""
372
373
def exec(self):
374
"""Execute dialog and return result."""
375
376
# Static convenience methods
377
@staticmethod
378
def getText(parent, title, label, text=""):
379
"""Get text input from user."""
380
381
@staticmethod
382
def getMultiLineText(parent, title, label, text=""):
383
"""Get multi-line text input from user."""
384
385
@staticmethod
386
def getItem(parent, title, label, items, current=0, editable=True):
387
"""Get item selection from user."""
388
389
# Signals
390
textValueChanged: pyTTkSignal # Emitted when text value changes
391
```
392
393
### Cross-Platform File Operations
394
395
Utilities for cross-platform file operations and system integration.
396
397
```python { .api }
398
def ttkCrossOpen(filename):
399
"""
400
Open file with system default application.
401
402
Parameters:
403
- filename (str): Path to file to open
404
405
Returns:
406
bool: True if successful, False otherwise
407
"""
408
409
def ttkCrossSave(data, filename, encoding="utf-8"):
410
"""
411
Save data to file with cross-platform compatibility.
412
413
Parameters:
414
- data: Data to save (string or bytes)
415
- filename (str): Target filename
416
- encoding (str): Text encoding for string data
417
418
Returns:
419
bool: True if successful, False otherwise
420
"""
421
422
def ttkCrossSaveAs(data, title="Save As", filter="", encoding="utf-8"):
423
"""
424
Save data with file dialog selection.
425
426
Parameters:
427
- data: Data to save
428
- title (str): Dialog title
429
- filter (str): File type filter
430
- encoding (str): Text encoding
431
432
Returns:
433
str: Selected filename or empty string if cancelled
434
"""
435
436
class TTkEncoding:
437
"""Encoding utilities for cross-platform compatibility."""
438
439
@staticmethod
440
def detectEncoding(filename):
441
"""
442
Detect file encoding.
443
444
Parameters:
445
- filename (str): File to analyze
446
447
Returns:
448
str: Detected encoding name
449
"""
450
451
@staticmethod
452
def convertEncoding(text, from_encoding, to_encoding):
453
"""
454
Convert text between encodings.
455
456
Parameters:
457
- text (str): Text to convert
458
- from_encoding (str): Source encoding
459
- to_encoding (str): Target encoding
460
461
Returns:
462
str: Converted text
463
"""
464
465
@staticmethod
466
def availableEncodings():
467
"""
468
Get list of available encodings.
469
470
Returns:
471
list: Available encoding names
472
"""
473
474
class ImageData:
475
"""Image data handling utilities."""
476
477
def __init__(self, data=None, format="PNG"):
478
"""
479
Initialize image data.
480
481
Parameters:
482
- data: Image data (bytes or file path)
483
- format (str): Image format
484
"""
485
486
def loadFromFile(self, filename):
487
"""Load image from file."""
488
489
def saveToFile(self, filename, format=None):
490
"""Save image to file."""
491
492
def size(self):
493
"""Get image size as (width, height)."""
494
495
def format(self):
496
"""Get image format."""
497
498
def data(self):
499
"""Get raw image data."""
500
501
def toBase64(self):
502
"""Convert to base64 string."""
503
504
@staticmethod
505
def fromBase64(base64_string):
506
"""Create ImageData from base64 string."""
507
508
# Drag and drop utilities
509
def ttkConnectDragOpen(widget, callback):
510
"""
511
Connect drag-and-drop file opening to widget.
512
513
Parameters:
514
- widget: Target widget for drag operations
515
- callback: Function to call with list of dropped files
516
"""
517
518
def ttkEmitDragOpen(files):
519
"""
520
Emit drag-open event with file list.
521
522
Parameters:
523
- files (list): List of file paths
524
"""
525
526
def ttkEmitFileOpen(filename):
527
"""
528
Emit file-open event.
529
530
Parameters:
531
- filename (str): File path to open
532
"""
533
```
534
535
## Usage Examples
536
537
### File Operations Dialog
538
539
```python
540
import TermTk as ttk
541
542
root = ttk.TTk()
543
container = ttk.TTkContainer(parent=root)
544
layout = ttk.TTkVBoxLayout()
545
546
# File operation buttons
547
open_btn = ttk.TTkButton(text="Open File")
548
save_btn = ttk.TTkButton(text="Save File")
549
open_dir_btn = ttk.TTkButton(text="Select Directory")
550
551
# File path display
552
path_label = ttk.TTkLabel(text="No file selected")
553
content_text = ttk.TTkTextEdit()
554
555
# File operations
556
current_file = ""
557
558
@ttk.pyTTkSlot()
559
def open_file():
560
global current_file
561
filename = ttk.TTkFileDialogPicker.getOpenFileName(
562
caption="Open File",
563
filter="Text Files (*.txt);;Python Files (*.py);;All Files (*)"
564
)
565
566
if filename:
567
try:
568
with open(filename, 'r', encoding='utf-8') as f:
569
content = f.read()
570
content_text.setText(content)
571
current_file = filename
572
path_label.setText(f"Opened: {filename}")
573
except Exception as e:
574
ttk.TTkMessageBox.critical(
575
root,
576
"Error",
577
f"Failed to open file:\n{str(e)}"
578
)
579
580
@ttk.pyTTkSlot()
581
def save_file():
582
global current_file
583
content = content_text.text()
584
585
if current_file:
586
# Save to current file
587
try:
588
ttkCrossSave(content, current_file)
589
path_label.setText(f"Saved: {current_file}")
590
except Exception as e:
591
ttk.TTkMessageBox.critical(
592
root,
593
"Error",
594
f"Failed to save file:\n{str(e)}"
595
)
596
else:
597
# Save as new file
598
filename = ttk.TTkFileDialogPicker.getSaveFileName(
599
caption="Save File",
600
filter="Text Files (*.txt);;Python Files (*.py);;All Files (*)"
601
)
602
603
if filename:
604
try:
605
ttkCrossSave(content, filename)
606
current_file = filename
607
path_label.setText(f"Saved: {filename}")
608
except Exception as e:
609
ttk.TTkMessageBox.critical(
610
root,
611
"Error",
612
f"Failed to save file:\n{str(e)}"
613
)
614
615
@ttk.pyTTkSlot()
616
def select_directory():
617
directory = ttk.TTkFileDialogPicker.getExistingDirectory(
618
caption="Select Directory"
619
)
620
621
if directory:
622
path_label.setText(f"Selected directory: {directory}")
623
624
# Connect buttons
625
open_btn.clicked.connect(open_file)
626
save_btn.clicked.connect(save_file)
627
open_dir_btn.clicked.connect(select_directory)
628
629
# Layout
630
button_layout = ttk.TTkHBoxLayout()
631
button_layout.addWidget(open_btn)
632
button_layout.addWidget(save_btn)
633
button_layout.addWidget(open_dir_btn)
634
button_layout.addStretch(1)
635
636
layout.addLayout(button_layout)
637
layout.addWidget(path_label)
638
layout.addWidget(content_text)
639
640
container.setLayout(layout)
641
root.mainloop()
642
```
643
644
### Message Box Examples
645
646
```python
647
import TermTk as ttk
648
649
root = ttk.TTk()
650
container = ttk.TTkContainer(parent=root)
651
layout = ttk.TTkVBoxLayout()
652
653
# Message box demonstration buttons
654
info_btn = ttk.TTkButton(text="Information")
655
question_btn = ttk.TTkButton(text="Question")
656
warning_btn = ttk.TTkButton(text="Warning")
657
error_btn = ttk.TTkButton(text="Error")
658
about_btn = ttk.TTkButton(text="About")
659
660
result_label = ttk.TTkLabel(text="Click a button to show message box")
661
662
@ttk.pyTTkSlot()
663
def show_information():
664
ttk.TTkMessageBox.information(
665
root,
666
"Information",
667
"This is an information message.\nIt provides helpful details to the user."
668
)
669
result_label.setText("Information dialog was shown")
670
671
@ttk.pyTTkSlot()
672
def show_question():
673
result = ttk.TTkMessageBox.question(
674
root,
675
"Question",
676
"Do you want to continue with this operation?",
677
buttons=ttk.TTkMessageBox.Yes | ttk.TTkMessageBox.No
678
)
679
680
if result == ttk.TTkMessageBox.Yes:
681
result_label.setText("User clicked Yes")
682
else:
683
result_label.setText("User clicked No")
684
685
@ttk.pyTTkSlot()
686
def show_warning():
687
ttk.TTkMessageBox.warning(
688
root,
689
"Warning",
690
"This action cannot be undone.\nAre you sure you want to proceed?"
691
)
692
result_label.setText("Warning dialog was shown")
693
694
@ttk.pyTTkSlot()
695
def show_error():
696
ttk.TTkMessageBox.critical(
697
root,
698
"Error",
699
"An error occurred while processing your request.\n\nError details:\n- Connection timeout\n- Server unavailable"
700
)
701
result_label.setText("Error dialog was shown")
702
703
@ttk.pyTTkSlot()
704
def show_about():
705
ttk.TTkMessageBox.about(
706
root,
707
"About My Application",
708
"My Application v1.0\n\nBuilt with pyTermTk\nCopyright © 2024"
709
)
710
result_label.setText("About dialog was shown")
711
712
# Connect buttons
713
info_btn.clicked.connect(show_information)
714
question_btn.clicked.connect(show_question)
715
warning_btn.clicked.connect(show_warning)
716
error_btn.clicked.connect(show_error)
717
about_btn.clicked.connect(show_about)
718
719
# Layout
720
button_layout = ttk.TTkHBoxLayout()
721
button_layout.addWidget(info_btn)
722
button_layout.addWidget(question_btn)
723
button_layout.addWidget(warning_btn)
724
button_layout.addWidget(error_btn)
725
button_layout.addWidget(about_btn)
726
727
layout.addLayout(button_layout)
728
layout.addWidget(result_label)
729
730
container.setLayout(layout)
731
root.mainloop()
732
```
733
734
### Color Picker Integration
735
736
```python
737
import TermTk as ttk
738
739
root = ttk.TTk()
740
container = ttk.TTkContainer(parent=root)
741
layout = ttk.TTkVBoxLayout()
742
743
# Color picker buttons
744
color_btn1 = ttk.TTkColorButtonPicker(text="Background Color")
745
color_btn2 = ttk.TTkColorButtonPicker(text="Text Color")
746
747
# Sample text widget to demonstrate colors
748
sample_text = ttk.TTkLabel(text="Sample text with selected colors")
749
sample_text.setColor(ttk.TTkColor.WHITE())
750
751
# Color display
752
bg_color_label = ttk.TTkLabel(text="Background: White")
753
text_color_label = ttk.TTkLabel(text="Text Color: White")
754
755
current_bg_color = ttk.TTkColor.WHITE()
756
current_text_color = ttk.TTkColor.BLACK()
757
758
@ttk.pyTTkSlot(ttk.TTkColor)
759
def background_color_changed(color):
760
global current_bg_color
761
current_bg_color = color
762
763
# Update sample text
764
new_color = ttk.TTkColor(fg=current_text_color.foreground(),
765
bg=color.foreground())
766
sample_text.setColor(new_color)
767
768
# Update label
769
bg_color_label.setText(f"Background: {color.foreground()}")
770
771
@ttk.pyTTkSlot(ttk.TTkColor)
772
def text_color_changed(color):
773
global current_text_color
774
current_text_color = color
775
776
# Update sample text
777
new_color = ttk.TTkColor(fg=color.foreground(),
778
bg=current_bg_color.foreground())
779
sample_text.setColor(new_color)
780
781
# Update label
782
text_color_label.setText(f"Text Color: {color.foreground()}")
783
784
# Connect color change signals
785
color_btn1.colorChanged.connect(background_color_changed)
786
color_btn2.colorChanged.connect(text_color_changed)
787
788
# Custom color dialog button
789
dialog_btn = ttk.TTkButton(text="Advanced Color Dialog")
790
791
@ttk.pyTTkSlot()
792
def show_color_dialog():
793
color = ttk.TTkColorDialogPicker.getColor(
794
initial=current_text_color,
795
parent=root,
796
title="Select Color"
797
)
798
799
if color.isValid():
800
text_color_changed(color)
801
color_btn2.setColor(color)
802
803
dialog_btn.clicked.connect(show_color_dialog)
804
805
# Layout
806
layout.addWidget(ttk.TTkLabel(text="Color Picker Demo"))
807
layout.addWidget(color_btn1)
808
layout.addWidget(color_btn2)
809
layout.addWidget(dialog_btn)
810
layout.addWidget(bg_color_label)
811
layout.addWidget(text_color_label)
812
layout.addStretch(1)
813
layout.addWidget(sample_text)
814
815
container.setLayout(layout)
816
root.mainloop()
817
```
818
819
### Text Input Dialogs
820
821
```python
822
import TermTk as ttk
823
824
root = ttk.TTk()
825
container = ttk.TTkContainer(parent=root)
826
layout = ttk.TTkVBoxLayout()
827
828
# Input dialog buttons
829
text_btn = ttk.TTkButton(text="Get Text Input")
830
multiline_btn = ttk.TTkButton(text="Get Multiline Text")
831
item_btn = ttk.TTkButton(text="Select Item")
832
833
# Results display
834
result_text = ttk.TTkTextEdit()
835
result_text.setText("Input results will appear here...")
836
837
@ttk.pyTTkSlot()
838
def get_text_input():
839
text, ok = ttk.TTkTextDialogPicker.getText(
840
root,
841
"Text Input",
842
"Enter your name:",
843
"Default Name"
844
)
845
846
if ok:
847
result_text.append(f"Text input: {text}")
848
else:
849
result_text.append("Text input cancelled")
850
851
@ttk.pyTTkSlot()
852
def get_multiline_input():
853
text, ok = ttk.TTkTextDialogPicker.getMultiLineText(
854
root,
855
"Multiline Input",
856
"Enter your message:",
857
"Default\nmultiline\ntext"
858
)
859
860
if ok:
861
result_text.append(f"Multiline input:\n{text}")
862
else:
863
result_text.append("Multiline input cancelled")
864
865
@ttk.pyTTkSlot()
866
def get_item_selection():
867
items = ["Option 1", "Option 2", "Option 3", "Option 4"]
868
item, ok = ttk.TTkTextDialogPicker.getItem(
869
root,
870
"Item Selection",
871
"Choose an option:",
872
items,
873
current=0,
874
editable=False
875
)
876
877
if ok:
878
result_text.append(f"Selected item: {item}")
879
else:
880
result_text.append("Item selection cancelled")
881
882
# Connect buttons
883
text_btn.clicked.connect(get_text_input)
884
multiline_btn.clicked.connect(get_multiline_input)
885
item_btn.clicked.connect(get_item_selection)
886
887
# Layout
888
button_layout = ttk.TTkHBoxLayout()
889
button_layout.addWidget(text_btn)
890
button_layout.addWidget(multiline_btn)
891
button_layout.addWidget(item_btn)
892
893
layout.addWidget(ttk.TTkLabel(text="Text Input Dialog Demo"))
894
layout.addLayout(button_layout)
895
layout.addWidget(result_text)
896
897
container.setLayout(layout)
898
root.mainloop()
899
```