CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pytermtk

Python Terminal Toolkit for creating sophisticated text-based user interfaces with Qt-like API and full widget support

Pending
Overview
Eval results
Files

file-dialogs.mddocs/

File and Dialog Operations

File operations, dialog widgets, and cross-platform utilities for common application tasks.

Capabilities

File Dialog Pickers

Dialog widgets for file and directory selection operations.

class TTkFileDialogPicker(TTkWidget):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a file dialog picker.
        
        Parameters:
        - path (str): Initial directory path
        - filter (str): File filter string
        - caption (str): Dialog caption
        """
    
    def getOpenFileName(self, caption="", dir="", filter=""):
        """
        Get filename for opening a file.
        
        Parameters:
        - caption (str): Dialog title
        - dir (str): Initial directory
        - filter (str): File type filter
        
        Returns:
        str: Selected filename or empty string if cancelled
        """
    
    def getOpenFileNames(self, caption="", dir="", filter=""):
        """
        Get multiple filenames for opening files.
        
        Parameters:
        - caption (str): Dialog title
        - dir (str): Initial directory
        - filter (str): File type filter
        
        Returns:
        list: List of selected filenames
        """
    
    def getSaveFileName(self, caption="", dir="", filter=""):
        """
        Get filename for saving a file.
        
        Parameters:
        - caption (str): Dialog title
        - dir (str): Initial directory
        - filter (str): File type filter
        
        Returns:
        str: Selected filename or empty string if cancelled
        """
    
    def getExistingDirectory(self, caption="", dir=""):
        """
        Get existing directory path.
        
        Parameters:
        - caption (str): Dialog title
        - dir (str): Initial directory
        
        Returns:
        str: Selected directory path
        """
    
    def setPath(self, path):
        """Set current directory path."""
    
    def path(self):
        """Get current directory path."""
    
    def setFilter(self, filter_str):
        """Set file filter string."""
    
    def filter(self):
        """Get current file filter."""
    
    def setCaption(self, caption):
        """Set dialog caption."""
    
    def caption(self):
        """Get dialog caption."""
    
    # Signals
    fileSelected: pyTTkSignal  # Emitted when file is selected
    filesSelected: pyTTkSignal  # Emitted when multiple files are selected

class TTkFileButtonPicker(TTkButton):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a file picker button.
        
        Parameters:
        - path (str): Initial file path
        - filter (str): File filter string
        - caption (str): Dialog caption
        - fileMode (int): File selection mode (open, save, directory)
        """
    
    def setPath(self, path):
        """Set current file path."""
    
    def path(self):
        """Get current file path."""
    
    def setFilter(self, filter_str):
        """Set file filter."""
    
    def filter(self):
        """Get file filter."""
    
    def setCaption(self, caption):
        """Set dialog caption."""
    
    def caption(self):
        """Get dialog caption."""
    
    def setFileMode(self, mode):
        """Set file selection mode."""
    
    def fileMode(self):
        """Get file selection mode."""
    
    # Signals
    fileChanged: pyTTkSignal  # Emitted when file selection changes

Message Box Dialogs

Standard message dialogs for user notifications and confirmations.

class TTkMessageBox(TTkWindow):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a message box dialog.
        
        Parameters:
        - title (str): Dialog title
        - text (str): Main message text
        - informativeText (str): Additional information text
        - icon (int): Icon type constant
        """
    
    def setText(self, text):
        """Set main message text."""
    
    def text(self):
        """Get main message text."""
    
    def setInformativeText(self, text):
        """Set informative text."""
    
    def informativeText(self):
        """Get informative text."""
    
    def setDetailedText(self, text):
        """Set detailed text (expandable)."""
    
    def detailedText(self):
        """Get detailed text."""
    
    def setIcon(self, icon):
        """Set message box icon."""
    
    def icon(self):
        """Get message box icon."""
    
    def setStandardButtons(self, buttons):
        """Set standard button combination."""
    
    def standardButtons(self):
        """Get standard buttons."""
    
    def setDefaultButton(self, button):
        """Set default button."""
    
    def defaultButton(self):
        """Get default button."""
    
    def addButton(self, text, role):
        """Add custom button."""
    
    def removeButton(self, button):
        """Remove button."""
    
    def exec(self):
        """Execute dialog and return result."""
    
    # Static convenience methods
    @staticmethod
    def information(parent, title, text, buttons=None):
        """Show information message."""
    
    @staticmethod
    def question(parent, title, text, buttons=None):
        """Show question dialog."""
    
    @staticmethod
    def warning(parent, title, text, buttons=None):
        """Show warning message."""
    
    @staticmethod
    def critical(parent, title, text, buttons=None):
        """Show critical error message."""
    
    @staticmethod
    def about(parent, title, text):
        """Show about dialog."""
    
    # Signals
    buttonClicked: pyTTkSignal  # Emitted when button is clicked

Color Picker Dialogs

Color selection dialogs for choosing colors interactively.

class TTkColorButtonPicker(TTkButton):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a color picker button.
        
        Parameters:
        - color (TTkColor): Initial color
        - showAlpha (bool): Show alpha channel control
        """
    
    def setColor(self, color):
        """Set current color."""
    
    def color(self):
        """Get current color."""
    
    def setShowAlpha(self, show):
        """Show/hide alpha channel control."""
    
    def showAlpha(self):
        """Check if alpha channel is shown."""
    
    def setColorDialogOptions(self, options):
        """Set color dialog options."""
    
    def colorDialogOptions(self):
        """Get color dialog options."""
    
    # Signals
    colorChanged: pyTTkSignal  # Emitted when color changes

