### Python TTkFileTreeWidget Quickstart Example Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkModelView/filetreewidget Demonstrates how to integrate the TTkFileTreeWidget into a TermTk application. It shows the basic setup of a root window and the instantiation of the file tree, starting from the current directory. ```python import TermTk as ttk root = ttk.TTk(layout=ttk.TTkGridLayout()) fileTree = ttk.TTkFileTree(parent=root, path='.') root.mainloop() ``` -------------------------------- ### Quickstart: TTkColorButtonPicker Example in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkPickers/colorpicker This code snippet demonstrates how to use the TTkColorButtonPicker widget in TermTk. It shows how to create the button, connect its color selection signals (colorSelectedFG, colorSelectedBG) to labels, and run the TermTk event loop. This example requires the TermTk library to be installed. ```python import TermTk as ttk root = ttk.TTk() btn = ttk.TTkColorButtonPicker( parent=root, size=(8,3), border=True, color=ttk.TTkColor.RED ) lfg = ttk.TTkLabel(parent=root, pos=(0,3), text="Test FG") lbg = ttk.TTkLabel(parent=root, pos=(0,4), text="Test BG") btn.colorSelectedFG.connect(lfg.setColor) btn.colorSelectedBG.connect(lbg.setColor) root.mainloop() ``` -------------------------------- ### TTkTerminal Widget Quickstart - Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_autosummary/TermTk.TTkWidgets.TTkTerminal This snippet demonstrates the basic usage of the TTkTerminal widget. It initializes the TTk application, creates a window, embeds a TTkTerminal widget within it, and then runs a shell process within the terminal. This is a foundational example for integrating terminal emulation into a GUI application. ```python import TermTk as ttk root = ttk.TTk(mouseTrack=True) win = ttk.TTkWindow(parent=root, title="Terminal", size=(80+2,24+4), layout=ttk.TTkGridLayout()) term = ttk.TTkTerminal(parent=win) th = ttk.TTkTerminalHelper(term=term) th.runShell() root.mainloop() ``` -------------------------------- ### Demonstrate pyTermTk Clipboard Behavior Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/resources/clipboard This example shows how pyTermTk interacts with the system clipboard. It demonstrates the behavior when no clipboard managers are installed versus when pyperclip is installed, highlighting the synchronization with the system clipboard. ```python # Assuming no clipboard managers are installed # you can still copy/paste between editors in this session # but no text is copied to/from the system clipboard python3 demo/showcase/textedit.py # if pyperclip is installed, # pyTermTk defaults the clipboard manager to this tool # any copy/paste is synced with the system clipboard # it is possible to copy/paste from/to an external editor pip install pyperclip python3 demo/showcase/textedit.py ``` -------------------------------- ### Install pyTermTk in a Virtual Environment - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Sets up a Python virtual environment, activates it, installs pyTermTk within it, and provides commands to clean up the environment. This ensures project dependencies are isolated. ```bash # Create a venv environment in the ".venv" folder python3 -m venv .venv . .venv/bin/activate # Install inside the venv environment pip3 install --upgrade pyTermTk # ... Do you Stuff # Clear/Erase/GetRidOf the venv rm -rf .venv ``` -------------------------------- ### Initialize and Run a PTY Terminal Session with TTkTerminalHelper (Python) Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkTerminal/terminalhelper This snippet demonstrates how to initialize a TTkTerminalHelper and run a shell session within a TTkTerminal widget. It covers importing necessary modules, creating the root and terminal windows, attaching the terminal to the helper, and starting the main loop. This is a basic example for integrating a terminal emulator. ```python import TermTk as ttk root = ttk.TTk(mouseTrack=True) win = ttk.TTkWindow(parent=root, title="Terminal", size=(80+2,24+4), layout=ttk.TTkGridLayout()) term = ttk.TTkTerminal(parent=win) th = ttk.TTkTerminalHelper(term=term) th.runShell() root.mainloop() ``` -------------------------------- ### Install pyTermTk Globally - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Installs or upgrades pyTermTk globally using pip3. This command is suitable for user-level or system-wide installations. ```bash # User/Global Install pip3 install --upgrade pyTermTk ``` -------------------------------- ### Python Imports for PyTermTk Examples Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tests%2Ft.ui%2Ftest.ui.026.toolTip This section imports necessary modules for PyTermTk development, including system and OS functionalities, argument parsing, regular expressions, and random number generation. It also appends a custom path to sys.path to import the TermTk library and various demo modules. ```python import sys, os, argparse import re import random sys.path.append(os.path.join(sys.path[0],'../libs/pyTermTk')) import TermTk as ttk from showcase.layout_basic import demoLayout from showcase.layout_nested import demoLayoutNested from showcase.layout_span import demoLayoutSpan from showcase.tab import demoTab from showcase.graph import demoGraph from showcase.splitter import demoSplitter from showcase.windows import demoWindows from showcase.windowsflags import demoWindowsFlags from showcase.formwidgets02 import demoFormWidgets from showcase.scrollarea01 import demoScrollArea01 from showcase.scrollarea02 import demoScrollArea02 from showcase.list import demoList from showcase.menubar import demoMenuBar from showcase.filepicker import demoFilePicker from showcase.colorpicker import demoColorPicker from showcase.textpicker import demoTextPicker from showcase.tree import demoTree from showcase.table import demoTTkTable from showcase.fancytable import demoFancyTable from showcase.fancytree import demoFancyTree from showcase.textedit import demoTextEdit from showcase.dragndrop import demoDnD from showcase.dndtabs import demoDnDTabs from showcase.sigmask import demoSigmask from showcase.apptemplate import demoAppTemplate ``` -------------------------------- ### Initialize and Use TTkClipboard in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkGui/clipboard This example demonstrates how to initialize the TTkClipboard manager and use its methods to set and get text from the clipboard. It requires the TTkClipboard class to be imported from the TermTk library. ```python from TermTk import TTkClipboard # Initialize the clipboard manager clipboard = TTkClipboard() # Push some text to the clipboard clipboard.setText("Example") # Get the text from the clipboard text = clipboard.text() ``` -------------------------------- ### Python TTkTreeWidget Usage Example Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkModelView/treewidget Demonstrates how to create and populate a TTkTreeWidget. It initializes the TTk environment, creates a tree widget, sets header labels, adds a top-level item, and appends child items to the top-level item. This example requires the TermTk library. ```python import TermTk as ttk root = ttk.TTk() tree = ttk.TTkTree(parent=root,size=(80,24)) tree.setHeaderLabels(["Column 1", "Column 2", "Column 3"]) top = ttk.TTkTreeWidgetItem(["String A", "String B", "String C"]) tree.addTopLevelItem(top) for i in range(5): child = ttk.TTkTreeWidgetItem(["Child A" + str(i), "Child B" + str(i), "Child C" + str(i)]) top.addChild(child) root.mainloop() ``` -------------------------------- ### pyTermTk: GridLayout Example with Buttons Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/002-layout Illustrates the usage of TTkGridLayout in pyTermTk to arrange widgets in a grid. This example shows how to add buttons to specific positions within the grid. It requires the TermTk library and optionally accepts column minimum height and width. ```python import TermTk as ttk # Set the GridLayout as default in the terminal widget gridLayout = ttk.TTkGridLayout(columnMinHeight=0,columnMinWidth=2) root = ttk.TTk(layout=gridLayout) # Attach 2 buttons to the root widget using the default method # this will append them to the first row ttk.TTkButton(parent=root, border=True, text="Button1") ttk.TTkButton(parent=root, border=True, text="Button2") # Attach 2 buttons to a specific position in the grid gridLayout.addWidget(ttk.TTkButton(parent=root, border=True, text="Button3"), 1,2) gridLayout.addWidget(ttk.TTkButton(parent=root, border=True, text="Button4"), 3,4) root.mainloop() ``` -------------------------------- ### Run pyTermTk Showcase Demos - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Executes specific showcase applications from the pyTermTk repository. These demos highlight advanced features like text editing, animations, and UI components. ```bash # Demo - Text Editor python3 demo/showcase/textedit.py # Demo - Animation python3 demo/showcase/animation.01.py # Demo - color picker python3 demo/showcase/colorpicker.py # Demo - file picker python3 demo/showcase/filepicker.py # Demo - drag & drop python3 demo/showcase/dragndrop.py # Demo - d&d with tabs python3 demo/showcase/dndtabs.py # Demo - d&d with list python3 demo/showcase/list.py # Demo - base widgets python3 demo/showcase/formwidgets02.py # Demo - messagebox python3 demo/showcase/messagebox.py # Demo - splitter python3 demo/showcase/splitter.py # Demo - Windows python3 demo/showcase/windowsflags.py # Demo - AppTemplate python3 demo/showcase/apptemplate.py # Demo - Tooltip python3 tests/t.ui/test.ui.026.toolTip.py ``` -------------------------------- ### Get Line Number Starting Value Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/texedit Retrieves the starting number for the line number ruler. This determines the initial number displayed in the line number column. ```Python def lineNumberStarting(self): '''lineNumberStarting''' ``` -------------------------------- ### Create Hello World GUI with pyTermTk Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/001-helloworld Demonstrates the basic steps to create a simple 'Hello World' GUI application using pyTermTk. This involves importing the library, creating a root TTk object, adding a TTkLabel with specific text and position, and starting the application's main loop. ```python import TermTk as ttk root = ttk.TTk() ttk.TTkLabel(parent=root, pos=(5,2), text="Hello World") root.mainloop() ``` -------------------------------- ### Run TextEdit with Pygments Highlight - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Executes the pyTermTk TextEdit demo with Pygments syntax highlighting integration, requiring Pygments to be installed. It takes a README.md file as an argument to demonstrate highlighting. ```bash # Text edit with "Pygments" highlight integrated # it require pygments # pip install pygments python3 tests/t.ui/test.ui.018.TextEdit.Pygments.py README.md ``` -------------------------------- ### Get Selection Start Position Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkGui/textcursor Retrieves the starting position of the current selection for the active cursor. This method is part of the TTkTextCursor class. It returns a _CP object representing the cursor position. ```python def selectionStart(self) -> _CP: return self._properties[self._cID].selectionStart() ``` -------------------------------- ### Create a Window with pyTermTk Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/001-helloworld Illustrates how to create a basic window application using pyTermTk. This example shows the creation of a root object, a TTkWindow with specified dimensions, title, and border, and a TTkLabel placed within that window. ```python import TermTk as ttk # Create a root object (it is a widget that represent the terminal) root = ttk.TTk() # Create a window and attach it to the root (parent=root) helloWin = ttk.TTkWindow(parent=root,pos = (1,1), size=(30,10), title="Hello Window", border=True) # Define the Label and attach it to the window (parent=helloWin) ttk.TTkLabel(parent=helloWin, pos=(5,5), text="Hello World") # Start the Main loop root.mainloop() ``` -------------------------------- ### Get Line Slice Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/filebuffer Retrieves a contiguous block of lines from the file, starting at a given line index and spanning a specified length. It utilizes the `getLine` method for each line in the slice. ```python [docs] def getSlice(self, line, length): ret = [] for i in range(line, line+length): ret.append(self.getLine(i)) return ret ``` -------------------------------- ### Run pyTermTk Demos - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Executes various demo applications included with the pyTermTk library. These commands demonstrate different functionalities and features of the library. ```bash # Run the main demo python3 demo/demo.py # Run the paint demo python3 demo/paint.py # Run the ttkode demo python3 demo/ttkode.py ``` -------------------------------- ### Get List of Parent Directories - TTkFileDialogPicker Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkPickers/filepicker Static method to generate a list of parent directories for a given path, starting from the path itself and going up to the root. This is used to populate the path lookup. ```python @staticmethod def _getListLook(path:str) -> list[str]: path = os.path.abspath(path) ret = [path] while True: path, e = os.path.split(path) if e: ret.append(path) if not path or path=='/' or path[1:]==':\': break return ret ``` -------------------------------- ### Run ttkDesigner tutorial file Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/ttkDesigner/textEdit/README This command allows you to quickly open and interact with a specific ttkDesigner project file. It requires the pyTermTk installation and is executed from the pyTermTk root directory. ```shell # You can quickly open this file using: ttkDesigner tutorial/ttkDesigner/textEdit/textEdit.01.tui.json ``` -------------------------------- ### Import PyTermTk and Showcase Modules Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fexamples%2FDragAndDrop%2Fdnd.01.basic This code imports the main TermTk (ttk) library and various showcase modules, demonstrating functionalities like basic layouts, nested layouts, tabs, graphs, windows, forms, scroll areas, lists, menus, file pickers, color pickers, text pickers, trees, tables, text editors, drag-and-drop, signal masks, and application templates. ```python sys.path.append(os.path.join(sys.path[0],'../libs/pyTermTk')) import TermTk as ttk from showcase.layout_basic import demoLayout from showcase.layout_nested import demoLayoutNested from showcase.layout_span import demoLayoutSpan from showcase.tab import demoTab from showcase.graph import demoGraph from showcase.splitter import demoSplitter from showcase.windows import demoWindows from showcase.windowsflags import demoWindowsFlags from showcase.formwidgets02 import demoFormWidgets from showcase.scrollarea01 import demoScrollArea01 from showcase.scrollarea02 import demoScrollArea02 from showcase.list import demoList from showcase.menubar import demoMenuBar from showcase.filepicker import demoFilePicker from showcase.colorpicker import demoColorPicker from showcase.textpicker import demoTextPicker from showcase.tree import demoTree from showcase.table import demoTTkTable from showcase.fancytable import demoFancyTable from showcase.fancytree import demoFancyTree from showcase.textedit import demoTextEdit from showcase.dragndrop import demoDnD from showcase.dndtabs import demoDnDTabs from showcase.sigmask import demoSigmask from showcase.apptemplate import demoAppTemplate ``` -------------------------------- ### Manage Terminal Signal Masks (Python) Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/drivers/term_unix_linux This snippet demonstrates how to manage terminal signal masks for interrupt, stop, suspend, and start signals using the termios module in Python. It includes functions to set and get these masks, overriding base class methods. It handles potential import errors for the termios module. ```python # MIT License # # Copyright (c) 2025 Eugenio Parodi # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. __all__ = ['TTkTerm'] import sys try: import termios except Exception as e: print(f'ERROR: {e}') exit(1) from ..TTkTerm.term_base import TTkTermBase from .term_unix_common import _TTkTerm class TTkTerm(_TTkTerm): @staticmethod def _setSigmask(mask, value=True): attr = termios.tcgetattr(sys.stdin) if mask & TTkTerm.Sigmask.CTRL_C: attr[6][termios.VINTR]= b'\x03' if value else 0 if mask & TTkTerm.Sigmask.CTRL_S: attr[6][termios.VSTOP]= b'\x13' if value else 0 if mask & TTkTerm.Sigmask.CTRL_Z: attr[6][termios.VSUSP]= b'\x1a' if value else 0 if mask & TTkTerm.Sigmask.CTRL_Q: attr[6][termios.VSTART]= b'\x11' if value else 0 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, attr) TTkTermBase.setSigmask = _setSigmask @staticmethod def _getSigmask(): mask = 0x00 attr = termios.tcgetattr(sys.stdin) mask |= TTkTerm.Sigmask.CTRL_C if attr[6][termios.VINTR] else 0 mask |= TTkTerm.Sigmask.CTRL_S if attr[6][termios.VSTOP] else 0 mask |= TTkTerm.Sigmask.CTRL_Z if attr[6][termios.VSUSP] else 0 mask |= TTkTerm.Sigmask.CTRL_Q if attr[6][termios.VSTART] else 0 return mask TTkTermBase.getSigmask = _getSigmask ``` -------------------------------- ### Initialize pyTermTk Environment Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Flogging%2Fexample3.customlogging Appends the pyTermTk library path to sys.path, allowing it to be imported. It then imports the main TermTk module as ttk, enabling the use of its UI components. ```python sys.path.append(os.path.join(sys.path[0],'../libs/pyTermTk')) import TermTk as ttk ``` -------------------------------- ### Initialize pyTermTk Window and Layout Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/005-calculator Initializes the pyTermTk root object, creates a main window with a title and dimensions, and sets a TTkGridLayout as the default layout for the window. This sets up the basic structure for the calculator interface. ```python import TermTk as ttk # Create a root object (it is a widget that represent the terminal) root = ttk.TTk() # Create a window and attach it to the root (parent=root) calculatorWin = ttk.TTkWindow(parent=root, pos=(1,1), size=(30,17), title="My first Calculator") # Create a grid layout and set it as default for the window winLayout = ttk.TTkGridLayout() calculatorWin.setLayout(winLayout) ``` -------------------------------- ### Search for Text in File and Get Line Indexes in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/filebuffer This Python method searches a file for lines containing specific text and returns a list of their indexes. It opens the file with 'replace' error handling and iterates through each line, appending the index if the text is found. The `id` variable used in the example appears to be a placeholder and might need correction to use the line index. ```python def search(self, txt): indexes = [] with open(self._filename, 'r', errors='replace', newline='\n') as infile: for line in infile: if txt in line: indexes.append(id) return indexes ``` -------------------------------- ### Import pyTermTk Demo Modules Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fcalculator%2Fcalculator.001 Imports various demo modules from the pyTermTk library, showcasing different UI components and layouts such as layouts, windows, widgets, and tables. ```python from showcase.layout_basic import demoLayout from showcase.layout_nested import demoLayoutNested from showcase.layout_span import demoLayoutSpan from showcase.tab import demoTab from showcase.graph import demoGraph from showcase.splitter import demoSplitter from showcase.windows import demoWindows from showcase.windowsflags import demoWindowsFlags from showcase.formwidgets02 import demoFormWidgets from showcase.scrollarea01 import demoScrollArea01 from showcase.scrollarea02 import demoScrollArea02 from showcase.list import demoList from showcase.menubar import demoMenuBar from showcase.filepicker import demoFilePicker from showcase.colorpicker import demoColorPicker from showcase.textpicker import demoTextPicker from showcase.tree import demoTree from showcase.table import demoTTkTable from showcase.fancytable import demoFancyTable from showcase.fancytree import demoFancyTree from showcase.textedit import demoTextEdit from showcase.dragndrop import demoDnD from showcase.dndtabs import demoDnDTabs from showcase.sigmask import demoSigmask from showcase.apptemplate import demoAppTemplate ``` -------------------------------- ### Start Fade Animation in TTkKeyPressView Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkTestWidgets/keypressview Initiates and starts the property animation for the fading effect. It sets the duration, start and end values, and the easing curve for the animation. Dependencies include TTkPropertyAnimation and TTkEasingCurve. ```python def _startFade(self): self._anim.setDuration(self._fadeDuration) self._anim.setStartValue(0) self._anim.setEndValue(1) self._anim.setEasingCurve(TTkEasingCurve.OutExpo) self._anim.start() ``` -------------------------------- ### Start TTkPropertyAnimation in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/propertyanimation Starts the property animation. This method sets the base time for the animation and connects the internal refresh method to the widget's paint execution signal to begin the animation loop. It also performs an initial refresh to set the starting state. ```python @pyTTkSlot() def start(self): self._baseTime = time.time() if TTkHelper._rootWidget: TTkHelper._rootWidget.paintExecuted.connect(self._refreshAnimation) self._refreshAnimation() ``` -------------------------------- ### Create a TTkWindow with Maximized Button Hint Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fcalculator%2Fcalculator.003 This snippet demonstrates how to create a TTkWindow using the TermTk library. It specifies window dimensions, title, layout, and flags to include maximize and close buttons. This is a foundational step for building any GUI application with TermTk. ```python sourceWin = ttk.TTkWindow(size=(100,40), title=file, layout=ttk.TTkGridLayout(), flags=ttk.TTkK.WindowFlag.WindowMaximizeButtonHint|ttk.TTkK.WindowFlag.WindowCloseButtonHint) ``` -------------------------------- ### Set Line Number Starting Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/texedit Sets the starting number for the line number display in the text edit. ```APIDOC ## POST /setLineNumberStarting ### Description Sets the starting number for the line number display. ### Method POST ### Endpoint /setLineNumberStarting ### Parameters #### Request Body - **starting** (int) - Required - The starting number for line numbering. ``` -------------------------------- ### Profiling with VizTracer Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/debug This section details how to use VizTracer for profiling pyTermTk applications. It includes installation instructions, how to generate a trace file, and how to view the results using Perfetto UI or vizviewer. VizTracer is effective for analyzing performance bottlenecks. ```bash # install cprofilev: # pip3 install viztracer viztracer --tracer_entries 10000010 tests/paint.py # View the results # loading the "result.json" in https://ui.perfetto.dev # or running vizviewer result.json ``` -------------------------------- ### Set TTkPropertyAnimation Start Value in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/propertyanimation Sets the initial value for the property being animated. This value is used as the starting point for the animation. ```python def setStartValue(self, startValue): self._startValue = startValue ``` -------------------------------- ### Import System Libraries in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fcalculator%2Fcalculator.002 This code imports essential Python system modules: `sys` for system-specific parameters and functions, `os` for operating system-dependent functionality, and `argparse` for parsing command-line arguments. ```python import sys, os, argparse ``` -------------------------------- ### Start pytermtk Input Loop (Emscripten) Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/ttk This function starts the pytermtk input loop, but it returns immediately if the platform is Emscripten, as the input handling differs in that environment. ```python def _mainLoop_2(self): if platform.system() == 'Emscripten': return TTkInput.start() ``` -------------------------------- ### Set Line Number Starting - Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/texedit Sets the starting number for line numbering in the text edit view. This method is part of the PyTermTk library and is decorated with a pyTTkSlot decorator, indicating it can be called as a slot in a Qt-like event system. It takes an integer argument representing the desired starting number and internally updates the line number view. ```python @pyTTkSlot(int) def setLineNumberStarting(self, starting): '''setLineNumberStarting''' self._lineNumberView._startingNumber = starting self._lineNumberView._wrapChanged() ``` -------------------------------- ### Python Imports for PyTermTk Showcase Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fcalculator%2Fcalculator.004 This snippet imports necessary modules and functionalities from the PyTermTk library and other standard Python libraries. It sets up the environment for running various showcase demos. ```python import sys, os, argparse import re import random sys.path.append(os.path.join(sys.path[0],'../libs/pyTermTk')) import TermTk as ttk from showcase.layout_basic import demoLayout from showcase.layout_nested import demoLayoutNested from showcase.layout_span import demoLayoutSpan from showcase.tab import demoTab from showcase.graph import demoGraph from showcase.splitter import demoSplitter from showcase.windows import demoWindows from showcase.windowsflags import demoWindowsFlags from showcase.formwidgets02 import demoFormWidgets from showcase.scrollarea01 import demoScrollArea01 from showcase.scrollarea02 import demoScrollArea02 from showcase.list import demoList from showcase.menubar import demoMenuBar from showcase.filepicker import demoFilePicker from showcase.colorpicker import demoColorPicker from showcase.textpicker import demoTextPicker from showcase.tree import demoTree from showcase.table import demoTTkTable from showcase.fancytable import demoFancyTable from showcase.fancytree import demoFancyTree from showcase.textedit import demoTextEdit from showcase.dragndrop import demoDnD from showcase.dndtabs import demoDnDTabs from showcase.sigmask import demoSigmask from showcase.apptemplate import demoAppTemplate ``` -------------------------------- ### TTkFileTree Initialization and Signals Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkModelView/filetree Documentation for the initialization of the TTkFileTree widget and its various signals, which are forwarded from TTkFileTreeWidget. ```APIDOC ## TTkFileTree ### Description A container widget that places TTkFileTreeWidget in a scrolling area with on-demand scroll bars. ### Method `__init__(self, **kwargs)` ### Parameters #### Keyword Arguments - `**kwargs`: Accepts keyword arguments, which are passed to the underlying TTkFileTreeWidget and TTkTree. ### Signals - **itemActivated** (pyTTkSignal): Emitted when the user activates an item (double-click or Enter). - **itemChanged** (pyTTkSignal): Emitted when the contents of an item's column change. - **itemClicked** (pyTTkSignal): Emitted when the user clicks inside the widget. - **itemExpanded** (pyTTkSignal): Emitted when an item is expanded. - **itemCollapsed** (pyTTkSignal): Emitted when an item is collapsed. - **itemDoubleClicked** (pyTTkSignal): Emitted when the user double-clicks an item. - **fileClicked** (pyTTkSignal): Emitted when a file item is clicked. - **folderClicked** (pyTTkSignal): Emitted when a folder item is clicked. - **fileDoubleClicked** (pyTTkSignal): Emitted when a file item is double-clicked. - **folderDoubleClicked** (pyTTkSignal): Emitted when a folder item is double-clicked. - **fileActivated** (pyTTkSignal): Emitted when a file item is activated. - **folderActivated** (pyTTkSignal): Emitted when a folder item is activated. ### Forwarded Methods - **openPath**(path) - **getOpenPath**() - **setFilter**(filter) ### Request Example ```python # Example of initializing TTkFileTree and connecting a signal from TermTk.TTkWidgets.TTkModelView.filetree import TTkFileTree file_tree = TTkFileTree() def on_file_clicked(item): print(f"File clicked: {item.text()}") file_tree.fileClicked.connect(on_file_clicked) ``` ### Response Example (Signals) When `fileClicked` is emitted, the connected slot receives a `TTkFileTreeWidgetItem` object. ```json { "type": "TTkFileTreeWidgetItem", "text": "example.txt", "path": "/path/to/example.txt" } ``` ``` -------------------------------- ### Get and Set Minimum/Maximum for TTkSpinBox in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/spinbox Methods to get and set the minimum and maximum allowable values for the TTkSpinBox. The `setMinimum` and `setMaximum` methods automatically adjust the current value if it falls outside the new range. ```python def minimum(self): '''minimum''' return self._minimum @pyTTkSlot(int) def setMinimum(self, minimum): '''setMinimum''' if self._minimum == minimum: return self._minimum = minimum self.setValue(self._value) def maximum(self): '''maximum''' return self._maximum @pyTTkSlot(int) def setMaximum(self, maximum): '''setMaximum''' if self._maximum == maximum: return self._maximum = maximum self.setValue(self._value) ``` -------------------------------- ### Get TTkFrame Menu Bar in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/frame Provides a Python function to retrieve the menu bar associated with a TTkFrame widget. It allows specifying whether to get the top or bottom menu bar using the `position` parameter, defaulting to the top menu bar. ```python def menuBar(self, position=TTkK.TOP): if position == TTkK.TOP: return self._menubarTop else: return self._menubarBottom ``` -------------------------------- ### Basic Signal & Slot Connection in pyTermTk Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/003-signalslots Demonstrates the fundamental usage of signals and slots in pyTermTk. It defines signals with and without arguments, connects them to corresponding slots, and then emits the signals to trigger the slots. This example requires the TermTk library. ```python import TermTk as ttk ttk.TTkLog.use_default_stdout_logging() # define 2 signals with different signatures signal = ttk.pyTTkSignal() otherSignal = ttk.pyTTkSignal(int) # Define a slot with no input as signature @ttk.pyTTkSlot() def slot(): ttk.TTkLog.debug("Received a simple signal") # Define 2 slots with "int" as input signature @ttk.pyTTkSlot(int) def otherSlot(val): ttk.TTkLog.debug(f"[otherSlot] Received a valued signal, val:{val}") @ttk.pyTTkSlot(int) def anotherSlot(val): ttk.TTkLog.debug(f"[anootherSlot] Received a valued signal, val:{val}") # connect the signals to the proper slot signal.connect(slot) otherSignal.connect(otherSlot) otherSignal.connect(anotherSlot) # Test the signals ttk.TTkLog.debug("Emit a simple signal") signal.emit() ttk.TTkLog.debug("Emit a valued signal") otherSignal.emit(123) ``` -------------------------------- ### Create and Set Up Menu Bar in Python Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkUiTools/uiloader This function sets up a menu bar for a given widget. It handles adding menus with specified text, checkable status, and alignment, along with their associated buttons. ```python def _setMenuBar(_menuBarProp, _menuBar:TTkMenuBarLayout): def __addMenu(__prop, __alignment): for _bp in __prop: _btn = _menuBar.addMenu(text=_bp['params']['Text'], checkable=_bp['params']['Checkable'], checked=_bp['params']['Checked'], alignment=__alignment) _btn.setName(_bp['params']['Name']) _btn.setToolTip(_bp['params']['ToolTip']) _setMenuButton(_bp, _btn) if 'left' in _menuBarProp: __addMenu(_menuBarProp['left'], TTkK.LEFT_ALIGN) if 'center' in _menuBarProp: __addMenu(_menuBarProp['center'], TTkK.CENTER_ALIGN) if 'right' in _menuBarProp: __addMenu(_menuBarProp['right'], TTkK.RIGHT_ALIGN) ``` -------------------------------- ### Initialize pytermtk Application Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/ttk This snippet initializes the pytermtk application, including setting up the main loop, registering event handlers, and configuring the terminal. It handles cleanup for non-Emscripten environments, ensuring proper shutdown of timers, signal drivers, and the terminal. ```python TTkLog.debug( " ▌ ▐ ╚═╝ ╚═╝ " ) TTkLog.debug( " ▚▄▄▘ " ) TTkLog.debug( "" ) TTkLog.debug(f" Version: {TTkCfg.version}" ) TTkLog.debug( "" ) TTkLog.debug( "Starting Main Loop..." ) TTkLog.debug(f"screen = ({TTkTerm.getTerminalSize()})") # Register events TTkSignalDriver.init() TTkLog.debug("Signal Event Registered") TTkTerm.registerResizeCb(self._win_resize_cb) self._timer = TTkTimer() self._timer.timeout.connect(self._time_event) self._timer.start(0.1) self.show() # Keep track of the multiTap to avoid the extra key release self._lastMultiTap = False TTkInput.init( mouse=self._termMouse, directMouse=self._termDirectMouse) TTkTerm.init( title=self._title, sigmask=self._sigmask) if self._showMouseCursor: self._mouseCursor = _MouseCursor() self._mouseCursor.updated.connect(self.update) self.paintChildCanvas = self._mouseCursorPaintChildCanvas self._mainLoop_2() finally: if platform.system() != 'Emscripten': TTkHelper.quitEvent.emit() if self._timer: self._timer.timeout.disconnect(self._time_event) self._timer.quit() self._paintEvent.set() # self._timer.join() TTkSignalDriver.exit() self.quit() TTkTerm.exit() ``` -------------------------------- ### TermTk TTkAbout Widget Initialization Example Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/about Demonstrates how to initialize and display the TTkAbout widget within a TermTk application. This is typically used for 'About' dialogs. ```python import TermTk root = TermTk.TTk() TermTk.TTkAbout(parent=root) root.mainloop() ``` -------------------------------- ### Get and Set FileMode in PyTermTk Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkPickers/filepicker Provides functionality to get and set the file mode, which defines whether the dialog operates in single file selection, multiple file selection, or directory selection mode. This is crucial for controlling user interaction with the file system. ```python def fileMode(self) -> TTkK.FileMode: return self._fileMode [docs] def setFileMode(self, fm:TTkK.FileMode): self._fileMode = fm ``` -------------------------------- ### PyTermTk About Window Initialization and Painting (Python) Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/about Initializes the `TTkAbout` window, setting its title and size. The `paintEvent` method is overridden to draw custom content onto the canvas, including ASCII art, version information, author name, and a hyperlinked GitHub URL. ```python __slots__=('_image') _image:TTkString def __init__(self, **kwargs) -> None: TTkWindow.__init__(self,**kwargs) if not self.title(): self.setTitle('About...') self.resize(55,15) def paintEvent(self, canvas): c = [0xFF,0xFF,0xAA] for y, line in enumerate(TTkAbout.pyTermTk): canvas.drawText(pos=(9,3+y),text=line, color=TTkColor.fg(f'#{c[0]:02X}{c[1]:02X}{c[2]:02X}')) c[2]-=0x11 for i,line in enumerate(TTkAbout._peppered_string.split('\n')): canvas.drawTTkString(pos=(1,3+i), text=line) canvas.drawText(pos=(20, 9),text=f" Version: {TTkCfg.version}", color=TTkColor.fg('#AAAAFF')) canvas.drawText(pos=(12,11),text=f"Powered By, Eugenio Parodi") canvas.drawText(pos=( 2,13),text=f"https://github.com/ceccopierangiolieugenio/pyTermTk", color=TTkColor.fg('#44FFFF', link="https://github.com/ceccopierangiolieugenio/pyTermTk")) TTkWindow.paintEvent(self, canvas) ``` -------------------------------- ### PyTermTk Nested Layouts Example Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/tutorial/002-layout Demonstrates how to create nested layouts using TTkGridLayout and TTkVBoxLayout in pyTermTk. This example shows how to set a default layout for the root widget and attach widgets to specific positions within the grid or nested layouts. It requires the TermTk library. ```python import TermTk as ttk # Set the GridLayout as default in the terminal widget root = ttk.TTk() gridLayout = ttk.TTkGridLayout() root.setLayout(gridLayout) # Attach 2 buttons to the root widget using the default method # this will append them to the first row # NOTE: it is not recommended to use this legacy method in a gridLayout ttk.TTkButton(parent=root, border=True, text="Button1") ttk.TTkButton(parent=root, border=True, text="Button2") # Attach 2 buttons to a specific position in the grid gridLayout.addWidget(ttk.TTkButton(border=True, text="Button3"), 1,2) gridLayout.addWidget(ttk.TTkButton(border=True, text="Button4"), 2,4) # Create a VBoxLayout and add it to the gridLayout vboxLayout = ttk.TTkVBoxLayout() gridLayout.addItem(vboxLayout,1,3) # Attach 2 buttons to the vBoxLayout vboxLayout.addWidget(ttk.TTkButton(border=True, text="Button5")) vboxLayout.addWidget(ttk.TTkButton(border=True, text="Button6")) root.mainloop() ``` -------------------------------- ### PyTermTk Tab Widget: Tab Management Methods Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/tabwidget Provides methods for managing tabs within the pyTermTk Tab Widget. Includes functions to get the number of tabs, find a tab's index, retrieve a specific tab button or widget, get the current widget, and set the current tab. ```python def count(self) -> int: return len(self._tabWidgets) def indexOf(self, widget) -> int: if widget in self._tabWidgets: return self._tabWidgets.index(widget) return -1 def tabButton(self, index) -> TTkTabButton: '''tabButton''' return self._tabBar.tabButton(index) def widget(self, index): '''widget''' if 0 <= index < len(self._tabWidgets): return self._tabWidgets[index] return None def currentWidget(self) -> TTkWidget: '''currentWidget''' for w in self._tabWidgets: if w.isVisible(): return w return self._spacer def setCurrentWidget(self, widget): '''setCurrentWidget''' for i, w in enumerate(self._tabWidgets): if widget == w: self.setCurrentIndex(i) break ``` -------------------------------- ### Import pyTermTk and System Modules (Python) Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/sandbox/sandbox_filepath=tutorial%2Fhelloworld%2Fhelloworld.001 This snippet imports necessary modules for pyTermTk applications. It includes `sys` for system-specific parameters and functions, `os` for interacting with the operating system, `argparse` for parsing command-line arguments, and `TermTk` as `ttk` for the core TUI functionalities. It also appends a local library path to `sys.path`. ```Python import sys, os, argparse sys.path.append(os.path.join(sys.path[0],'../libs/pyTermTk')) import TermTk as ttk ``` -------------------------------- ### Initialize and Use TTkColorDialogPicker Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/TTkPickers/colorpicker Demonstrates the basic instantiation of a TTkColorDialogPicker widget, its placement within a root window, and connection of its colorSelected signal to update a TTkLabel. This is a fundamental example for integrating the color picker into a PyTermTk application. ```python root = TTk() cdp = TTkColorDialogPicker( parent=root, pos=(3,3), size=(75,24), border=True, color=TTkColor.RED, title="Test Color Picker") lfg = TTkLabel(parent=root, pos=(0,0), text="Test Color") cdp.colorSelected.connect(lfg.setColor) root.mainloop() ``` -------------------------------- ### TTkWidget Name Methods Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/widget Provides methods to get and set the name of a TTkWidget. ```APIDOC ## TTkWidget Name Methods ### Description Methods for managing the name property of a TTkWidget. ### Method `name()` #### Description Returns the name of the widget. #### Method `setName(name: str)` #### Description Sets the name of the widget. #### Parameters * **name** (str) - The new name to be set for the widget. ### Request Example ```python widget.setName("MyCustomWidget") print(widget.name()) ``` ### Response #### Success Response (200) * `name()`: Returns (str) - The current name of the widget. * `setName()`: Returns (None) #### Response Example ```json { "name": "MyCustomWidget" } ``` ``` -------------------------------- ### Profiling with py-spy Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/debug This set of commands illustrates how to use py-spy for profiling a running Python application. It includes installation, running the target application, and then using py-spy to attach to the process and display its performance statistics in real-time. This is useful for live debugging of performance issues. ```bash # install pip install py-spy # run the application python3 demo/demo.py # on another terminal run the py-spy sudo env "PATH=$PATH" \ py-spy top \ --pid $(ps -A -o pid,cmd | grep demo.py | grep -v grep | sed 's,python.*,,') ``` -------------------------------- ### Layout Management API Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/container APIs for setting, getting, and managing the layout of widgets. ```APIDOC ## setLayout ### Description Sets the layout used by this widget to arrange all child widgets. ### Method `setLayout(self, layout: TTkLayout) -> None` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **layout** (TTkLayout) - Required - The layout to be applied to the widget. ### Request Example ```json { "layout": "TTkLayout_instance" } ``` ### Response #### Success Response (200) None #### Response Example None ## layout ### Description Gets the layout currently used by the widget. ### Method `layout(self) -> TTkLayout` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **return value** (TTkLayout) - The layout object used by the widget. #### Response Example ```json { "layout": "TTkLayout_instance" } ``` ## rootLayout ### Description Provides access to the root layout, primarily for items not intended for the main layout, like menu elements. ### Method `rootLayout(self) -> TTkLayout` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **return value** (TTkLayout) - The root layout object. #### Response Example ```json { "layout": "TTkLayout_instance" } ``` ``` -------------------------------- ### Clone pyTermTk Repository - Bash Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/info/installing Clones the pyTermTk repository from GitHub and changes the current directory into the cloned repository. This is a prerequisite for running local demos. ```bash # Clone and enter the folder git clone https://github.com/ceccopierangiolieugenio/pyTermTk.git cd pyTermTk ``` -------------------------------- ### Get Canvas Size Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkCore/canvas Returns the current dimensions (width and height) of the canvas. ```python def size(self): return (self._width, self._height) ``` -------------------------------- ### Get Document Source: https://ceccopierangiolieugenio.github.io/pyTermTk-Docs/_modules/TermTk/TTkWidgets/texedit Retrieves the TTkTextDocument associated with the text edit. ```APIDOC ## GET /document ### Description Retrieves the TTkTextDocument currently associated with the text edit widget. ### Method GET ### Endpoint /document ### Response #### Success Response (200) - **document** (TTkTextDocument) - The TTkTextDocument object. ```