class TTkColorDialogPicker(TTkWindow):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a color dialog picker.
        
        Parameters:
        - color (TTkColor): Initial color
        - showAlpha (bool): Show alpha channel
        """
    
    def setCurrentColor(self, color):
        """Set current selected color."""
    
    def currentColor(self):
        """Get current selected color."""
    
    def selectedColor(self):
        """Get final selected color."""
    
    def setOption(self, option, on=True):
        """Set dialog option."""
    
    def testOption(self, option):
        """Test if option is enabled."""
    
    def setOptions(self, options):
        """Set multiple dialog options."""
    
    def options(self):
        """Get current dialog options."""
    
    def exec(self):
        """Execute dialog and return result."""
    
    # Static convenience method
    @staticmethod
    def getColor(initial=None, parent=None, title="", options=0):
        """Get color from user selection."""
    
    # Signals
    colorSelected: pyTTkSignal  # Emitted when color is selected
    currentColorChanged: pyTTkSignal  # Emitted when current color changes

Text Picker Dialogs

Text input and selection dialogs for string values.

class TTkTextPicker(TTkWidget):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a text picker widget.
        
        Parameters:
        - text (str): Initial text
        - multiline (bool): Allow multiple lines
        """
    
    def setText(self, text):
        """Set current text."""
    
    def text(self):
        """Get current text."""
    
    def setMultiline(self, multiline):
        """Enable/disable multiline mode."""
    
    def isMultiline(self):
        """Check if multiline mode is enabled."""
    
    def setPlaceholderText(self, text):
        """Set placeholder text."""
    
    def placeholderText(self):
        """Get placeholder text."""
    
    def setReadOnly(self, readOnly):
        """Set read-only mode."""
    
    def isReadOnly(self):
        """Check if in read-only mode."""
    
    # Signals
    textChanged: pyTTkSignal  # Emitted when text changes

class TTkTextDialogPicker(TTkWindow):
    def __init__(self, parent=None, **kwargs):
        """
        Initialize a text dialog picker.
        
        Parameters:
        - title (str): Dialog title
        - label (str): Input label text
        - text (str): Initial text
        """
    
    def setLabelText(self, text):
        """Set input label text."""
    
    def labelText(self):
        """Get input label text."""
    
    def setTextValue(self, text):
        """Set text value."""
    
    def textValue(self):
        """Get text value."""
    
    def setInputMode(self, mode):
        """Set input mode (normal, password, etc.)."""
    
    def inputMode(self):
        """Get input mode."""
    
    def exec(self):
        """Execute dialog and return result."""
    
    # Static convenience methods
    @staticmethod
    def getText(parent, title, label, text=""):
        """Get text input from user."""
    
    @staticmethod
    def getMultiLineText(parent, title, label, text=""):
        """Get multi-line text input from user."""
    
    @staticmethod
    def getItem(parent, title, label, items, current=0, editable=True):
        """Get item selection from user."""
    
    # Signals
    textValueChanged: pyTTkSignal  # Emitted when text value changes

Cross-Platform File Operations

Utilities for cross-platform file operations and system integration.

def ttkCrossOpen(filename):
    """
    Open file with system default application.
    
    Parameters:
    - filename (str): Path to file to open
    
    Returns:
    bool: True if successful, False otherwise
    """

def ttkCrossSave(data, filename, encoding="utf-8"):
    """
    Save data to file with cross-platform compatibility.
    
    Parameters:
    - data: Data to save (string or bytes)
    - filename (str): Target filename
    - encoding (str): Text encoding for string data
    
    Returns:
    bool: True if successful, False otherwise
    """

def ttkCrossSaveAs(data, title="Save As", filter="", encoding="utf-8"):
    """
    Save data with file dialog selection.
    
    Parameters:
    - data: Data to save
    - title (str): Dialog title
    - filter (str): File type filter
    - encoding (str): Text encoding
    
    Returns:
    str: Selected filename or empty string if cancelled
    """

class TTkEncoding:
    """Encoding utilities for cross-platform compatibility."""
    
    @staticmethod
    def detectEncoding(filename):
        """
        Detect file encoding.
        
        Parameters:
        - filename (str): File to analyze
        
        Returns:
        str: Detected encoding name
        """
    
    @staticmethod
    def convertEncoding(text, from_encoding, to_encoding):
        """
        Convert text between encodings.
        
        Parameters:
        - text (str): Text to convert
        - from_encoding (str): Source encoding
        - to_encoding (str): Target encoding
        
        Returns:
        str: Converted text
        """
    
    @staticmethod
    def availableEncodings():
        """
        Get list of available encodings.
        
        Returns:
        list: Available encoding names
        """

class ImageData:
    """Image data handling utilities."""
    
    def __init__(self, data=None, format="PNG"):
        """
        Initialize image data.
        
        Parameters:
        - data: Image data (bytes or file path)
        - format (str): Image format
        """
    
    def loadFromFile(self, filename):
        """Load image from file."""
    
    def saveToFile(self, filename, format=None):
        """Save image to file."""
    
    def size(self):
        """Get image size as (width, height)."""
    
    def format(self):
        """Get image format."""
    
    def data(self):
        """Get raw image data."""
    
    def toBase64(self):
        """Convert to base64 string."""
    
    @staticmethod
    def fromBase64(base64_string):
        """Create ImageData from base64 string."""

# Drag and drop utilities
def ttkConnectDragOpen(widget, callback):
    """
    Connect drag-and-drop file opening to widget.
    
    Parameters:
    - widget: Target widget for drag operations
    - callback: Function to call with list of dropped files
    """

def ttkEmitDragOpen(files):
    """
    Emit drag-open event with file list.
    
    Parameters:
    - files (list): List of file paths
    """

def ttkEmitFileOpen(filename):
    """
    Emit file-open event.
    
    Parameters:
    - filename (str): File path to open
    """

Usage Examples

File Operations Dialog

import TermTk as ttk

root = ttk.TTk()
container = ttk.TTkContainer(parent=root)
layout = ttk.TTkVBoxLayout()

# File operation buttons
open_btn = ttk.TTkButton(text="Open File")
save_btn = ttk.TTkButton(text="Save File")
open_dir_btn = ttk.TTkButton(text="Select Directory")

# File path display
path_label = ttk.TTkLabel(text="No file selected")
content_text = ttk.TTkTextEdit()

# File operations
current_file = ""

@ttk.pyTTkSlot()
def open_file():
    global current_file
    filename = ttk.TTkFileDialogPicker.getOpenFileName(
        caption="Open File",
        filter="Text Files (*.txt);;Python Files (*.py);;All Files (*)"
    )
    
    if filename:
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                content = f.read()
                content_text.setText(content)
                current_file = filename
                path_label.setText(f"Opened: {filename}")
        except Exception as e:
            ttk.TTkMessageBox.critical(
                root, 
                "Error", 
                f"Failed to open file:\n{str(e)}"
            )

@ttk.pyTTkSlot()
def save_file():
    global current_file
    content = content_text.text()
    
    if current_file:
        # Save to current file
        try:
            ttkCrossSave(content, current_file)
            path_label.setText(f"Saved: {current_file}")
        except Exception as e:
            ttk.TTkMessageBox.critical(
                root,
                "Error", 
                f"Failed to save file:\n{str(e)}"
            )
    else:
        # Save as new file
        filename = ttk.TTkFileDialogPicker.getSaveFileName(
            caption="Save File",
            filter="Text Files (*.txt);;Python Files (*.py);;All Files (*)"
        )
        
        if filename:
            try:
                ttkCrossSave(content, filename)
                current_file = filename
                path_label.setText(f"Saved: {filename}")
            except Exception as e:
                ttk.TTkMessageBox.critical(
                    root,
                    "Error",
                    f"Failed to save file:\n{str(e)}"
                )

@ttk.pyTTkSlot()
def select_directory():
    directory = ttk.TTkFileDialogPicker.getExistingDirectory(
        caption="Select Directory"
    )
    
    if directory:
        path_label.setText(f"Selected directory: {directory}")

# Connect buttons
open_btn.clicked.connect(open_file)
save_btn.clicked.connect(save_file)
open_dir_btn.clicked.connect(select_directory)

# Layout
button_layout = ttk.TTkHBoxLayout()
button_layout.addWidget(open_btn)
button_layout.addWidget(save_btn)
button_layout.addWidget(open_dir_btn)
button_layout.addStretch(1)

layout.addLayout(button_layout)
layout.addWidget(path_label)
layout.addWidget(content_text)

container.setLayout(layout)
root.mainloop()

Message Box Examples

import TermTk as ttk

root = ttk.TTk()
container = ttk.TTkContainer(parent=root)
layout = ttk.TTkVBoxLayout()

# Message box demonstration buttons
info_btn = ttk.TTkButton(text="Information")
question_btn = ttk.TTkButton(text="Question")
warning_btn = ttk.TTkButton(text="Warning")
error_btn = ttk.TTkButton(text="Error")
about_btn = ttk.TTkButton(text="About")

result_label = ttk.TTkLabel(text="Click a button to show message box")

@ttk.pyTTkSlot()
def show_information():
    ttk.TTkMessageBox.information(
        root,
        "Information",
        "This is an information message.\nIt provides helpful details to the user."
    )
    result_label.setText("Information dialog was shown")

@ttk.pyTTkSlot()
def show_question():
    result = ttk.TTkMessageBox.question(
        root,
        "Question",
        "Do you want to continue with this operation?",
        buttons=ttk.TTkMessageBox.Yes | ttk.TTkMessageBox.No
    )
    
    if result == ttk.TTkMessageBox.Yes:
        result_label.setText("User clicked Yes")
    else:
        result_label.setText("User clicked No")

@ttk.pyTTkSlot()
def show_warning():
    ttk.TTkMessageBox.warning(
        root,
        "Warning",
        "This action cannot be undone.\nAre you sure you want to proceed?"
    )
    result_label.setText("Warning dialog was shown")

@ttk.pyTTkSlot()
def show_error():
    ttk.TTkMessageBox.critical(
        root,
        "Error",
        "An error occurred while processing your request.\n\nError details:\n- Connection timeout\n- Server unavailable"
    )
    result_label.setText("Error dialog was shown")

@ttk.pyTTkSlot()
def show_about():
    ttk.TTkMessageBox.about(
        root,
        "About My Application",
        "My Application v1.0\n\nBuilt with pyTermTk\nCopyright © 2024"
    )
    result_label.setText("About dialog was shown")

# Connect buttons
info_btn.clicked.connect(show_information)
question_btn.clicked.connect(show_question)
warning_btn.clicked.connect(show_warning)
error_btn.clicked.connect(show_error)
about_btn.clicked.connect(show_about)

# Layout
button_layout = ttk.TTkHBoxLayout()
button_layout.addWidget(info_btn)
button_layout.addWidget(question_btn)
button_layout.addWidget(warning_btn)
button_layout.addWidget(error_btn)
button_layout.addWidget(about_btn)

layout.addLayout(button_layout)
layout.addWidget(result_label)

container.setLayout(layout)
root.mainloop()

Color Picker Integration

import TermTk as ttk

root = ttk.TTk()
container = ttk.TTkContainer(parent=root)
layout = ttk.TTkVBoxLayout()

# Color picker buttons
color_btn1 = ttk.TTkColorButtonPicker(text="Background Color")
color_btn2 = ttk.TTkColorButtonPicker(text="Text Color")

# Sample text widget to demonstrate colors
sample_text = ttk.TTkLabel(text="Sample text with selected colors")
sample_text.setColor(ttk.TTkColor.WHITE())

# Color display
bg_color_label = ttk.TTkLabel(text="Background: White")
text_color_label = ttk.TTkLabel(text="Text Color: White")

current_bg_color = ttk.TTkColor.WHITE()
current_text_color = ttk.TTkColor.BLACK()

@ttk.pyTTkSlot(ttk.TTkColor)
def background_color_changed(color):
    global current_bg_color
    current_bg_color = color
    
    # Update sample text
    new_color = ttk.TTkColor(fg=current_text_color.foreground(), 
                           bg=color.foreground())
    sample_text.setColor(new_color)
    
    # Update label
    bg_color_label.setText(f"Background: {color.foreground()}")

@ttk.pyTTkSlot(ttk.TTkColor)
def text_color_changed(color):
    global current_text_color
    current_text_color = color
    
    # Update sample text
    new_color = ttk.TTkColor(fg=color.foreground(),
                           bg=current_bg_color.foreground())
    sample_text.setColor(new_color)
    
    # Update label
    text_color_label.setText(f"Text Color: {color.foreground()}")

# Connect color change signals
color_btn1.colorChanged.connect(background_color_changed)
color_btn2.colorChanged.connect(text_color_changed)

# Custom color dialog button
dialog_btn = ttk.TTkButton(text="Advanced Color Dialog")

@ttk.pyTTkSlot()
def show_color_dialog():
    color = ttk.TTkColorDialogPicker.getColor(
        initial=current_text_color,
        parent=root,
        title="Select Color"
    )
    
    if color.isValid():
        text_color_changed(color)
        color_btn2.setColor(color)

dialog_btn.clicked.connect(show_color_dialog)

# Layout
layout.addWidget(ttk.TTkLabel(text="Color Picker Demo"))
layout.addWidget(color_btn1)
layout.addWidget(color_btn2)
layout.addWidget(dialog_btn)
layout.addWidget(bg_color_label)
layout.addWidget(text_color_label)
layout.addStretch(1)
layout.addWidget(sample_text)

container.setLayout(layout)
root.mainloop()

Text Input Dialogs

import TermTk as ttk

root = ttk.TTk()
container = ttk.TTkContainer(parent=root)
layout = ttk.TTkVBoxLayout()

# Input dialog buttons
text_btn = ttk.TTkButton(text="Get Text Input")
multiline_btn = ttk.TTkButton(text="Get Multiline Text")
item_btn = ttk.TTkButton(text="Select Item")

# Results display
result_text = ttk.TTkTextEdit()
result_text.setText("Input results will appear here...")

@ttk.pyTTkSlot()
def get_text_input():
    text, ok = ttk.TTkTextDialogPicker.getText(
        root,
        "Text Input",
        "Enter your name:",
        "Default Name"
    )
    
    if ok:
        result_text.append(f"Text input: {text}")
    else:
        result_text.append("Text input cancelled")

@ttk.pyTTkSlot()
def get_multiline_input():
    text, ok = ttk.TTkTextDialogPicker.getMultiLineText(
        root,
        "Multiline Input",
        "Enter your message:",
        "Default\nmultiline\ntext"
    )
    
    if ok:
        result_text.append(f"Multiline input:\n{text}")
    else:
        result_text.append("Multiline input cancelled")

@ttk.pyTTkSlot()
def get_item_selection():
    items = ["Option 1", "Option 2", "Option 3", "Option 4"]
    item, ok = ttk.TTkTextDialogPicker.getItem(
        root,
        "Item Selection",
        "Choose an option:",
        items,
        current=0,
        editable=False
    )
    
    if ok:
        result_text.append(f"Selected item: {item}")
    else:
        result_text.append("Item selection cancelled")

# Connect buttons
text_btn.clicked.connect(get_text_input)
multiline_btn.clicked.connect(get_multiline_input)
item_btn.clicked.connect(get_item_selection)

# Layout
button_layout = ttk.TTkHBoxLayout()
button_layout.addWidget(text_btn)
button_layout.addWidget(multiline_btn)
button_layout.addWidget(item_btn)

layout.addWidget(ttk.TTkLabel(text="Text Input Dialog Demo"))
layout.addLayout(button_layout)
layout.addWidget(result_text)

container.setLayout(layout)
root.mainloop()

Install with Tessl CLI

npx tessl i tessl/pypi-pytermtk

docs

color-drawing.md

container-widgets.md

core-widgets.md

display-widgets.md

event-system.md

file-dialogs.md

index.md

input-widgets.md

layouts.md

model-view.md

text-editing.md

utilities.md

tile.json