# ztk > Tk rebuilt in Zig on the ztcl interpreter. A script uses the Tk 8.6 commands, and ztk draws it with CSS styles: on Wayland, on Windows with Direct3D 12, and in a browser with WebGPU or WebGL 2. An agent can see and drive the window it builds: ztk::snapshot gives a PNG of a widget, ztk::tree gives each widget with its class and its box, and ztk::inject sends pointer and key events. `ztk --headless` runs a script with no display. # ztk Tk, rebuilt in Zig. ztk runs Tk scripts on the [ztcl](https://github.com/beetlebugorg/ztcl) interpreter, with a GPU renderer, a modern look from CSS, smooth animation, and a WebAssembly build for the browser. **Docs and live demos:** https://beetlebug.org/ztk/ ![The widget gallery drawn by ztk: buttons, switches, radio buttons, entries, a scale, ttk widgets, and a canvas in cards](docs/site/shots/gallery-light.png) - **Tk scripts.** The widgets of Tk 8.6, among them `text`, `canvas`, `listbox`, `menu`, `ttk::notebook`, `ttk::treeview`, and the other `ttk` widgets, with `pack`, `grid`, `place`, `bind`, and the option database. Each example also runs in `wish` 8.6, and [well-known Tk apps](docs/apps.md) run with no change. - **Native on each desktop.** Its own Wayland and X11 clients on Linux, AppKit with Metal on macOS, and Win32 with Direct3D 12 on Windows, with the tray, drag and drop, and the dialogs of each system. `ztk bundle` makes one program for each platform from any host. - **A modern look.** A stylesheet in a subset of CSS styles each widget, with a dark scheme, transitions, and a classic theme with the look of Tk. - **Fluid.** A frame with 1,000 widgets uses 0.85 ms of CPU time at the 99th percentile, and a render thread draws animations while the script is busy. - **On the web.** The same scripts run in the browser with WebGPU, WebGL 2, or a 2D canvas. - **No third-party library.** ztk uses the platform, ztcl, and the Zig standard library. `ztk::terminal` uses libghostty-vt through ztcl. ## Install ```sh npm install @beetlebug/ztk # for the web ``` [Install](docs/install.md) has the release binaries and the build from source. ## Example ```tcl ttk::label .title -text "Hello from ztk" ttk::entry .name -textvariable name ttk::button .greet -text "Greet" -style Accent.TButton -command {set msg "Hello, $name!"} ttk::label .msg -textvariable msg pack .title .name .greet .msg -padx 12 -pady 4 -anchor w ttk::style configure Accent.TButton -foreground white -background #2563eb ``` ```sh ztk hello.tcl ``` ## Documentation - [Quick start](docs/quickstart.md) and [the widgets](docs/widgets/README.md) - [Styling and themes](docs/styling.md) and [animation](docs/animation.md) - [On the web](docs/web.md), [On Linux](docs/linux.md), [On macOS](docs/macos.md), [On Windows](docs/windows.md), and [embed in Zig](docs/embedding.md) - [The ztk:: commands](docs/commands/README.md) and [debugging](docs/debugging.md) - [Performance](docs/performance.md) and [differences from Tk](docs/differences.md) - For contributors: [docs/dev/](docs/dev/README.md) has the plan, the task lists, and the reports. ## Status ztk is experimental, and it is not yet a drop-in Tk. [Differences from Tk](docs/differences.md) lists what is missing, such as `send` and the selections and clipboard of the system. The code and the docs were written largely with AI coding agents, under human direction. Review the code before you depend on it. The [plan](docs/dev/plan.md#11-stages) has the roadmap, and the [issues](https://github.com/beetlebugorg/ztk/issues) take bug reports and requests. ## Contact Write to [opensource@beetlebug.org](mailto:opensource@beetlebug.org) about ztk. Open an [issue](https://github.com/beetlebugorg/ztk/issues) for a bug or a request, and report a security problem as [SECURITY.md](SECURITY.md) says. ## License BSD-2-Clause. See [LICENSE](LICENSE). ztk has no code of Tk. [References](docs/references/README.md) credits Tk and the other sources. # Install ## With Homebrew ```sh brew install beetlebugorg/tap/ztk ``` Homebrew installs the `ztk` program on macOS and Linux (arm64 and x86-64) from the release binaries. ## In the browser The quickest way to try ztk is the [playground](https://beetlebug.org/ztk/play/index.html). It runs each example, and you can edit the script. For your own page, install the npm package. [On the web](web.md) has the API. ```sh npm install @beetlebug/ztk ``` ## Build from source Use the build from source to get a window on the Linux desktop. Install [Zig 0.17.0](https://ziglang.org/download/). On Linux the default build also needs `glslc`. The Wayland backend links no library, so the static Linux programs of a release open a window too. ```sh git clone https://github.com/beetlebugorg/ztk cd ztk zig build -Doptimize=ReleaseFast # makes zig-out/bin/ztk zig-out/bin/ztk examples/gallery.tcl # opens a window in a Wayland session ``` `zig build test` runs the tests. `zig build wasm` makes the web build in `zig-out/web`. On Windows, the build has the native Win32 backend with Direct3D 12: [On Windows](windows.md) has the steps and the limits. On macOS, the build has the native AppKit backend with Metal: [On macOS](macos.md) has the steps and how to make an app. ## Release binaries Each [release](https://github.com/beetlebugorg/ztk/releases) has `ztk` for Linux (x86-64 and arm64), macOS (x86-64 and arm64), and Windows (x86-64). These programs have the headless backend, on Linux also the direct backend, and on Windows also the Win32 backend. With `--headless`, they draw a script to a PNG file: ```sh ztk --headless --scale 2 --exit-after-frames 1 --screenshot gallery.png examples/gallery.tcl ``` ## The ztk program ``` ztk [flags] script.tcl [arguments] ``` | Flag | Use | |---|---| | `--headless` | Draws with the CPU renderer and no window. | | `--screenshot FILE.png` | With `--headless`: writes the last frame at the exit. | | `--scale N` | With `--headless`: the scale of the window. | | `--exit-after-frames N` | Exits after N frames. | | `--dark` | Uses the dark color scheme. | | `--windowingsystem NAME` | Sets the result of `tk windowingsystem`: `x11`, `win32`, `aqua`, or `ztk` (the default). A Tk app that tests for `x11`, `win32`, or `aqua` can then choose its path. The look of ztk does not change. | | `--allow a,b` | Turns on more capabilities of ztcl, with the names of the `ztcl` runner: `package`, `interp`, `clock`, `event`, `socket`, `exec`, `random`, `env`, `sqlite`, and `thread`. `hotkey` lets `ztk::hotkey` add global shortcuts. | | `--root DIR` | Keeps the file commands in one folder, which a script sees as `/`. With no `--root`, they use the real paths of the host. | | `--cpu` | Uses the CPU renderer on Wayland, as `ZTK_RENDERER=cpu` does. | On Wayland, ztk renders the main window with Vulkan into dma-bufs when the GPU and the compositor share them (`zwp_linux_dmabuf_v1` with linear XBGR8888), and else with the CPU renderer into shared memory. With the CPU renderer, ztk writes the cause to stderr once, for example `ztk: the CPU renderer: the compositor has no zwp_linux_dmabuf_v1 version 3`. `ZTK_RENDERER=cpu` selects the CPU renderer, and `ZTK_RENDERER=vulkan` makes ztk exit when it cannot use Vulkan. Menus and other popups use the CPU renderer. `ZTK_NO_ANIMATION=1` turns the animations off and shows each end state at once. The program gives a script the file commands and the file channels of ztcl (`file`, `open`, `read`, `puts` to a file) by default, with the real paths of the host, as in `wish`. A relative path counts from the current folder. `--root DIR` keeps the file commands in one folder, which a script sees as `/`. The other host access (`socket`, `exec`, and the others) needs `--allow`. `ztk::style load` reads style sheets from the folder of the script. ## An app in one file `ztk bundle` with an output name that has no `.app` writes one program file: a copy of the `ztk` program with the app in it. ```sh ztk bundle -o notes notes.tcl lib/ images/ ztk bundle -o notes.exe --target x86_64-windows --runner ztk.exe notes.tcl ``` The first file is the main script. Each file keeps its path relative to the main script, so a script that finds a file next to it in the source folder finds it in the app too. The top folder of the app is the deepest folder that has the main script and each other file and folder. For example, `ztk bundle -o demo examples/demo.tcl examples/demo.css` gives `//zipfs:/app/demo.tcl` and `//zipfs:/app/demo.css`, and `ztk bundle -o notes app/notes.tcl lib/` gives `//zipfs:/app/app/notes.tcl` and `//zipfs:/app/lib/`. `ztk::style load` reads style sheets from the folder of the main script in the app too. `--allow` sets the capabilities of the app, and the default is `file,channels`. The program reads no flag: each word of its command line goes to `$argv`. `ZTK_HEADLESS=1` in the environment runs the app with the headless backend and the CPU renderer, as `--headless` does for `ztk`. A program file for Windows (`--target x86_64-windows` or `aarch64-windows`, or this computer on Windows) gets the resources of a Windows app: the icon of `--icon` (an `.ico`, or a `.png` of 256 pixels or less), a manifest with per-monitor DPI and version 6 of the common controls, and the version information of `--name` and `--version`, which Explorer shows in the properties of the file. It uses the GUI subsystem, so it opens no console window. Started from a terminal, it writes `puts` and its errors to that terminal. `--console` gives a program with a console window of its own. On Linux, `--desktop` also writes a desktop entry and an icon next to the program file: `ztk bundle -o notes --desktop --name "My Notes" --icon notes.png notes.tcl` gives `notes`, `notes.desktop`, and `notes.png` (256 pixels or less). The entry has `Exec=notes`, so put the program in a folder of `PATH` such as `~/.local/bin`, the entry in `~/.local/share/applications`, and the icon in `~/.local/share/icons/hicolor/256x256/apps`. A bundled program gives its file name as the app id of its Wayland window, so the desktop finds the entry and its icon. A renamed program needs an entry of the new name. `wm iconphoto` sets the icon of the window on Linux. On X11 the photos go in the property `_NET_WM_ICON`. On Wayland they go to the compositor with the protocol `xdg-toplevel-icon-v1`, and a compositor without the protocol shows the icon of the desktop entry. With `--target` and an output name that ends in `.app`, the target is `aarch64-macos` or `x86_64-macos`, and `ztk bundle` writes a macOS app folder (see [macOS](macos.md#make-an-app)). The default target is the computer that runs `ztk bundle`, with the `ztk` program itself as the copy. For another target, give the `ztk` program of that target with `--runner`, or put it in `lib/ztk/runtime/TARGET/` next to the folder of `ztk`. `zig build runtimes` builds the program of each target into `zig-out/lib/ztk/runtime/`, so `zig-out/bin/ztk bundle --target T` finds it. Each one has the full GUI backend of its platform: Wayland, X11, the direct backend, and Vulkan on Linux (a static program), AppKit and Metal on macOS, and Win32 and Direct3D 12 on Windows. `-Druntime-targets=x86_64-linux,aarch64-macos` builds a part of them. The targets are `x86_64-linux`, `aarch64-linux`, `x86_64-macos`, `aarch64-macos`, `x86_64-windows`, and `aarch64-windows`. A macOS file gets an ad hoc signature. The form of the file is the form of `ztcl build` of ztcl. ## A smaller app `ztk bundle --strip` writes one program file with a ztk program that has only the parts the scripts use. It is the strip mode of `ztcl build` ([Strip a program](https://github.com/beetlebugorg/ztcl/blob/main/docs/strip.md)) with the widget classes of ztk as features too: `text`, `terminal`, `canvas`, `treeview`, and `notebook`. The build scans the scripts, maps each command and `package require` to a feature, and runs `zig build runtimes -Ddrop=...` in the source folder of ztk, into a cache folder. ```sh ztk bundle --strip --trust-scan -o notes notes.tcl lib/ ``` - The source folder is `--src DIR`, or the folder of `ZTK_SRC`, or the folder two levels above the `ztk` program. Zig is `ZIG` or `zig` on the `PATH`. - A Tk program calls each widget through its path, such as `$w configure`, so the scan finds computed command names in most programs. By default each such site keeps every widget class and command group. `--trust-scan` keeps a class only when a literal word of the scripts names it, such as `canvas` or `ttk::treeview`. - `--keep LIST`, `--drop-module LIST`, `--check`, `--test FILE`, and `--profile` work as in `ztcl build`. The manifest is `ztk-strip.txt` in the current folder. - A call of a widget class that the build left out gives the error `command "canvas" is not in this build`, with the flag that keeps it. - The strip mode writes one program file: an output name with no `.app`. On x86-64 Linux, the full ztk program is 11,224,360 bytes. With `--strip --trust-scan`, the counter example (`examples/counter.tcl`) is 7,337,022 bytes, and 11,225,390 bytes with the full program. The gallery (`examples/gallery.tcl`) is 7,902,337 bytes, and 11,237,105 bytes with the full program: it keeps `text`, `canvas`, `treeview`, and `notebook`. A test of the counter (the window, one `update`, a click, and `exit`, with `ZTK_HEADLESS=1`) starts in 16.6 ms stripped and in 19.5 ms with the full program, as the mean of 50 runs. # Quick start This page builds a small window with a script and a stylesheet. [Install](install.md) ztk first, or paste the script into the [playground](https://beetlebug.org/ztk/play/index.html). ## The script Save this file as `counter.tcl`: ```tcl ztk::style load counter.css wm title . "Counter" set count 0 set fast 0 ttk::label .value -textvariable count ttk::button .add -text "Add one" -style Accent.TButton -command {incr count [expr {$fast ? 10 : 1}]} ttk::checkbutton .fast -text "Count by ten" -style Switch.TCheckbutton -variable fast pack .value .add .fast -padx 16 -pady 6 bind . {.add invoke} ``` The commands are the commands of Tk. `ttk::button`, `pack`, `-textvariable`, and `bind` work as in `wish`. ## The stylesheet Save this file as `counter.css` in the same folder: ```css #value { font-size: 32px; color: var(--accent); } TButton.Accent { background: var(--accent); color: var(--accent-fg); border-radius: 8px; } TButton.Accent:hover { background: var(--accent-hover); } ``` A type selector is the class of a widget (`TButton`), `#value` is the last part of the path `.value`, and `.Accent` is the style `Accent.TButton`. The variables come from the modern theme, so the colors follow the light and the dark scheme. ## Run it ```sh ztk counter.tcl # a window, in a Wayland session ztk --headless --scale 2 --exit-after-frames 1 --screenshot counter.png counter.tcl ``` ![The counter window: the number 0 in blue, an Add one button, and a switch that is off](site/shots/counter-light.png) ## Next steps - [All widgets](widgets/README.md), each with a live example. - [Styling and themes](styling.md): CSS, the classic theme, and `ttk::style`. - [Animation](animation.md): transitions and `ztk::animate`. - [On the web](web.md): run the same script in a page. # For agents ztk is a GUI toolkit that an agent can see. A script builds a window with the Tk 8.6 commands. Then the same script, or a check script, can look at the window and drive it: - `ztk::snapshot path` gives a PNG image of a widget. - `ztk::tree` gives each widget with its class, its box, and its map state. - `ztk::inject` sends pointer, wheel, key, and text events through the hit test and the focus, as a real backend does. - `ztk::debug why` gives the source of an option, and `ztk::debug geometry` gives the chain that sets the size and the place of a widget. See [Debugging](debugging.md). - `ztk::debug explain`, `ztk::debug click`, and `ztk::debug changes` give short answers: why a widget is like this, what ran for a click, and what changed. `ztk --mcp app.tcl` serves them as MCP tools. `ztk --headless` runs a script with no display and the CPU renderer, so the image of a window is the same on each platform. ## The files for agents | File | What it has | |---|---| | [llms.txt](https://beetlebug.org/ztk/llms.txt) | The list of the docs pages. | | [llms-full.txt](https://beetlebug.org/ztk/llms-full.txt) | The Markdown of each docs page in one file. | | [api.json](https://beetlebug.org/ztk/api.json) | Each command, and each widget command with its options and their defaults, from the build of the site. | | [The skill](../skills/ztk-app/SKILL.md) | The loop of an agent that builds a ztk app, the tools, a check script, and the idioms. Copy the folder `skills/ztk-app` into the skills folder of your agent. | ## A check script This script builds a counter, clicks its button with `ztk::inject`, and prints the count. `ztk --headless check.tcl` prints `n = 1`. `tests/skill.sh` runs it on each change. ```tcl set n 0 button .go -text Count -command {incr ::n} label .count -textvariable n pack .go .count -padx 12 -pady 8 update foreach row [ztk::tree .] { lassign $row path class x y w h mapped if {$path eq ".go"} { set cx [expr {$x + $w / 2}] set cy [expr {$y + $h / 2}] } } ztk::inject . motion $cx $cy ztk::inject . press 1 $cx $cy ztk::inject . release 1 $cx $cy update puts "n = $n" exit ``` ## What a script can do A script in the `ztk` program has the commands of Tk and of the ztcl core. `--allow a,b` turns on more capabilities of ztcl ([Install](install.md)). In a browser, a script has no file, network, or process access. Tcl code is short, so a person can read the code of an app and see what it does. # Watch it get built A person asks for an app, and an agent builds it in steps. Move the bar to a step: the window under the chat runs the app of that step, and you can click and type in it. Then the window runs the check of the step, a short Tcl script that the agent used to test its work with `ztk::tree` and `ztk::inject`. This replay is a sample that a person wrote by hand, in the format that dockyard is to record. `tests/replay.sh` runs the script and the check of each step in `ztk --headless`, so each step of a replay works. ## The format A replay is a JSON file with `version`, `title`, and `steps`. Each step has `who` (`person` or `agent`) and `say`. A step of the agent can also have `script`, the full Tcl text of the app after the step, and `check`, a Tcl script that gives 1 when the step works. # Runs on ztk These well-known Tcl/Tk apps run on ztk with no change to their code. Each app has a pinned release and a script that uses it as a person does: clicks, keys, and typed text through `ztk::inject`. The full CI run runs each script every 6 hours, so a regression shows. Each image is a screenshot of the app on ztk, made by its script on the headless backend. The table with each check and each gap is in [the app table](https://github.com/beetlebugorg/ztk/blob/main/docs/dev/apps.md) of the repository. To try an app, build ztk, download the pinned releases, and run the scripts: ```sh tools/fetch-apps.sh tests/famous-apps.sh shots ``` An app runs with the flag `--windowingsystem x11`, because these apps test for `x11`, `win32`, or `aqua`. For example, tkcon: ```sh ztk --windowingsystem x11 --allow package,clock,event,env,interp \ .apps-src/tkcon/tkcon-2.5/tkcon.tcl ``` ## Tk widget demo ![The widget demo of Tk 8.6.16 on ztk](site/shots/app-tk-widget.png) Version 8.6.16, `library/demos/widget`. Status: **works with gaps**. A click on each demo line opens its demo. Gaps: [text peers (#249)](https://github.com/beetlebugorg/ztk/issues/249), [Tk in a child interpreter (#250)](https://github.com/beetlebugorg/ztk/issues/250), [canvas bitmaps from a file (#251)](https://github.com/beetlebugorg/ztk/issues/251), [hscale and vscale (#252)](https://github.com/beetlebugorg/ztk/issues/252). ## tkcon ![tkcon 2.5 on ztk, with three commands in its console](site/shots/app-tkcon.png) Version 2.5. Status: **works**. The script types commands into the console, gets their results and errors, and recalls a command with Up. ## BWidget demo ![The BWidget 1.10.1 demo on ztk](site/shots/app-bwidget.png) Version 1.10.1, `demo/demo.tcl`. Status: **works**. A click on each notebook tab shows its page, and the script types into an entry and clicks a button. ## Tablelist ![The Tablelist 7.12 demo dirViewer on ztk](site/shots/app-tablelist.png) Version 7.12, six demos. Status: **works**. A click selects a row, a click on a column label sorts, and a double click opens a folder. ## tklib and Plotchart ![Plotchart charts of tklib 0.9 on ztk](site/shots/app-tklib.png) Version 0.9. Status: **works with gaps**. Eighteen Plotchart examples draw their charts, and a tooltip, a ctext widget, and a datefield take a hover and typed text. Gap: [plotdemos13 (#255)](https://github.com/beetlebugorg/ztk/issues/255). ## gitk Version: gitk of git 2.56.0. Status: **works**. In a test repository the list shows the commits, a click on a commit shows its diff, and Up selects the commit above. gitk has the GPL: ztk only runs it, and no code of gitk is in ztk. The page shows no screenshot of it. ## SaVi ![The coverage map of the Iridium constellation in SaVi 1.6.0 on ztk](site/shots/app-savi-coverage.png) Version 1.6.0, satellite constellation visualization by Lloyd Wood and the Geometry Center (https://savi.sourceforge.io/). Status: **works**. SaVi is a C program with Tcl and Tk scripts. It builds with no change against [libztk](python-tkinter.md) and its `tk.h`, and the same program file also runs on the libraries of Tcl and Tk. The script loads Iridium, opens the coverage map, which the C code fills through the photo API, and runs the simulation. The 3D view needs Geomview and is not tried. Run it with `tests/apps/savi/run.sh` after `zig build libztk`. SaVi calls `Tcl_GetCommandInfo`, which libztcl has from ztcl#502 on; the images come from a build of libztk on that branch. ![The main window of SaVi 1.6.0 on ztk](site/shots/app-savi-main.png) ## In progress - TkDiff 5.7 starts, but its text panes do not show yet ([#253](https://github.com/beetlebugorg/ztk/issues/253)). - git gui is not tried yet ([#254](https://github.com/beetlebugorg/ztk/issues/254)). # Python tkinter on ztk Python's `tkinter` is a small C module, `_tkinter`, over the libraries libtcl8.6 and libtk8.6. libztk is one shared library with ztcl and ztk that has the C API of Tcl 8.6 and the part of the C API of Tk 8.6 that `_tkinter` and common extensions call. A tkinter program runs on ztk with no change to the program and no change to Python. > [!WARNING] > libztk is new. It runs on Linux only. The table below gives the programs that were checked and the gaps that are known. ## Build and run ```sh zig build libztk LD_LIBRARY_PATH=zig-out/lib python3 your_app.py ``` The step writes two files. `zig-out/lib/libtcl8.6.so` has ztcl and ztk, the Tcl functions, and the Tk functions with the prefix `ztk_`. `zig-out/lib/libtk8.6.so` is small: it links libtcl8.6.so and has the names of the Tk functions, each a jump to its `ztk_` function. So `_tkinter` gets one copy of ztcl, and a C program built against libztk records both libraries, as with Tcl and Tk, and also runs on the libraries of Tcl and Tk. The step also installs `zig-out/include/tk.h`, a header with the part of the Tk API that libztk has, written from the manual pages of Tk. Use it with the Tcl headers of the kit of libztcl (`zig build libztcl` in ztcl) to build a C program such as SaVi. The backend comes from the environment: | Variable | Backend | |---|---| | `ZTK_HEADLESS=1` | The headless backend, with the clock of the process. No window opens. | | `WAYLAND_DISPLAY` | Wayland. | | `DISPLAY`, with no `WAYLAND_DISPLAY` | X11. | `ZTK_NO_ANIMATION=1` turns the transitions off. `tk windowingsystem` gives `x11` on Linux, so a program that tests for `x11`, `win32`, or `aqua` runs its X11 code. ## What libztk has - The Tcl API of libztcl (ztcl `docs/dev/libztcl.md`), with an event loop over the loop of ztk: `Tcl_DoOneEvent`, `Tcl_CreateTimerHandler`, `Tcl_CreateFileHandler`, and `Tcl_ThreadQueueEvent` for the calls of other Python threads. - `Tk_Init`, `Tk_MainWindow`, `Tk_GetNumMainWindows`, `Tk_MainLoop`, and `Tk_CreateWindow`. - The photo API of `FindPhoto.3`: `Tk_FindPhoto`, `Tk_PhotoPutBlock`, `Tk_PhotoPutZoomedBlock` (with the zoom 1), `Tk_PhotoGetImage`, `Tk_PhotoBlank`, `Tk_PhotoGetSize`, `Tk_PhotoSetSize`, and `Tk_PhotoExpand`. Pillow's `ImageTk` and matplotlib's TkAgg backend use them. - The bignum functions of the tommath table that `_tkinter` imports, for Python integers past 64 bits. The Tk stubs table (`Tk_InitStubs`) is not there yet, so a Tk extension that loads with stubs does not load. ## Results Checked on 2026-11-27 on x86-64 Arch Linux with Python 3.14.8 (the `_tkinter` of the system, against Tcl/Tk 8.6.16), with the headless backend, unless the row says otherwise. The machine had a load of about 20 on 8 cores from other work, so the times are rough. ### The tkinter tests of CPython The tests of `Lib/test/test_tkinter` and `Lib/test/test_ttk` of CPython 3.14.8, run one file at a time with `python3 -m test -u gui -v` (the system Python has no test package, so the files come from the source release): | Test file | Tests | Pass on ztk | |---|---:|---:| | test_tkinter.test_colorchooser | 3 | 3 | | test_tkinter.test_dnd | 11 | 11 | | test_tkinter.test_filedialog | 7 | 7 | | test_tkinter.test_font | 18 | 15 | | test_tkinter.test_geometry_managers | 59 | 42 | | test_tkinter.test_images | 40 | 16 | | test_tkinter.test_loadtk | 2 | 0 | | test_tkinter.test_messagebox | 1 | 1 | | test_tkinter.test_misc | 112 | 87 | | test_tkinter.test_scrolledtext | 4 | 4 | | test_tkinter.test_simpledialog | 23 | 17 | | test_tkinter.test_text | 31 | 29 | | test_tkinter.test_tkinter_pipe | 2 | 2 | | test_tkinter.test_variables | 25 | 22 | | test_tkinter.test_widgets | 676 | 421 | | test_ttk.test_extensions | 30 | 20 | | test_ttk.test_style | 20 | 6 | | test_ttk.test_widgets | 348 | 204 | | Total | 1,412 | 907 | A test with subtests counts once. The column Pass counts the lines `ok` of the verbose output, from a ReleaseFast build before the last canvas change of this page (the negative `xview moveto` of a canvas). The first run of the day, before the fixes of this work, passed 834. On the Tk 8.6.16 of the system in a private Xvfb, all 1,412 tests pass and 35 are skipped. Most failures on ztk are differences of ztk itself, the same with or without Python: an option value that `wish` rejects and ztk accepts, the text of an error, and a value that Tk gives as a list or a number and ztk gives as text. ### Programs Each program ran unchanged with `ZTK_HEADLESS=1`. `ZTK_SCRIPT` sourced a script that wrote a snapshot of each window after some seconds and then called `exit`. | Program | Result | |---|---| | IDLE (`python3 -m idlelib`) | The shell window opens with its menus, the banner, and the prompt. | | turtledemo viewer (`python3 -m turtledemo`) | The window opens with its menus, the code pane, and the canvas. | | turtle demos (`python3 -m turtledemo.NAME`), 19 of them | Each starts and gives a snapshot with no Python error. clock, bytedesign, rosette, and tree finish in the time of the run. The drawing is slower than on Tk. | | The first example of the tkinter docs, and the feet to meters example of the Tk tutorial | Both work. | | Pillow `ImageTk.PhotoImage` | The image shows. `ImageTk.getimage` gives the pixels back with the alpha of Tk. | | A widget-heavy window (`tools/libztk/widgets.py`) | The notebook, 200 widgets, a treeview of 500 rows, and a text show. | | matplotlib with TkAgg | Not checked: matplotlib asks for a running X or Wayland display, and these runs were headless. | | SaVi 1.6.0 (a C program of Tk) | Works. See [Runs on ztk](apps.md). | ![IDLE on ztk](site/shots/app-python-idle.png) ![The clock of the turtle demos on ztk](site/shots/app-python-turtle-clock.png) ![The feet to meters example on ztk](site/shots/app-python-feet.png) ![A Pillow image in a label on ztk](site/shots/app-python-pillow.png) ### Speed and memory The time from `import tkinter` to the first `update` of a `Tk()`, and the time to make a window with a notebook of 200 widgets in a form, a treeview of 500 rows, and a text of 200 lines (`widgets.py`), each the median of 5 runs of `tools/libztk/bench.sh` in a private Xvfb (libztk on the X11 backend). The memory is the largest resident set of the process. libztk is a ReleaseFast build. | | Tk 8.6.16 | libztk | |---|---:|---:| | Startup | 0.083 s | 0.068 s | | Memory after startup | 20,156 KB | 24,364 KB | | Widget-heavy window | 0.128 s | 0.104 s | | Memory of that window | 28,980 KB | 42,284 KB | ## Known gaps - Linux only. A build for arm64 Linux stops at the variadic Tcl slots of libztcl (Zig 0.17 disables `VaList` there), and libztcl has no Windows build. macOS needs the AppKit backend in `Tk_Init`. - The X11 backend has one window, so a program with a second toplevel needs Wayland or the headless backend. - The Tk stubs table (`Tk_InitStubs`) is missing, so a Tk extension built with stubs does not load. - `exit` from a script during a busy loop of `update` in Python does not end the process. - `Tcl_GetCommandInfo` comes with ztcl#502; SaVi needs it. - The `tk` test failures above: options that ztk accepts and Tk rejects, error texts, list and number results of some commands, `send`, and the PRIMARY selection. # Widgets ztk has the widgets below today. Each one has the commands and the options of Tk 8.6, and the modern theme gives it its look. Each card below opens the live snippet of the widget: edit its code, and the window next to it runs the code as you type. [Differences from Tk](../differences.md) lists what each widget lacks. | Page | Widgets and commands | |---|---| | [Frames, labels, and buttons](basic.md) | `frame`, `label`, `button`, `labelframe`, `message`, `toplevel`, `grab`, `ztk::tooltip` | | [Check and radio buttons](toggles.md) | `checkbutton`, `radiobutton`, the switch and the segmented control | | [Entry and spinbox](entry.md) | `entry`, `spinbox`, placeholders, the search field, validation, undo, `clipboard` | | [Scale and scrollbar](range.md) | `scale`, `scrollbar`, the mouse wheel | | [Listbox](listbox.md) | `listbox`, the sidebar style | | [Canvas](canvas.md) | `canvas` with all item types, `image create photo` | | [Text](text.md) | `text`, tags, marks, undo | | [Tree](tree.md) | `ttk::treeview`, columns, the sidebar style | | [Panes and tabs](panes.md) | `panedwindow`, `ttk::panedwindow`, `ttk::notebook` | | [Dialogs](dialogs.md) | `tk_messageBox`, `tk_dialog`, `tk_chooseColor`, the file dialogs, `ztk::toast`, the banner style | | [Menus](menus.md) | `menu`, `menubutton`, `ttk::menubutton`, `tk_popup`, the menu bar | | [Terminal](terminal.md) | `ztk::terminal`, a terminal emulator on libghostty-vt, with scrollback, the shell of ztcl, and a pseudo-terminal | | [Themed widgets (ttk)](ttk.md) | `ttk::button`, `ttk::checkbutton`, `ttk::radiobutton`, `ttk::label`, `ttk::frame`, `ttk::labelframe`, `ttk::entry`, `ttk::separator`, `ttk::sizegrip` | | [pack, grid, and place](geometry.md) | The three geometry managers | `bind`, `bindtags`, `event generate`, `focus`, `wm`, `winfo`, and `tk` work as in Tk. [Styling and themes](../styling.md) and [Animation](../animation.md) cover the look and the motion. Open the [gallery in the playground](https://beetlebug.org/ztk/play/index.html?example=gallery) to try each widget. # Toys Three games made with ztk. Each one runs in the page as WebAssembly, and a widget of Tk is part of its play: the tabs of a `ttk::notebook` are the streets of Lamplighter, a `listbox` is the bag of Skate Pond, and a `ttk::scale` is the burner of Tin Moon. Each game is a short Tcl script, and you can read and change its code under the frame. ## Play - Click the frame, or press Enter on its button, to give the game the keys. A ring shows that the game has them. - The arrow keys or W, A, S, and D move. Space or Z is A, and X is B. Enter starts. - Escape or P pauses the game and gives the keys back to the page. The page scrolls as usual while the game has no keys. - A gamepad works while the game has the keys. A touch screen shows a pad and two buttons in the frame. - The sound and the music are off until you turn them on under the frame. "Shake off" turns off the screen shake and the flashes. - Each game keeps your open levels and your best scores in this browser only. ## How the games are made Each game is one Tcl script for ztk, from 400 to 600 lines. The design notes give the goals, the controls, the levels, and the checks of each game: - [Lamplighter](build/lamplighter.md) - [Skate Pond](build/skatepond.md) - [Tin Moon](build/tinmoon.md) The sound is made at run time in the page, with oscillators and noise of the Web Audio API. No game uses a sample, a font of its own, or an image file. # Lamplighter: the design Lamplighter is a platform game in [one Tcl script](https://github.com/beetlebugorg/ztk/blob/main/docs/toys/lamplighter.tcl). Night falls on a hill town, and you carry the last flame. [Play it on the Toys page](../toys.md). ## The widget Each level is a walk through 2 or 3 streets, and each street is a tab of a `ttk::notebook`. A tab opens (`.nb tab N -state normal`) when you walk off the right edge of the street before it. The text of each tab has a dot for each lamp, and a lit lamp fills its dot. A click on a tab that you saw takes you back to the start of that street, through `<>`. A stylesheet gives the notebook the colors of the night. ## The goal and the pressure - Touch each lamp to light it. The gate at the end of the last street opens when each lamp of the level is lit. - The night comes in about 100 seconds: the sky goes from dusk to night, and the bar at the top right empties. Each lit lamp pushes the night back by a fifth. - A fall into the water or a gap costs a little light and puts you at the start of the street. ## The levels The first level teaches by its layout, with no text: a lamp at walking height on flat ground, then a step and a lamp on a roof. Each later level adds one idea: | Level | Streets | The new idea | |---|---|---| | Lantern Lane | 2 | Walk, jump, touch a lamp. | | Mill Steps | 3 | Ledges that you jump up through, and a spring. | | The Ford | 3 | Boats that swing over the water and carry you. | | Bell Tower | 3 | Boards that break 40 frames after you step on them and come back. | | Hilltop | 3 | All of them, and a lamp that you light in the air. | ## The feel - The run speeds up and slows down (0.45 pixels per frame on the ground, 0.28 in the air), so a turn has weight. - Coyote time: a jump works for 6 frames after you leave an edge. - The jump buffer: a press up to 7 frames before you land jumps at the landing. - The jump is higher while you hold the button, and a release cuts it short. - The hero squashes on a hard landing and stretches on a jump. Dust comes up at a landing, and embers rise from the flame. - A lamp freezes the game for 4 frames and shakes the screen a little. "Shake off" under the frame turns the shake off. ## The art and the sound The palette has two sets of colors, dusk and night, and the dark of the level mixes them: 20 bands of the sky, two lines of hills, the roofs, and the stars that come out. A lit lamp has six rings of glow, each one a mix of the gold of the lamp into the sky behind it. The sound effects and the music (a slow bell theme in A minor on the title, a walking theme in the level) are made at run time by `assets/toysound.js`. ## The checks - A replay drives the game with `toy_input` calls at fixed frames and calls `step` and `draw` itself, so a run is the same each time. Lantern Lane ends in the state `clear` after 513 frames (8.6 s) with one jump, and the save string has the new best time. - A second check puts the hero on the highest floor under each of the 23 lamps of the five levels, runs a held jump with the physics of the game, and reads the lamp: each one lights. A held jump rises about 66 pixels, and the floors of a level are at most 36 pixels apart, except where a spring or a boat is the way up. - The screenshots of the title and of the second street were checked by eye. - The script of one step and one frame takes about 4.5 ms on a loaded 8-core Linux host in the native build. The browser runs the same script in WebAssembly. # Skate Pond: the design Skate Pond is a sliding puzzle in [one Tcl script](https://github.com/beetlebugorg/ztk/blob/main/docs/toys/skatepond.tcl). A push sends the skater over the ice until something stops it. [Play it on the Toys page](../toys.md). ## The widget The `listbox` on the right is the bag. A plank or a pick on the ice goes into the bag when you slide over it: `insert`, `itemconfigure -foreground` for the color of the item, `selection set`, and `see`. A click selects another item, and `<>` changes the hint under the bag. A uses the selected item, and `delete` takes it out of the bag. ## The rules - A push slides the skater until a snowbank or a rock stops it. A patch of snow stops the skater on it. Open water ends the move, and the run goes back one move. - A plank goes on the open water in front of you and makes a bridge. A pick breaks the rock in front of you. - B takes back a move, as many times as you want. Enter starts the level again. - Each level has three stars: one for the flag, one for the flag within par, and one for each snowflake on the way. ## The levels Seven levels, in the order of their ideas: | Level | Par | The new idea | |---|---|---| | First Ice | 2 | A push slides to the wall. | | Snow Stops | 2 | A patch of snow stops you in the middle. | | Thin Spot | 3 | Open water, and a snowflake off the short way. | | A Plank | 6 | Pick up a plank, face the water, and lay it. | | The Pick | 6 | A row of rocks, and the pick that breaks one. | | Crossing | 5 | A rock as a stop, then a plank. | | Long Night | 7 | A long way around with a plank. | A solver (a breadth-first search over the place, the facing, the tiles, the bag, and the snowflakes) checked that each level has a way to the flag, and gave the par and the moves for each snowflake. The par of each level is the shortest way. ## The feel - A slide is a tween with an ease-out: a long slide is fast and settles at the end, from 7 to 26 frames. - A push during a slide waits for its end (the input buffer), so quick players do not lose a move. - The skater leans into a slide, the scarf trails behind, and ice spray comes off the skates. A stop at a wall squashes the skater and shakes the screen a little; a stop on snow puffs. ## The art and the sound A cold palette: two shades of ice in a checker, cracks, snowbanks with a shadow, rocks, and dark water. The stars are canvas polygons, so they do not depend on the glyphs of a font. The music is a light theme in G major, made at run time with the effects. ## The checks Each level was played in a headless run with the moves of the solver as recorded inputs. The run of "A Plank" ends in the state `clear` with 6 moves, and the save string keeps the stars. # Tin Moon: the design Tin Moon is a balloon flight in [one Tcl script](https://github.com/beetlebugorg/ztk/blob/main/docs/toys/tinmoon.tcl). You steer only with height. [Play it on the Toys page](../toys.md) or on the home page. ![A flight of Tin Moon: the balloon rises into the east wind, drifts over the hills, and sinks toward the green pad, too fast](../site/shots/toy-tinmoon-clip.gif) ## The widgets The `ttk::scale` on the right is the burner, on `-variable heat`. Drag it, or hold Up and Down: the keys move the scale, so you see the heat that you set. The `ttk::progressbar` under the sky is the fuel, on `-variable fuel`. The burner uses fuel at the rate of the heat, and with no fuel the burner is off. ## The idea A balloon cannot steer left or right. Each layer of the sky has its own wind, and the streaks and the arrows of a layer show its way and its speed. To go east, climb or sink into a wind to the east. The heat changes the air in the envelope slowly, so the balloon answers late: you plan a climb before you need it. Land on the green pad slowly. A fast touch, a large swing of the basket, or a spire is a crash. ## The levels | Level | The winds | The new idea | |---|---|---| | Drift | One wind to the east | Rise, drift, and sink onto the pad. | | Two Winds | East above, west below | Climb to go east fast, then sink. | | Back Home | West above, calm, east below | The pad is behind you. | | Spires | Three layers | Rock spires under the low wind. | | Long Night | Three layers, little fuel | A long route with each idea. | The score of a landing is the fuel left times 10, and 250 for each moon mote. The best score of each level stays in the browser. ## The feel - The wind of a layer moves the balloon with a lag, so a change of layer is a slow turn. - The basket swings on its ropes when the balloon speeds up, and a large swing at a landing is a crash. - The camera leads the balloon by its speed and eases to it. The sky stays, the far hills move at half the speed, and the ground moves at full speed. - A gust plays when you enter a new layer, and the burner roars while the heat is high. ## The art and the sound A blue night with a large moon, an amber balloon with a cream stripe, and a mint pad with lights that blink. The music is a slow line in D dorian. Both are made at run time. ## The checks A pilot script sets the burner in each frame with the physics of the game, and two forms of it landed on the pad of each level: - A search holds the height of the best wind and starts to sink at a point; it tries a point every 40 pixels. It lands Drift (sink from x 560 or 600, 87 fuel left), Two Winds (from x 800 or 840, 82 fuel left), and Back Home (from x 200, 71 fuel left). - A pilot that sinks when the time to the pad is less than the time to the ground lands Spires (32 fuel left) and Long Night (55 fuel left). The windows of these points are narrow for a script with fixed rules, and a player corrects in each frame. The landing limits are a sink speed of 1.5 pixels a frame and a swing of the basket of 12 pixels. The clip above is a run of the pilot in the live frame loop that comes in too fast. # Frames, labels, and buttons **Live:** the Buttons card and the Labelframe card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery), and the [sign-in form](https://beetlebug.org/ztk/play/index.html?example=signin). ## frame, label, and button ![A frame with the label Print farm and the buttons Start and Stop, with Stop disabled](../site/shots/widget-button-light.png) ```tcl frame .card -padx 16 -pady 12 label .card.title -text "Print farm" button .card.go -text "Start" -command {puts started} button .card.off -text "Stop" -state disabled pack .card -fill both -expand 1 pack .card.title -anchor w pack .card.go .card.off -side left -padx 4 -pady 8 ``` The [reference of button](../reference/button.tcl) has each option and each widget command of `button`, with examples. - `button` has `invoke`, `flash`, `-command`, `-state`, and `-default`. A button is a `Button` in CSS. - The theme gives the border and the padding, so `-borderwidth`, `-padx`, and `-pady` default to 0. A value of the script overrides the theme. - `ztk::class .card.go add primary` gives a widget a style class for your stylesheet. ## labelframe and message ![A labelframe with the title Notes around a message of three lines](../site/shots/widget-labelframe-light.png) ```tcl labelframe .notes -text "Notes" -padx 12 -pady 6 message .notes.m -width 260 -text "A message breaks its text into lines. A labelframe puts a title above a group of widgets." pack .notes.m -anchor w pack .notes -fill x -padx 8 -pady 8 ``` ## toplevel and grab ```tcl toplevel .about wm title .about "About" label .about.l -text "ztk" button .about.ok -text "Close" -command {destroy .about} pack .about.l .about.ok -padx 20 -pady 8 grab .about ``` Each `toplevel` has its own window and render thread. `grab` is local: `-global` acts as a local grab. In the browser, only the window `.` has a canvas. ## Tooltips `ztk::tooltip path ?text?` shows a text when the pointer rests on a widget. The tooltip fades in and out, and its part `::tooltip` accepts CSS rules. ![A window with one button, Save](../site/shots/widget-tooltip-light.png) ```tcl button .save -text "Save" pack .save -padx 20 -pady 20 ztk::tooltip .save "Saves the document" ``` # Check and radio buttons **Live:** the check button and radio button cards of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). ## checkbutton ![The check button Sync files on, the check button Some of the folders, in the mixed state, and a Wi-Fi switch that is off](../site/shots/widget-checkbutton-light.png) ```tcl set opts(sync) 1 set opts(mixed) x checkbutton .sync -text "Sync files" -variable opts(sync) checkbutton .mixed -text "Some of the folders" -variable opts(mixed) -tristatevalue x checkbutton .wifi -text "Wi-Fi" -variable opts(wifi) ztk::class .wifi add switch pack .sync .mixed .wifi -anchor w -padx 12 -pady 2 ``` - The style class `switch` draws a check button as a switch. Its knob slides with a spring. - A variable with the value of `-tristatevalue` shows the mixed state. - `select`, `deselect`, `toggle`, and `invoke` work as in Tk. `flash` has no effect. ## radiobutton ![Three radio buttons with Fine detail selected, and a segmented control of List, Grid, and Columns with List selected](../site/shots/widget-radiobutton-light.png) ```tcl set quality high foreach {v t} {low Draft normal Normal high "Fine detail"} { radiobutton .q$v -text $t -variable quality -value $v pack .q$v -anchor w -padx 12 } frame .seg foreach {v t} {list List grid Grid columns Columns} { radiobutton .seg.$v -text $t -variable view -value $v -indicatoron 0 ztk::class .seg.$v add segmented pack .seg.$v -side left } set view list pack .seg -padx 12 -pady 8 ``` The style class `segmented` joins radio buttons with `-indicatoron 0` into a segmented control. ## In CSS The indicator is the part `::indicator`, and the states are pseudo-classes: ```css Checkbutton.switch:checked::indicator { background: #16a34a; } Radiobutton:hover::indicator { border-color: var(--accent); } ``` The `ttk` forms are on [Themed widgets](ttk.md). # Entry and spinbox **Live:** the Text input card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). ## entry ![An entry with the text Ada Lovelace, an empty password entry, and a round search field with the placeholder Search files](../site/shots/widget-entry-light.png) ```tcl set name "Ada Lovelace" entry .name -textvariable name -width 22 entry .pw -show * -width 22 entry .search -width 22 -placeholder "Search files" ztk::class .search add search pack .name .pw .search -padx 12 -pady 4 ``` - `-placeholder` and `-placeholderforeground` show a hint in an empty entry. They are the names of Tk 8.7. - The style class `search` adds a search icon and a clear button. - Undo and redo: Control-z, Control-Shift-z, and Control-y, or `event generate .name <>`. A run of typed text is one step. - Cut, copy, and paste use the `clipboard` command. In this version the clipboard is local to the app. - `xview` and `-xscrollcommand` connect an entry to a [scrollbar](range.md). - Left, Right, Backspace, and Delete move and delete by grapheme cluster (Unicode UAX #29), and a double click selects a word of UAX #29. The index of an entry still counts characters, as in Tk. ## Validation Validation follows Tk: the modes, the `%` fields, and `-invalidcommand`. ```tcl entry .qty -validate key -validatecommand {string is integer %P} -invalidcommand bell pack .qty -padx 12 -pady 4 ``` ## spinbox ![A spinbox with the number 1 and a readonly spinbox with the text Medium](../site/shots/widget-spinbox-light.png) ```tcl spinbox .copies -from 1 -to 99 -width 6 spinbox .size -values {Small Medium Large} -state readonly -width 10 .size set Medium pack .copies .size -padx 12 -pady 4 ``` A spinbox has `-format`, `-wrap`, `-command`, and the repeat of a held button. The buttons are the parts `::buttonup` and `::buttondown` in CSS. # Scale and scrollbar **Live:** the Scale and Scrollbar cards of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). ## scale ![A horizontal scale at 40 with the ticks 0, 25, 50, 75, and 100](../site/shots/widget-scale-light.png) ```tcl set vol 40 scale .vol -orient horizontal -from 0 -to 100 -variable vol -tickinterval 25 -length 260 pack .vol -fill x -padx 12 -pady 8 ``` - The slider follows the pointer on the render thread, so a drag stays smooth while the script is busy. - The parts `::trough`, `::fill`, `::slider`, and `::value` accept CSS rules. ## scrollbar ![An entry with a long line of text and a horizontal scrollbar under it](../site/shots/widget-scrollbar-light.png) ```tcl entry .e -width 22 -xscrollcommand {.s set} scrollbar .s -orient horizontal -command {.e xview} .e insert 0 "A long line of text that is wider than its entry, so the scrollbar under it moves the view." pack .e .s -fill x -padx 12 ``` - The modern scrollbar is an overlay. Its thumb shows while the view scrolls, on hover, and during a drag, and then fades out. The `classic` theme draws the scrollbar of Tk. - A scroll by units or pages eases over 160 ms. A touchpad step adds momentum. - The mouse wheel sends `` with `%D` (120 for one step), and `` for a horizontal step, as in Tk 8.7. A touchpad gives fractions of 120. - The parts `::trough` and `::thumb` and the pseudo-class `:scrolling` accept CSS rules. # Listbox **Live:** the Lists card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery), and the layer list of the [vector tool](https://beetlebug.org/ztk/play/index.html?example=vector). ## listbox ![A listbox with four file names](../site/shots/widget-listbox-light.png) ```tcl listbox .files -height 6 -selectmode extended -yscrollcommand {.sb set} -emptytext "No files" scrollbar .sb -command {.files yview} .files insert end report.pdf notes.txt photo.png budget.xlsx bind .files <> {puts [.files curselection]} pack .files -side left -fill both -expand 1 pack .sb -side right -fill y listbox .side -height 4 -activestyle none .side insert end Inbox Drafts Sent Archive ztk::class .side add sidebar ``` - The listbox has the options, the subcommands, and the four selection modes of Tk 8.6: `single`, `browse`, `multiple`, and `extended`. The pointer and the keys select rows as in `wish`, and a change by the user sends `<>`. - `-listvariable` links the rows to a list variable in both directions. - When the selection moves from one row to another row, its background eases between the rows in 180 ms. - A scroll eases, and a touchpad scrolls by pixels with momentum. A whole step of `yview scroll` or `yview moveto` puts a row at the top, as in Tk. - The additions: `-emptytext` shows a text in an empty listbox, and the style class `sidebar` gives a list with no field and round accent rows. - The parts `::item`, `::selection`, `::active`, and `::empty` accept CSS rules. # Canvas The canvas has every item type of Tk 8.6: `arc`, `bitmap`, `image`, `line`, `oval`, `polygon`, `rectangle`, `text`, and `window`, with tags, bindings, scrolling, and `scale`. Only `postscript` is missing. **Live:** the Canvas card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery), the [spreadsheet](https://beetlebug.org/ztk/play/index.html?example=spreadsheet), and the [vector tool](https://beetlebug.org/ztk/play/index.html?example=vector). ![A canvas with a blue square, an orange circle, a green triangle, and the text Drag a shape](../site/shots/widget-canvas-light.png) ```tcl canvas .c -width 300 -height 110 -highlightthickness 0 pack .c -fill both -expand 1 .c create rectangle 8 10 88 66 -fill #2563eb -activefill #3b82f6 -outline {} -tags shape .c create oval 108 8 168 68 -fill #f59e0b -outline {} -tags shape .c create polygon 188 68 218 8 248 68 -fill #10b981 -tags shape .c create text 12 90 -text "Drag a shape" -anchor w .c bind shape {set ::xy [list %x %y]; %W raise current} .c bind shape { lassign $::xy x0 y0 %W move current [expr {%x - $x0}] [expr {%y - $y0}] set ::xy [list %x %y] } ``` - `ztk::animate {.c tagOrId} -coords {...} -fill red -duration 300` moves items. See [Animation](../animation.md). - Items that keep the default black of Tk draw with the text color of the theme, so they show in the dark scheme. - `image create photo` reads PNG data from `-data` or a PNG file in the folder of the script. ## Showcase: the spreadsheet ![A spreadsheet with a menu bar, a formula bar, number formats, and a grid of costs by quarter with totals and error cells](../site/shots/spreadsheet-light.png) [`examples/spreadsheet.tcl`](../../examples/spreadsheet.tcl) has 10,000 rows on one canvas. It makes items only for the cells in view. Formulas such as `=sum(B2:B7)` are Tcl expressions, with recalculation and cycle errors. A scroll frame uses 0.75 ms of CPU time at the median. ## Showcase: the vector tool ![A drawing tool with a menu bar, tools, a page with a sun, mountains, and a tilted square, a properties panel, and a console](../site/shots/vector-light.png) [`examples/vector.tcl`](../../examples/vector.tcl) draws rectangles, ellipses, lines, polygons, paths, and text, with handles that move, resize, and rotate. It has undo, groups, the z-order, zoom, and SVG export. Its console runs Tcl in a child interpreter under `ztk::limit`, a step and memory limit for one script. # Text **Live:** the [playground](https://beetlebug.org/ztk/play/index.html) runs the example below. ## text ![A text widget with a heading in bold, a line with a blue link, a selected word, and a list of steps with a hanging indent](../site/shots/widget-text-light.png) ```tcl text .t -wrap word -undo 1 -width 30 -height 8 -yscrollcommand {.sb set} scrollbar .sb -command {.t yview} .t tag configure title -font {TkDefaultFont 14 bold} -spacing3 6 .t tag configure link -foreground #2563eb -underline 1 .t tag configure step -lmargin1 8 -lmargin2 24 .t insert end "Release notes\n" title .t insert end "The text widget has tags, marks, undo, and smooth scrolling. See the " {} "manual page" link ".\n\n" .t insert end "1. Type in the text. Control-z undoes a change.\n" step .t insert end "2. Drag to select. A double click selects a word.\n" step .t insert end "3. The wheel scrolls by pixels, with momentum on a touchpad.\n" step .t tag bind link {.t configure -cursor hand2} .t tag bind link {.t configure -cursor xterm} .t tag add sel 2.4 2.8 pack .sb -side right -fill y pack .t -side left -fill both -expand 1 -padx 8 -pady 8 focus .t ``` - The text widget has the options, the indexes, and the subcommands of Tk 8.6: `bbox`, `compare`, `count`, `delete`, `dlineinfo`, `dump`, `edit`, `get`, `image`, `index`, `insert`, `mark`, `replace`, `search`, `see`, `tag`, `window`, `xview`, and `yview`. `peer` has no peers in ztk. An index has the forms and the modifiers of `text.n`, such as `insert wordend`, `end - 1 chars`, and `insert + 1 display lines`. The unit `graphemes` (or a prefix such as `g`) is a ztk addition: `insert + 1 graphemes` counts grapheme clusters, so an accent, a flag, or an emoji with a skin tone is one step. - Left, Right, Backspace, and Delete move and delete by grapheme cluster (Unicode UAX #29). A double click selects a word of UAX #29, such as `can't` or `3.14`. A wrapped line breaks only between clusters. - Tags give text colors, fonts, underlines, margins, spacing, justification, and elided text. `tag bind` runs a script for the events of the tagged text, with `` and `` as the pointer moves between tags. - `window create` puts a widget in the text, and `image create` puts a photo image in it. Each one has one place in the index space and moves with the text. `-align`, `-padx`, `-pady`, and `-stretch` place it in its line, and `-create` makes a window when the embed has none. `dump -window` and `dump -image` list them. A delete of the range of a window deletes the window. - `search` finds exact text or a regular expression, forwards or backwards, with `-all`, `-count`, and `-nocase`. `dump` lists the text, the marks, and the tag edges of a range. - Marks keep a place in the text with their gravity. `insert` is the caret and `current` is the character under the pointer. - `-wrap char`, `word`, and `none` wrap the lines, and tabs go to the stops of `-tabs`. A buffer of 1 MB scrolls at the full frame rate: the widget lays out only the lines in the window. - `-undo 1` turns on undo and redo, with `edit undo`, `edit redo`, `edit separator`, and Control-z. `<>` comes when the text changes. - The keys and the pointer edit the text as in `wish`. A scroll eases, and a touchpad scrolls by pixels with momentum. The caret blinks while the widget has the focus. Text from an input method shows at the caret until it is committed. - The part `::selection` gives the colors of the tag `sel` in the modern theme. # Tree **Live:** the [playground](https://beetlebug.org/ztk/play/index.html) runs the example below. ## ttk::treeview ![A tree of files with the columns Name, Size, and Modified, an open folder, and a selected row](../site/shots/widget-treeview-light.png) ```tcl ttk::treeview .t -columns {size modified} -height 6 .t heading #0 -text Name -anchor w .t heading size -text Size -anchor w .t heading modified -text Modified -anchor w .t column #0 -width 150 .t column size -width 70 -anchor e .t column modified -width 100 .t insert {} end -id docs -text Documents -open 1 .t insert docs end -text Report.pdf -values {"1.2 MB" "Nov 24"} .t insert docs end -text Budget.ods -values {"88 KB" "Nov 20"} .t insert {} end -id pics -text Pictures -values {"" "Nov 18"} .t insert pics end -text beach.png -values {"2.4 MB" "Nov 18"} .t insert {} end -text notes.txt -values {"4 KB" Today} .t selection set [lindex [.t children docs] 0] pack .t -fill both -expand 1 -padx 8 -pady 8 focus .t ``` - The tree has the options, the item options, the column options, the heading options, the tag options, and the subcommands of `ttk_treeview.n`: `bbox`, `children`, `column`, `delete`, `detach`, `exists`, `focus`, `heading`, `identify`, `index`, `insert`, `item`, `move`, `next`, `parent`, `prev`, `see`, `selection`, `set`, `tag`, `xview`, and `yview`. - A click selects a row, Shift extends the selection, and Control toggles a row with `-selectmode extended`. A click on the arrow or a double click opens and closes an item. The arrow keys move the focus, Right opens an item, and Left closes it. `<>`, `<>`, and `<>` come as in `wish`. - An item opens and closes with a move of the rows below it, and its arrow turns. - A drag of the border at the right of a heading changes the width of the column. A click on a heading runs its `-command`. - `tag configure` gives rows colors and fonts, and `tag bind` runs a script for the events of the rows with the tag. - `-emptytext` shows a text when the tree has no items. The style class `sidebar` (`ztk::class .t sidebar`) gives a tree with no border, for the side of a window. # Panes and tabs **Live:** the Panes and Tabs cards of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). ## panedwindow and ttk::panedwindow ![A window with a list of mail folders on the left and two panes on the right, one above the other, with a thin line between each pair of panes](../site/shots/widget-panedwindow-light.png) ```tcl panedwindow .p listbox .p.list -width 10 .p.list insert end Inbox Drafts Sent Archive Trash .p.list selection set 0 ttk::panedwindow .p.right -orient vertical label .p.right.mail -text "Drag a sash" label .p.right.info -text "This pane gets twice the space" .p.right add .p.right.mail -weight 1 .p.right add .p.right.info -weight 2 .p add .p.list -stretch never .p add .p.right -stretch always pack .p -fill both -expand 1 -padx 8 -pady 8 ``` - `panedwindow` puts its panes in a row (`-orient horizontal`) or a column, with a sash between two panes. It has the options, the pane options, and the subcommands of Tk 8.6: `add`, `forget`, `identify`, `panecget`, `paneconfigure`, `panes`, `proxy`, and `sash` with `coord`, `dragto`, `mark`, and `place`. - A pane has the size of its widget, or its `-width` or `-height`, plus `-padx` or `-pady`. `-sticky` places the widget in its pane. `-stretch` picks the panes that get the extra space, or lose space, when the panedwindow changes size. A sash move stops at the `-minsize` of the panes. - `ttk::panedwindow` has `add`, `forget`, `identify`, `insert`, `pane`, `panes`, and `sashpos`. A change of the size goes to the panes in proportion to their `-weight`. `sashpos` puts a sash between its neighbors and pushes them when it must. - A press on a sash and a drag move it. The panes follow the pointer in each frame, and the render thread moves the sash with the pointer while a script is busy. With `-opaqueresize 0`, a drag moves a line, and the release moves the sash. `-showhandle` draws a handle on each sash. - The pointer shape is a resize arrow over a sash, or the shape of `-sashcursor`. - The modern theme draws a sash as a thin line in the part `::sash`. The sash under the pointer or in a drag fades to the part `::sash-active` in 120 ms. ## ttk::notebook ![A notebook with the tabs General, Network, and Advanced, the General tab selected with a blue line under it, and a page with two check buttons](../site/shots/widget-notebook-light.png) ```tcl ttk::notebook .n foreach {page title} {general General network Network advanced Advanced} { ttk::frame .n.$page -padding 12 .n add .n.$page -text $title -underline 0 } set login 1 set menubar 0 ttk::checkbutton .n.general.a -text "Open at login" -variable login ttk::checkbutton .n.general.b -text "Show in the menu bar" -variable menubar pack .n.general.a .n.general.b -anchor w -pady 2 ttk::label .n.network.l -text "Proxy: none" pack .n.network.l -anchor w .n tab .n.advanced -state disabled ttk::notebook::enableTraversal .n pack .n -fill both -expand 1 -padx 8 -pady 8 ``` - `ttk::notebook` has the subcommands of Tk 8.6: `add`, `forget`, `hide`, `identify`, `index`, `insert`, `select`, `tab`, and `tabs`, with `instate` and `state`. A tab is `normal`, `disabled`, or `hidden`, and it has `-text`, `-underline`, `-padding`, and `-sticky`. - A click on a tab selects it. `Left` and `Right` move to the next tab that is not disabled, and `Control-Tab` and `Control-Shift-Tab` cycle the tabs. `ttk::notebook::enableTraversal` adds these keys to the whole window, with `Control-Page Up`, `Control-Page Down`, and `Alt` with the letter of `-underline`. - Each change of the selected tab sends `<>` after the script that made the change. - The line under the selected tab slides to the new tab in 200 ms, and the new page fades in over 150 ms. A change during the slide starts from the shown place. - The parts `::tab`, `::tab-selected`, `::tab-hover`, `::tab-disabled`, `::indicator`, and `::client` of `TNotebook` accept CSS rules. # Dialogs **Live:** the [playground](https://beetlebug.org/ztk/play/index.html) runs the example below. ## The dialogs and ztk::toast ![A banner and three buttons that open a message box, a color dialog, and a toast](../site/shots/widget-dialogs-light.png) ```tcl frame .banner label .banner.l -text "Your changes are not saved." pack .banner.l -anchor w ztk::class .banner add banner button .ask -text "Message box" -command { set r [tk_messageBox -message "Save the changes?" -detail "The changes are lost when you close the window." -type yesnocancel -icon question] ztk::toast "You chose $r" } button .color -text "Color" -command { set c [tk_chooseColor -initialcolor #2563eb] if {$c ne ""} { .banner configure -background $c } } pack .banner -fill x -padx 12 -pady 12 pack .ask .color -side left -anchor n -padx {12 0} ``` - `tk_messageBox` has the options, the types, the icons, and the results of `messageBox.n`. Return invokes the button with the focus, and Escape gives `cancel`, or `no`, `abort`, or `ok` when the type has no cancel button. On Windows it is the message box of the system. - `tk_dialog` gives the number of the button, or -1 when the window closes. - `tk_chooseColor` has a grid of swatches, sliders for red, green, and blue, and a hex field. It gives a color such as `#2563eb`, or an empty string for a cancel. On Windows it is the color dialog of the system. - `tk_getOpenFile`, `tk_getSaveFile`, and `tk_chooseDirectory` list the folders and the files, with the filters of `-filetypes`. They need the file capability of the program. On Windows and macOS they are the dialogs of the system. On Wayland they are the file chooser of the desktop portal when the session bus has `org.freedesktop.portal.Desktop`, and else the dialogs that ztk draws. - Each dialog is a toplevel of the class `Dialog` with a grab, and it fades in. - `ztk::toast text ?-duration ms?` shows a short message at the bottom of the window. It slides in, stays for 2,500 ms by default, and slides out. The style class `banner` gives a frame the look of a message in the page. # Menus **Live:** the Menus card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). ## menu, menubutton, and ttk::menubutton ![A window with a menu bar of File, Edit, and View, and the File menu open with New, Open, a separator, and Close, each with its key](../site/shots/widget-menu-light.png) ```tcl menu .bar . configure -menu .bar foreach {name text} {file File edit Edit view View} { menu .bar.$name -tearoff 0 .bar add cascade -label $text -menu .bar.$name -underline 0 } .bar.file add command -label New -accelerator Ctrl+N -command {set status New} .bar.file add command -label Open... -accelerator Ctrl+O -command {set status Open} .bar.file add separator .bar.file add command -label Close -accelerator Ctrl+W -command {set status Close} .bar.edit add command -label Undo -accelerator Ctrl+Z -command {set status Undo} .bar.edit add command -label Redo -state disabled .bar.view add checkbutton -label "Show grid" -variable grid .bar.view add radiobutton -label Small -variable size -value small .bar.view add radiobutton -label Large -variable size -value large set grid 1 set size small set status "Click File, press F10, or right-click" ttk::menubutton .mb -text Size -menu .bar.view label .status -textvariable status pack .mb -pady {24 8} pack .status bind . {tk_popup .bar.edit %X %Y} ``` - `menu` has the five entry types of Tk 8.6 (`command`, `cascade`, `checkbutton`, `radiobutton`, and `separator`), the tearoff entry, and the subcommands and the messages of `wish` 8.6.16. `invoke` sets the variable of a check or radio entry and then runs `-command`. A change of the active entry sends `<>`. - `toplevel -menu` gives the window a menu bar. On Linux and the web, ztk draws the bar as a row at the top of the window, as Tk on X11 does. The content of the window goes below the row. macOS and Windows show their own menus. - `tk_popup` and `post` show a menu at a point of the window. A cascade opens on the right of its entry. On Wayland, each posted menu and each cascade is a popup surface (`xdg_popup`) that can extend past the window: the compositor flips a cascade to the left and slides a menu when the screen has no room. On the web, each one is a canvas in a layer above the page, and the viewport is the screen. - `menubutton` and `ttk::menubutton` post their `-menu` on the side of `-direction`. A drag from the button to an entry and a release there invokes the entry. - The pointer: motion activates an entry and opens a cascade, a release invokes the entry, and a press outside the menus closes them. - The keys: `Up` and `Down` move the active entry, `Right` opens a cascade, `Left` closes it, and `Return` or `space` invokes the entry. `Escape` closes the menu. The letter of `-underline` invokes its entry. On the menu bar, `F10` opens the first menu, `Alt` with a letter opens the menu with that `-underline` letter, and `Left` and `Right` move along the bar. - A menu opens with a fade and a slide of 6 logical pixels in 150 ms, and fades out in 150 ms after it closes. The moves run on the render thread. The highlight of the active entry eases from one entry to the next in 120 ms. - The parts `::item`, `::item-active`, `::separator`, `::accelerator`, and `::indicator` of the class `Menu` accept CSS rules, and so do `::bar`, `::bar-item`, and `::bar-item-active` for the menu bar row. `Menubutton::indicator` is the chevron of a menu button. # Terminal ## ztk::terminal `ztk::terminal` is a terminal emulator widget. This one runs the shell of ztcl: click it, type `pu`, and press Tab. Up and Down go through the history. ```tcl ztk::terminal .t -shell 1 -width 60 -height 14 pack .t -fill both -expand 1 focus .t ``` | Option or command | What it does | |---|---| | `-shell 1` | Runs the shell of `ztcl` in the interpreter of the widget: Tab completion, history, colors. | | `-command list` | Runs a program on a pseudo-terminal, for example `-command {/bin/sh -l}`. It needs `exec`. | | `-inputcommand script` | Gets the keys and the replies when no program runs. | | `-width`, `-height` | The size in cells. | | `-font` | The font of the cells. The default is TkFixedFont, a monospace face. | | `-scrollback n` | The lines of the scrollback (default 10,000). | | `write`, `send`, `paste` | Put text and sequences on the screen, or send bytes to the program. | | `get`, `size`, `cursor`, `title` | Read the screen. | | `selection`, `copy`, `yview` | Select, copy, and scroll. | ### Write your own output Without a program, `write` puts text and escape sequences on the screen, and `-inputcommand` gets the keys. This snippet echoes what you type. ```tcl ztk::terminal .t -width 40 -height 12 -inputcommand echo pack .t -fill both -expand 1 proc echo {data} {.t write [string map [list \r \r\n] $data]} .t write "\x1b\[1;32m$\x1b\[0m echo hello\r\nhello\r\n" .t write "\x1b\[1;34mblue\x1b\[0m \x1b\[7minverse\x1b\[0m \x1b\[4munderline\x1b\[0m\r\n" .t write "╭────╮\r\n│ ok │\r\n╰────╯\r\n$ " focus .t ``` `ztk::terminal` is a terminal emulator. Its state (the parser, the screen, the scrollback, the cursor, and the modes) is [libghostty-vt](https://github.com/ghostty-org/ghostty) 1.0.2, the terminal core of Ghostty, through the `ztcl::vt` module of ztcl. The build compiles it from source and links it statically on each target, with no C code, no C++ code, and no libc. ztk renders the cells with its own fonts and colors, so each renderer draws the terminal, and ztk handles the keys, the mouse, and the selection. Tk has no terminal widget. On 2026-11-26, `zig build term-bench` (ReleaseFast, 8,388,627 bytes of generated output on 80 by 24 cells, x86-64 Linux) parsed 141.6 MiB/s with libghostty-vt, against 114.7 MiB/s with the earlier VT core of ztk. libghostty-vt and `ztcl::vt` add 595,823 bytes to `ztk.wasm` (`docs/dev/libghostty.md`). The widget keeps no combining marks, and a resize cuts long lines and does not wrap them again. The design is in `docs/dev/terminal.md`, and [the references](../references/terminal.md) credit Ghostty. | Platform | `-shell 1` | `-command` (a program on a PTY) | |---|---|---| | Linux, x86-64 and arm64 | Yes | Yes, on a pseudo-terminal of `ztcl::pty`, when the embedder turns on `exec` | | macOS, arm64 and x86-64 | Yes | Yes, as on Linux | | Windows, x86-64 | Yes | Yes, on a pseudo console (ConPTY) | | The web (WebAssembly) | Yes | No: the browser build has no processes | - `-command list` runs a program on a pseudo-terminal with `ztcl::pty spawn`, for example `-command {/bin/sh -l}` or `-command {vim notes.txt}`. The interpreter needs the `exec` capability of ztcl. The `ztk` program does not turn it on, so in `ztk` and in the playground `-command` gives an error. An embedder that turns on `exec` and `channels` gets a full terminal. `-cwd dir` is the working folder of the program, and `-exitcommand script` runs with the status of `ztcl::pty status` when the program ends. On Windows the program runs on a pseudo console (ConPTY), for example `-command cmd.exe` or `-command {powershell.exe -NoLogo}`, and its output has the escape sequences of a VT terminal. - Without a program, `pathName write data` puts text and control sequences on the screen, and the keys and the replies of the terminal go to the script of `-inputcommand`, with the bytes as the last word. - `-shell 1` runs the interactive shell of the `ztcl` program in the interpreter of the widget, with no program and no PTY. It is the same line editor as in a terminal: Tab completes commands, subcommands, variables, and the file names when the interpreter has `file`. Up and Down go through the history, `shell mode vi` turns on vim keys, and the code has colors. The output of `puts` goes to the screen. The shell has the capabilities and the compute limit of the interpreter, so in `ztk` and in the playground it has no files, network, or clock. Ctrl-D on an empty line starts a new prompt. The editor key (Ctrl-X Ctrl-E) gives the line back with no change, because the widget has no editor. - `-width` and `-height` are the size in cells. After the layout, the size of the grid follows the size of the widget, and the program gets the new size. - The terminal understands the sequences of xterm that shells and full-screen programs use: the cursor moves, the erase and insert functions, the scroll region, SGR with 16, 256, and 24-bit colors, bold, italic, underline, inverse, and strike, the alternate screen, the DEC line drawing set, wide characters, grapheme clusters (mode 2027, on by default: a cell holds a whole cluster, such as an emoji ZWJ sequence), bracketed paste, the mouse reports (X10, normal, button, and any-motion, in the SGR form or the X10 form), the focus reports, the window title, and the replies to the status queries and the color queries. - The box drawing characters and the block elements are rendered as boxes, so their lines meet with each font. - `-scrollback n` keeps n lines (default 10,000). The wheel and Shift with Prior or Next scroll the view, and `yview` works as for a listbox. - A drag with button 1 selects text, a double click selects a word, and a triple click selects a line. Control-Shift-C copies the selection and Control-Shift-V pastes. When the program asks for mouse reports, hold Shift to select. - Subcommands: `write`, `send`, `paste`, `get ?first? ?last?` (the text of view lines, where 0 is the first row of the screen and negative lines are in the scrollback), `size`, `cursor`, `title`, `selection get|clear|range`, `copy`, `yview`, `channel`, `status`, and `kill ?signal?`. - The part `::selection` accepts CSS rules. The class `Terminal` gets its colors from the theme. # Themed widgets (ttk) ztk has these widgets of the Tk themed set: `ttk::button`, `ttk::checkbutton`, `ttk::radiobutton`, `ttk::label`, `ttk::frame`, `ttk::labelframe`, `ttk::entry`, `ttk::separator`, `ttk::sizegrip`, and the range widgets `ttk::combobox`, `ttk::spinbox`, `ttk::scale`, `ttk::scrollbar`, and `ttk::progressbar`. Each one has the options of `wish` 8.6.16, in its order, with its defaults and its error messages. `ttk::style` restyles them, and the theme sets their look. **Live:** the [ttk window in the modern theme](https://beetlebug.org/ztk/play/index.html?example=themes), the [same window in the classic theme](https://beetlebug.org/ztk/play/index.html?example=themes-classic), and the Themed widgets card of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). | Modern theme | Classic theme | |---|---| | ![Each ttk widget in the modern theme: a blue Accent button, Cancel, a disabled button, a check box, a switch, radio buttons, a separator, two entries, and a size grip](../site/shots/themes-light.png) | ![The same window in the classic theme, with the square reliefs of Tk](../site/shots/themes-classic-light.png) | [`examples/themes.tcl`](../../examples/themes.tcl) is the script of both images. ## The widgets ![A ttk labelframe with an accent button Apply, a check button, a switch, two radio buttons, a separator, and an entry, with a status line and a size grip](../site/shots/widget-ttk-light.png) ```tcl ttk::style configure Accent.TButton -foreground white -background #2563eb ttk::style map Accent.TButton -background {active #1d4ed8} ttk::frame .f -padding 16 ttk::labelframe .f.lf -text "Options" -padding 10 ttk::button .f.lf.ok -text "Apply" -style Accent.TButton ttk::checkbutton .f.lf.notify -text "Notify me" -variable notify ttk::checkbutton .f.lf.wifi -text "Wi-Fi" -style Switch.TCheckbutton -variable wifi ttk::radiobutton .f.lf.s -text "Small" -variable size -value S ttk::radiobutton .f.lf.m -text "Medium" -variable size -value M ttk::separator .f.lf.sep -orient horizontal ttk::entry .f.lf.name -width 24 ttk::label .f.status -text "Ready" ttk::sizegrip .f.grip set notify 0 set wifi 1 set size M grid .f.lf.ok .f.lf.notify .f.lf.wifi -sticky w -padx 4 -pady 4 grid .f.lf.s .f.lf.m -sticky w -padx 4 -pady 4 grid .f.lf.sep - - -sticky ew -pady 6 grid .f.lf.name - - -sticky ew -padx 4 pack .f -fill both -expand 1 pack .f.lf -fill both -expand 1 pack .f.status -side left -pady {8 0} pack .f.grip -side right -anchor se ``` | Widget | Notes | |---|---| | `ttk::button` | `-style Accent.TButton` is a common style for the main action. `invoke` runs `-command`. | | `ttk::checkbutton` | `-style Switch.TCheckbutton` draws a switch, in the modern theme and in the classic theme. A variable that does not exist shows the state `alternate`. | | `ttk::radiobutton` | Buttons with the same `-variable` form a group. | | `ttk::label` | `-image` with `-compound` puts an image beside the text. `-wraplength` breaks the text. | | `ttk::frame`, `ttk::labelframe` | `-padding` sets the inner space. `-labelanchor` places the title. | | `ttk::entry` | The commands of `entry`, with `-placeholder` and validation. See [Entry and spinbox](entry.md). | | `ttk::separator` | `-orient horizontal` or `vertical`. Use `grid -sticky ew` to stretch it. | | `ttk::sizegrip` | A drag resizes the toplevel with `wm geometry`. | ## The range widgets ![A combobox with Medium, a spinbox with 1, a scale at 60, a progress bar at 60 percent, and an indeterminate progress bar](../site/shots/widget-ttk-range-light.png) ```tcl set level 60 ttk::combobox .size -values {Small Medium Large} -state readonly .size current 1 bind .size <> {puts "size: [.size get]"} ttk::spinbox .copies -from 1 -to 10 -width 4 .copies set 1 ttk::scale .volume -from 0 -to 100 -variable level ttk::progressbar .meter -maximum 100 -variable level ttk::progressbar .busy -mode indeterminate after 500 {.busy start} pack .size .copies .volume .meter .busy -fill x -padx 12 -pady 4 ``` | Widget | Notes | |---|---| | `ttk::combobox` | An entry with a list of `-values`. A press on the arrow, or the Down key, opens the list. A readonly combobox opens it on a press anywhere. `-postcommand` runs before the list opens. A choice from the list sends `<>`. `current` gives or sets the index of the text in `-values`, and `set` sets the text. `-placeholder` shows a hint in an empty field. | | `ttk::spinbox` | An entry with up and down buttons. It steps through `-values`, or from `-from` to `-to` by `-increment`, with `-format` and `-wrap`. The Up and Down keys send `<>` and `<>`. | | `ttk::scale` | A slider from `-from` to `-to` (0 to 1.0 by default) with no resolution. `get` gives `-value`, and `set` runs `-command` with the new value. A `-variable` that does not exist stays unset until the value changes. | | `ttk::scrollbar` | The overlay scrollbar of the modern theme, with `set first last`, `get`, `delta`, and `fraction`. `identify` gives `thumb` or `trough`. | | `ttk::progressbar` | `-mode determinate` fills `-value / -maximum` of the track. `-mode indeterminate` moves a short bar. `step ?amount?` adds to the value and wraps at `-maximum`. `start ?interval?` steps it with a timer, and `stop` ends the timer. A `-variable` with text that is not a number sets the state `invalid`. | The list of a combobox is a popover with a round corner and a shadow. It opens below the field, or above it when the window has no room below. The arrow keys move the highlight, Return chooses, and Escape or a press outside closes the list. The list fades in and slides 6 pixels in 150 ms, and it closes the same way. The determinate bar eases to a new value in 200 ms. While `start` runs, the indeterminate bar moves back and forth on the render thread, so a busy script does not stop it. The parts for CSS: `TCombobox::arrow`, `::popdown`, `::item`, and `::item-active`; `TProgressbar::trough` and `::bar`. A `ttk::scale`, a `ttk::spinbox`, and a `ttk::scrollbar` match the rules of `Scale`, `Spinbox`, and `Scrollbar` too, and a `ttk::combobox` the rules of `Entry`. ## How they differ from the classic widgets A `ttk` widget gets its colors, fonts, and reliefs from its style. It has no `-background`, `-foreground`, `-font`, or `-relief`. A script that names one gets `unknown option`, as in `wish`. Change the look with `ttk::style` or CSS. | Option | Widgets | Use | |---|---|---| | `-style` | all | The style name, for example `Accent.TButton`. | | `-class` | all | The class for the option database and for CSS. | | `-padding` | button, checkbutton, radiobutton, label, frame, labelframe | The inner space: one to four distances. | | `-image`, `-compound` | button, label | An image and its place beside the text. | | `-underline` | button, label, labelframe | Stored. It has no effect on the look yet. | ## state and instate A `ttk` widget has a set of state flags: `active`, `disabled`, `focus`, `pressed`, `selected`, `background`, `readonly`, `alternate`, `invalid`, `hover`, and `user1` to `user6`. ```tcl ttk::button .b -text "Save" .b state disabled ;# returns !disabled, the flags to undo it .b instate disabled ;# 1 .b instate !disabled {puts enabled} ;# runs the script only in that state .b state !disabled ``` `-state disabled` and `-state readonly` set the same flags. Each state is a CSS pseudo-class: `TButton:disabled`, `TCheckbutton:checked`, or `:state(user1)`. See [Styling and themes](../styling.md#ttkstyle). # pack, grid, and place ztk has the three geometry managers of Tk, with all their subcommands and options. CSS has no layout properties in ztk: the geometry managers place each widget. **Live:** each example uses them. The [calculator](https://beetlebug.org/ztk/play/index.html?example=calculator) is one `grid`, and the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery) mixes `pack` and `grid`. ![A toolbar with New and Open, a form with Name and Email entries and a New badge in its corner, and the status line Ready at the bottom](../site/shots/widget-geometry-light.png) ```tcl # pack: a toolbar at the top, a status line at the bottom. frame .bar button .bar.new -text New button .bar.open -text Open pack .bar.new .bar.open -side left -padx 4 pack .bar -side top -fill x -pady 4 label .status -text Ready -anchor w pack .status -side bottom -fill x # grid: a form with a column that grows. frame .form label .form.l1 -text Name entry .form.e1 label .form.l2 -text Email entry .form.e2 grid .form.l1 .form.e1 -sticky ew -padx 4 -pady 2 grid .form.l2 .form.e2 -sticky ew -padx 4 -pady 2 grid columnconfigure .form 1 -weight 1 pack .form -fill both -expand 1 -padx 8 # place: a badge in the corner of the form. label .badge -text New place .badge -in .form -relx 1.0 -x -4 -y 4 -anchor ne ``` A comparison tool runs random layouts in ztk and in `wish` 8.6.16. `pack` and `place` gave the same result in each run. `grid` differs by one pixel in a few rare layouts with overlapping spans. A distance with a unit (`1c`) uses 96 / 72 pixels in a point. # Styling and themes A stylesheet in a subset of CSS gives each widget its look. The widget tree is the document. The default theme is `modern`, with a light and a dark scheme. The theme `classic` has the sizes and the colors of Tk on X11. **Live:** the [status board](https://beetlebug.org/ztk/play/index.html?example=dashboard) and the [sign-in form](https://beetlebug.org/ztk/play/index.html?example=signin) each have a stylesheet. The playground shows it next to the script. ## Load a stylesheet ```tcl ztk::style load app.css ;# a file in the folder of the script ztk::style add { Button.big { font-size: 18px; padding: 10px 20px; box-shadow: 0 2px 6px var(--shadow); } Frame.card { background: linear-gradient(135deg, #2563eb, #7c3aed); border-radius: 12px; } } button .go -text "Go" ztk::class .go add big ``` ## Selectors | CSS | Matches | |---|---| | `Button` | The class of the widget (`winfo class`). `TButton` is the `ttk` button. | | `#ok` | The last part of the path: `#ok` matches `.f.ok`. | | `.big` | A style class. `ztk::class path add big` adds one to a classic widget. A `ttk` style `Big.TButton` is the selector `TButton.Big`. | | `A B`, `A > B` | A descendant and a child in the widget tree. | | `:hover`, `:active`, `:focus`, `:disabled`, `:checked`, `:read-only`, `:invalid`, `:indeterminate`, `:placeholder-shown`, `:scrolling` | The states of the widget. | | `:state(user1)`, `:state(!hover)` | Any state flag of Tk, and its negation. | | `::indicator`, `::thumb`, `::trough`, `::slider`, `::tooltip`, `::placeholder` | A part of a widget. Each widget page names its parts. | | `--name` and `var(--name)` | Variables. They inherit down the tree. | | `@media (prefers-color-scheme: dark)` | The dark scheme. | ## Properties `color`, `background` (a color or a `linear-gradient`), `border`, `border-radius`, `border-style` (with `raised`, `sunken`, `groove`, and `ridge`), `padding`, `font-family`, `font-size`, `opacity`, `box-shadow`, `outline`, `min-width`, `min-height`, `caret-color`, `cursor`, `text-align`, `transition`, and `animation`. The geometry managers do the layout, so `display`, `margin`, `flex`, and `grid` are not in the subset. The modern theme sets the variables `--bg`, `--fg`, `--muted`, `--accent`, `--accent-fg`, `--accent-hover`, `--border`, `--field-bg`, `--radius`, and `--shadow`. Set them on `:root` to change the colors of each widget at once. ## The order of the rules From the lowest to the highest: 1. The theme sheet, and its sheet for the platform. 2. The settings of `ttk::style configure` and `ttk::style map`. 3. Your stylesheets (`ztk::style load` and `ztk::style add`). 4. The options that the script sets on a widget, such as `-background red`. Inside one level, the specificity and then the order decide, as in CSS. ## Themes ```tcl ztk::style theme classic ;# or modern ttk::style theme use classic ;# the same for the ttk names ztk::style scheme ;# light or dark ``` | Theme | Look | |---|---| | `modern` | Round corners, an accent color, overlay scrollbars, and a dark scheme. `ttk::style theme use default`, `clam`, and `alt` select it. | | `classic` | The reliefs and the gray of Tk on X11, with square corners. | The [Themed widgets page](widgets/ttk.md) shows one window in both themes. ## ttk::style `ttk::style` works as in `wish`, and each setting of a script becomes a CSS rule. ```tcl ttk::style configure Accent.TButton -foreground white -background #2563eb -padding {12 6} ttk::style map Accent.TButton -background {pressed #1e40af active #1d4ed8} ttk::button .ok -text "Apply" -style Accent.TButton ``` These two commands act as these rules: ```css TButton.Accent { color: white; background-color: #2563eb; padding: 6px 12px; } TButton.Accent:active { background-color: #1e40af; } TButton.Accent:hover { background-color: #1d4ed8; } ``` | Command | What it does in ztk | |---|---| | `configure style ?-option value ...?` | Adds a rule. `-foreground`, `-background`, `-fieldbackground`, `-bordercolor`, `-borderwidth`, `-relief`, `-padding`, `-font`, and `-indicatorcolor` change the look. Other options are stored for `lookup`. | | `map style -option {states value ...}` | Adds one rule for each pair. The first pair that matches wins, as in Tk. | | `lookup style -option ?state? ?default?` | Gives the value, as `wish` gives it. | | `layout style ?spec?` | Gives the layout of `wish`. A new layout is stored and has no effect on the look. | | `element create`, `element names`, `element options` | As in `wish`. A new element has no effect on the look. | | `theme create name ?-parent p? ?-settings script?` | Makes a theme with the look of its parent. | | `theme names`, `theme use ?name?`, `theme settings name script` | List, select, and set up themes: `clam`, `alt`, `default`, `classic`, and yours. | The style `.` is the root: `ttk::style configure . -font {Inter 12}` applies to each `ttk` widget. [Differences from Tk](differences.md#styles-and-themes) has the rules that differ from `wish`. # Animation ztk moves a widget with CSS transitions, CSS keyframes, or the command `ztk::animate`. A render thread draws the frames, so a transition, a switch, or a scrollbar stays smooth while the script is busy. **Live:** hover the buttons and toggle the switches of the [gallery](https://beetlebug.org/ztk/play/index.html?example=gallery). Drag the slider of the scale. ## CSS transitions A change of state moves each property in `transition` from its old value to its new value. ```css Button { transition: background-color 150ms ease, color 150ms ease; } Button:hover { background-color: var(--accent); color: var(--accent-fg); } Checkbutton.switch::indicator { transition: all 320ms spring(260 20 1); } ``` The timing functions are those of CSS (`ease`, `linear`, `ease-in-out`, `cubic-bezier()`, `steps()`), and `spring(stiffness damping mass)`. A spring has its own duration: the time until it rests. ## CSS keyframes ```tcl ztk::style add { @keyframes pulse { from { background-color: #dbeafe; } to { background-color: #2563eb; } } #badge { animation: pulse 800ms ease-in-out infinite alternate; border-radius: 10px; padding: 4px 10px; } } label .badge -text "Live" pack .badge -padx 20 -pady 20 ``` ## ztk::animate `ztk::animate` moves widget options of the types color, distance, and number from their current values to new values. ```tcl label .l -text "Hello" -background #dbeafe pack .l -padx 20 -pady 20 set id [ztk::animate .l -background #2563eb -foreground white -duration 400 -easing ease-out] ``` ``` ztk::animate target ?-option value ...? ?-duration ms? ?-easing name? ?-delay ms? ?-repeat count? ?-command script? ztk::animate cancel|pause|resume id ztk::animate info ?id? ztk::animate reduce ?bool? ``` - The command returns an id such as `anim#1`. `cancel` keeps the shown value. - A new animation of the same option starts from the shown value, so a fast series of changes does not jump. - `-command` runs after the frame that showed the end value. - A canvas item is a target too: `ztk::animate {.c tagOrId} -coords {10 10 90 60} -fill red -duration 300`. ## Reduced motion `ztk::animate reduce 1`, `ZTK_NO_ANIMATION=1`, the setting `prefers-reduced-motion` of a browser, and the setting of the system for less motion (on Windows, the animation effects of the visual effects; on Wayland, `enable-animations` of GNOME or `AnimationDurationFactor` of KDE through the settings portal) show each end state at once. The setting of the system applies until a script calls `ztk::animate reduce` with a value. ## How smooth On the development machine, a hover transition beside 1,000 widgets uses 1.36 ms of CPU time for a frame at the 99th percentile, and 1,000 `ztk::animate` moves at once use 7.20 ms. [Performance](performance.md) has the method. # Debugging `ztk::debug` answers the question "why is this widget like this". It gives the source of each option of a widget and the geometry chain that sets its size and place. Its trace records what ran for each event, and its visual diffs show what an action changed. [Debug a form](debug-a-form.md) has a live form with three bugs to find with these tools. The answers are Tcl dicts, so a script, a test, or an agent can read them. ## The source of an option `ztk::debug sources on` starts the record of option sources. Turn it on before the code that you want to check, for example on the first line of the script. While it is off, a `configure` call keeps no record, and its cost is one test of a flag. ```tcl ztk::debug sources on button .ok -text Save pack .ok proc lock {w} { $w configure -state disabled } lock .ok puts [ztk::debug why .ok -state] ``` The output is one dict: ``` option -state value disabled source configure code {$w configure -state disabled} call {.ok configure -state disabled} file app.tcl line 2 fileline 14 proc lock prev normal count 1 seq 3 stack {{lock .ok}} ``` | Key | What it has | |---|---| | `option`, `value` | The option and the value that `cget` gives. | | `source` | `create`, `configure`, `animate` (a step of `ztk::animate`), `internal` (the widget keeps the option equal to its state), `optiondb` (the new widget took the value of the option database, `option add`), `variable` (the `-text` of a `-textvariable`), `call` (a call set it while the record was off), `style` (`cget` reads the computed style), or `default`. | | `code` | The source text of the command, before substitution. | | `call` | The words of the call with their values. | | `file`, `line` | The value of `info script`, and the line of the command in its own script. For a command in a proc, the line counts from the start of the body of the proc. | | `fileline` | The line of the command in `file`, also for a command in a proc or in the body of an `if` or a loop. `file` is then the file of the command. It is 0 for a command from a string that ztk did not run as a file, such as `eval $text`. The main script and the code of a live snippet get it. | | `proc`, `stack` | The innermost proc, and the words of each proc call, innermost first. A call at the global level has an empty stack. | | `prev` | The value before the call. | | `count`, `seq` | The count of recorded writes of the option, and the order of the last write among all recorded writes. | | `default` | The default value, for the source `default`. | | `style` | For an option that no call set: the CSS declaration that gives the look, with its sheet, its origin, and its line. | | `overrides` | For an option that a call set: the CSS declaration that the option overrides. | | `variable` | The name of the `-textvariable`. | An option with a CSS property is `-background`, `-foreground`, `-borderwidth`, `-relief`, `-font`, `-padx`, `-pady`, `-padding`, `-cursor`, or `-insertbackground`. For a property that inherits, such as `color`, the declaration can be on an ancestor. Then the dict has the key `inherited` with the path of that ancestor. `ztk::debug why .ok` with no option gives a list of these dicts: one for each option that a call set or that the style gives. Add `-all` for each option of the widget. A value from the option database (`option add`, `option readfile`) has the source `optiondb`. ## The geometry chain `ztk::debug geometry path` runs the pending layout, and then gives one dict for the widget and one for each container up to its toplevel. ```tcl frame .f -width 100 -height 40 pack propagate .f 0 pack .f button .f.ok -text "A long label" pack .f.ok puts [lindex [ztk::debug geometry .f.ok] 0] ``` | Key | What it has | |---|---| | `widget`, `class` | The path and the class. | | `req` | The requested width and height in logical pixels. | | `box` | The x, y, width, and height in the container. | | `mapped` | 1 when the widget is mapped. | | `size` | The `-width` and `-height` that a call set. | | `manager`, `info` | The geometry manager and the result of its `info` subcommand. An empty `manager` means that no manager has the widget. | | `propagate` | For a container: 1 when its content sets its requested size. | | `notes` | Each difference between the requested size and the box, and the reason that a widget is not mapped. | ## Traces `ztk::debug trace start` records what happens in the app: each event, the bindings that it runs, the `-command` of a button, each option write, each geometry pass, each widget that gets dirty, each frame, and each change of the focus and the grab. `ztk::debug trace records` gives the records as dicts, oldest first. ```tcl button .save -text Save -command {.status configure -text Saved} label .status -text Ready pack .save .status update ztk::debug trace start .save invoke update foreach r [ztk::debug trace records -kind {command option frame}] { puts $r } ``` Each record starts with the same keys: | Key | What it has | |---|---| | `seq` | The number of the record. Option sources use the same numbers. | | `kind` | The kind of the record. | | `widget` | The widget of the record. | | `cause` | The number of the event whose bindings ran when the record was made, or 0. | | `us` | The time of the clock of the app, in microseconds. | The other keys depend on the kind: | Kind | Keys | |---|---| | `event` | `event` (for example ``), `x`, `y`, `text`. | | `motion` | The same keys, for ``, ``, and ``. This kind is off unless `-kinds` names it. | | `binding` | `tag`, `pattern`, `script`. | | `command` | `script`, `ran` (0 when the command did not run), `why` (for example `the widget is disabled`). | | `option` | `option`, `value`, `prev`, `source`, `code`, `line`, `proc`, as in `ztk::debug why`. | | `dirty` | `flags` (the new flags of `style`, `measure`, `layout`, and `paint`), `by` (the number of the option record that made the widget dirty, or 0). | | `geometry` | `manager`, `req`, `box`, `changed` (each content widget whose box changed: the path, the old box, and the new box). | | `frame` | `frame` (the count of frames), `us` (the time of the frame), `dirty` (the widgets that got dirty since the last frame of the toplevel). | | `focus` | `from`, `to`. | | `grab` | `action` (`set` or `release`), `global`. | The subcommands: | Command | What it does | |---|---| | `ztk::debug trace start ?-kinds list? ?-size n?` | Starts the trace. `-kinds` is a list of kinds, or `all`. The default is each kind except `motion`. `-size` is the count of records that the ring keeps (default 10,000). A new record replaces the oldest one. | | `ztk::debug trace stop` | Stops the trace and keeps the records. | | `ztk::debug trace clear` | Removes the records. | | `ztk::debug trace status` | Gives `on`, `kinds`, `count`, `size`, and `dropped` (the count of records that the ring replaced). | | `ztk::debug trace records ?filter ...?` | Gives the records that pass each filter. | The filters of `records`: | Filter | What it keeps | |---|---| | `-kind list` | The records of these kinds. | | `-widget pattern` | The records of the widgets that match the pattern, with `*` and `?`. | | `-match pattern` | The records whose fields match the pattern, for example `*ButtonRelease*`. | | `-cause n` | The event `n` and each record that its bindings made: the answer to "what ran when I clicked". | | `-since n` | The records after the number `n`. | | `-last n` | The last `n` records that pass the other filters. | This script answers "what ran when I clicked Save": ```tcl set click [lindex [ztk::debug trace records -kind event -widget .save -match *ButtonRelease* -last 1] 0] foreach r [ztk::debug trace records -cause [dict get $click seq]] { puts "[dict get $r kind] [dict get $r widget]" } ``` While the trace is off, each hook tests one mask and makes no record. ## Visual diffs `ztk::debug mark name ?path?` keeps the image of the toplevel of `path` (default `.`) and the state of each widget in it: the class, the box, the map state, and the text of each option. `ztk::debug diff name` makes the same capture again and gives what changed. ```tcl label .msg -text Ready button .go -text Go -command {.msg configure -text Done -foreground red} pack .msg .go update ztk::debug mark before .go invoke update puts [ztk::debug diff before] ``` | Key | What it has | |---|---| | `pixels` | The count of device pixels that changed. | | `box` | The bounding box of the changed pixels in logical pixels: x, y, width, height. | | `size` | The old and the new size of the image, when it changed. | | `added`, `removed` | The widgets that are new, and the widgets that are gone. | | `moved` | Each widget whose box changed: the path, the old box, and the new box. | | `mapped` | Each widget whose map state changed: the path, the old state, and the new state. | | `options` | Each option whose text changed: the path, the option, the old text, and the new text. | | `image` | With `-image`: a PNG of the new image as base64 text. A changed pixel is red, and each other pixel is a pale copy. | The answer has only the keys with a change. The answer `pixels 0` with no other key means that the image and the widgets are the same. `-tolerance n` counts a pixel only when a channel changed by more than `n` (default 0). `ztk::debug marks` gives the names of the marks, and `ztk::debug forget name` removes one. ## Short answers These subcommands give lines of text for a person or an agent. Each answer has at most 24 lines, and a longer answer ends with a line that gives the count of the lines that it left out. | Command | The question that it answers | |---|---| | `ztk::debug explain path ?option?` | "Why is `.f.ok` disabled?" With an option: the value, the call that set it with its line and stack, the value before, and the style. With no option: the box, the geometry notes, and each option that a call set. | | `ztk::debug click path ?button?` | "What ran when I clicked Save?" It clicks the center of the widget through the hit test and gives each event with its bindings, commands, option changes, and dirty widgets, then the geometry passes and the frames. | | `ztk::debug type text ?path?` | The same for text: into the widget with the focus, or into `path` after a click on it. | | `ztk::debug ran ?seq?` | What ran for the last event that ran a binding, or for the event with the number `seq`. It needs the trace. | | `ztk::debug changes name` | "Diff the UI before and after": the answer of `ztk::debug diff` as lines. | | `ztk::debug tree ?path?` | One line for each widget: the path, the class, the box, and the map state. | `click` and `type` start the trace when it is off, and stop it again after. For example, `ztk --headless app.tcl` with this `app.tcl`: ```tcl ztk::debug sources on button .save -text Save -command save label .status -text Ready pack .save .status proc save {} { .status configure -text Saved; lock .save } proc lock {w} { $w configure -state disabled } puts [ztk::debug click .save] puts [ztk::debug explain .save -state] ``` The second answer is: ``` .save -state is "disabled": set by $w configure -state disabled at line 1 of proc lock in app.tcl. Before: "normal". Writes: 1. Stack: lock .save < save A click on .save runs no -command while it is disabled. ``` ## MCP tools `ztk --mcp app.tcl` runs the script on the headless backend and then serves the Model Context Protocol on stdin and stdout: one JSON-RPC message on each line. The output of the script goes to stderr. The app runs only inside the calls of the tools, so two runs with the same calls give the same answers. The trace is on from the start. | Tool | Arguments | What it gives | |---|---|---| | `ui_tree` | `path` | The answer of `ztk::debug tree`. | | `ui_explain` | `path`, `option` | The answer of `ztk::debug explain`. | | `ui_geometry` | `path` | The geometry chain, one line for each level. | | `ui_click` | `path`, `button` | The answer of `ztk::debug click`. | | `ui_type` | `text`, `path` | The answer of `ztk::debug type`. | | `ui_ran` | `seq` | The answer of `ztk::debug ran`. | | `ui_trace` | `kind`, `widget`, `last` | The trace records, one line each (default: the last 20). | | `ui_mark` | `name` | Takes a mark for `ui_diff`. | | `ui_diff` | `name`, `image` | The answer of `ztk::debug changes`. With `image`, also the PNG with the changed pixels in red. | | `ui_snapshot` | `path` | A PNG image of the widget. | | `tcl_eval` | `script` | The result of the script at the global level, after an `update`. | An MCP client that starts a server from a command line gets the command `ztk` and the arguments `--mcp /path/to/app.tcl`. ## Cost A script with 200,000 calls of `.b configure -text $i -state normal` ran 1,161,719,315 instructions before `ztk::debug` existed, 1,165,918,947 with the record off (0.36 % more, 21 instructions for each call), and 2,211,793,540 with the record on. The command was `perf stat -e instructions:u -r 3 ztk --headless --allow clock bench/debug-configure.tcl` on a ReleaseFast build, on 2026-11-26, on an Intel Core i7-6700K with Linux. The difference in time with the record off was smaller than the spread between runs. ## Limits - The line of a command in a proc counts from the body of the proc. The file of the proc and the line in that file need the debug interface of ztcl. - The record keeps only the last write of each option. The trace has each write. # Debug a form This page has a small sign-up form with three bugs. The form runs live in the page. Find each bug with the tools of [Debugging](debugging.md), fix the code in the editor, and see the window change. The bar of the snippet has two tools for this page: - **Console** opens a line under the window. A Tcl command in the line runs in the window, and the answer shows above the line. Use the up arrow for the last commands. - **Inspect** shows the widget under the pointer. A click on a widget opens a panel with its options and the source of each value, its bindings, its geometry chain, its code, its trace, and the probes and breakpoints of its procs. ```tcl ztk::debug sources on # A sign-up form with three bugs. set name "" set email "" frame .f -padx 12 -pady 8 label .f.l1 -text Name entry .f.name -textvariable name label .f.l2 -text Email entry .f.email -textvariable mail label .f.hint -text "Use your work address" -foreground #6b7180 button .f.save -text "Sign up" -command save -state disabled label .f.status -text "Fill in both fields" grid .f.l1 .f.name -sticky w -pady 2 grid .f.l2 .f.email -sticky w -pady 2 grid .f.save -column 1 -sticky w -pady 6 grid .f.status -columnspan 2 -sticky w pack .f -fill both proc check {args} { set ok [expr {$::name ne "" && [string match *@* $::email]}] .f.save configure -state [expr {$ok ? "normal" : "disabled"}] } trace add variable name write check trace add variable mail write check proc save {} { .f.status configure -text "Welcome, $::name" } # A click on the window clears the status. bind . {.f.status configure -text "Fill in both fields"} ``` The first line, `ztk::debug sources on`, starts the record of option sources. Keep it at the top, so the record has each call of the code. ## Bug 1: Sign up stays disabled Type a name and an email address in the window. The button stays disabled. To type with the console, run these two commands: ```tcl ztk::debug type Ada .f.name ztk::debug type ada@example.com .f.email ``` Each answer lists the events, the bindings that ran, and the option writes. Each key gives the line `option .f.save -state: "disabled" again (line 3 of proc check)`. So `check` runs and keeps the button disabled. Ask why: ```tcl ztk::debug explain .f.save -state ``` ``` .f.save -state is "disabled": set by .f.save configure -state [expr {$ok ? "normal" : "disabled"}] at line 20, in proc check. Before: "disabled". Writes: 19. Stack: check ::mail {} write A click on .f.save runs no -command while it is disabled. ``` The stack shows the words of the call of `check`: a write trace of `::mail` calls it. The proc reads `::email`. Ask where `mail` comes from: ```tcl ztk::debug explain .f.email -textvariable ``` ``` .f.email -textvariable is "mail": set by entry .f.email -textvariable mail at line 9. Before: "". Writes: 1. ``` Line 9 of the code gives the entry the variable `mail`, so `::email` stays empty. With Inspect, the same answer is in the Options tab of `.f.save`: the source of `-state` is `configure line 20 in check`. The Probe tab of `.f.save` has the lines of `check`: a probe on line 3 records `ok` and the other locals at each key. The fix: change `mail` to `email` on line 9 and in the `trace add variable mail write check` line. Type in the window again, and the button gets enabled. ## Bug 2: The hint does not show The code makes the label `.f.hint`, but the window has no hint. A widget that is not mapped has no box to point at, so ask with the console: ```tcl ztk::debug explain .f.hint ``` ``` .f.hint Label, box 0,0 1x1, no manager, not mapped not mapped: no geometry manager (pack, grid, or place) -foreground "#6b7180": create at line 10 -text "Use your work address": create at line 10 ``` No geometry manager has the label. `ztk::debug geometry .f.hint` gives the same note, and `ztk::debug tree .f` gives each widget with its box and its map state. The fix: add this line after the `grid .f.l2 .f.email` line: ```tcl grid .f.hint -column 1 -sticky w ``` ## Bug 3: Sign up shows no welcome After the fix of bug 1, fill in the form and click Sign up. The status stays "Fill in both fields". Ask what ran for the click: ```tcl ztk::debug click .f.save ``` The answer has the events of the click. The part for the release is: ``` #130 on .f.save at 36,15 binding Button : ::ztk::priv::button up %W command .f.save: save option .f.status -text: "Fill in both fields" -> "Welcome, Ada" (line 2 of proc save) dirty .f.status: style measure layout binding . : .f.status configure -text "Fill in both fields" option .f.status -text: "Welcome, Ada" -> "Fill in both fields" (line 1) ``` The numbers of the records depend on the events before the click. The command `save` writes the welcome. Then the binding of the tag `.` writes the old text back. The tag `.` is the toplevel, and each widget of the window has it in its bind tags: ```tcl bindtags .f.save ``` ``` .f.save Button . all ``` So the binding on `.` runs for a click on each widget, after the binding of the class. The Bindings tab of Inspect shows the same list for `.f.save`, with the script of each tag. The fix: put the binding on the frame, so that only a click on the frame clears the status: ```tcl bind .f {.f.status configure -text "Fill in both fields"} ``` ## Check each fix A visual diff shows what an action changed. Take a mark, click, and ask for the changes: ```tcl ztk::debug mark before ztk::debug click .f.save ztk::debug changes before ``` Before the fix of bug 3, the changes have no line for `.f.status`, because the text ends where it started. After the fix, the changes have this line: ``` .f.status -text: "Fill in both fields" -> "Welcome, Ada" ``` The first line of the changes gives the count of the pixels that changed and their box. `ztk::debug diff before -image` also gives a PNG of the window with the changed pixels in red. ## For an agent An agent uses the same answers with `ztk --mcp`. Save the code as `form.tcl`, and start the server: ```sh ztk --mcp form.tcl ``` Then each line of stdin is one JSON-RPC message. These calls find bug 3: ```json {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ui_type","arguments":{"path":".f.name","text":"Ada"}}} {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ui_type","arguments":{"path":".f.email","text":"ada@example.com"}}} {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ui_click","arguments":{"path":".f.save"}}} ``` The text of each answer is the text of the console. For a check in CI, a script runs the same commands in `ztk --headless`: ```tcl source form.tcl ztk::debug type Ada .f.name ztk::debug type ada@example.com .f.email ztk::debug click .f.save puts [.f.status cget -text] exit ``` With the three fixes, it prints `Welcome, Ada`. `tests/debug-form.sh` runs the code of this page with and without the fixes. # On the web ztk runs the same Tk scripts in a browser. Each example on the [landing page](https://beetlebug.org/ztk/) runs live, and the [playground](https://beetlebug.org/ztk/play/index.html) lets you edit a script. `zig build wasm` builds ztk for the browser into `zig-out/web`. The build has `ztk.wasm`, the page module `ztk.js`, the playground `index.html`, and the examples. `ztk.wasm` has the interpreter (ztcl), the widgets, the layout, the style sheets, the Inter font, and the CPU renderer. `ztk.js` gives the module the clock, the size, the scale, the color scheme, and the input, and draws each frame with WebGPU (`webgpu.js`), WebGL 2, or the CPU renderer. ## Install from npm The package [`@beetlebug/ztk`](https://www.npmjs.com/package/@beetlebug/ztk) has `ztk.wasm`, `ztk.js`, and the TypeScript types. It works with a bundler, in a plain page from a CDN, and with Vite. ```sh npm install @beetlebug/ztk ``` ```js import * as ztk from "@beetlebug/ztk"; const app = await ztk.mount(document.getElementById("app"), { script: "button .b -text Hello -command {set clicked 1}; pack .b -padx 8 -pady 8", theme: "auto", size: "fill", }); app.eval(".b configure -text Bye"); app.destroy(); ``` With no build step, import `https://cdn.jsdelivr.net/npm/@beetlebug/ztk@VERSION/ztk.js`. The module loads `ztk.wasm` from its own folder. With the Vite dev server, add `optimizeDeps: { exclude: ["@beetlebug/ztk"] }` to `vite.config.js`, so that `ztk.wasm` stays next to `ztk.js`. ## mount `mount(el, options)` adds a canvas to `el` (or uses `el` when it is a canvas), runs the script, draws the first frame, and returns the app. A script error destroys the app and rejects with the error text. | Option | Use | |---|---| | `script` | Tcl text with Tk commands. | | `files` | Files by name for `ztk::style load`. | | `theme` | `"auto"` (the color scheme of the page), `"light"`, or `"dark"`. | | `size` | `"auto"`: the size of the element at the start, and then the size that the toplevel computes. `"fill"`: the window follows the size of the element through a `ResizeObserver`. `[width, height]`: a fixed logical size. | | `renderer` | `"auto"`, `"webgl2"`, `"cpu"`, or `"webgpu"`. `"auto"` selects WebGPU when the browser gives an adapter, else WebGL 2, else the CPU renderer. With `"auto"`, a blank first WebGPU frame, a GPU error, or a lost device with no new device makes the app render with WebGL 2 on a new canvas in the place of the old one. Read `app.canvas` again after the first frame. A forced renderer that the browser does not have rejects. | | `scale` | The device pixels in one logical pixel. The default is `devicePixelRatio`. | | `module`, `wasm` | A compiled module, or the URL of `ztk.wasm`. | | `log` | Gets the text of `puts` and the error messages. | The app has `eval(script)`, `addFile(name, text)`, `resize(width, height)`, `setTheme(theme)`, `destroy()`, `frame(ms)`, `canvas`, `renderer`, and `tree` (the hidden elements with ARIA roles). `destroy` stops the frame loop, removes the event listeners and the elements of the app, and frees the renderer. `start(canvas, options)` is the API under `mount`. The playground and the landing page use it. ## HiDPI and the color scheme The backing store of the canvas is the scene in device pixels, and the CSS size of the canvas is the scene in CSS pixels. A change of `devicePixelRatio` gives the module a new scale, and the next frame is sharp at that scale. With `theme: "auto"`, a change of `prefers-color-scheme` changes the scheme of the app. A change of `prefers-reduced-motion` turns the animations off or on. ## The renderers | Renderer | How it draws | |---|---| | `webgpu` | WGSL shaders with the formulas of the CPU renderer. The canvas is `display-p3` on a wide-gamut screen. After a device loss, the renderer makes its pipeline again. | | `webgl2` | One instanced draw of the quads of the scene. The shaders have the formulas of the CPU renderer. | | `cpu` | `ztk.wasm` draws each frame to an RGBA image with `src/render/cpu.zig` (`ztk_cpu`, `ztk_image`), and a 2D context shows the image. | `tests/web.sh` compares the WebGPU, WebGL 2, and 2D canvas images with the CPU image of the same script. ## The size of the build `ztk.wasm` builds in ReleaseFast: 3.0 MB, or 1.0 MB with `gzip -9`. A ReleaseSmall build is 2.2 MB, or 0.82 MB with gzip. In Node.js, the median time of a frame of the gallery at scale 2 was 5.1 ms with ReleaseFast and 6.6 ms with ReleaseSmall. The build stays in ReleaseFast for the frame time. ## Build it yourself ```sh zig build wasm python3 -m http.server --bind 127.0.0.1 --directory zig-out/web 8000 ``` Then open `http://127.0.0.1:8000/index.html`. # On Linux ztk opens windows on Linux with its own client of the Wayland protocol, and with its own X11 client on a desktop with no Wayland compositor. Neither one links a C library, so the static Linux programs of a release open a window too. [Install](install.md#build-from-source) has the build. ## The backends | Session | Backend | Renderer | |---|---|---| | Wayland (`WAYLAND_DISPLAY` is set) | The Wayland client of ztk (`src/platform/wl/`), with its own reader of the XKB key map | Vulkan into dma-bufs when the GPU and the compositor share them (`zwp_linux_dmabuf_v1` version 3, linear XBGR8888), else the CPU renderer into shared memory | | X11 (`DISPLAY` is set, no `WAYLAND_DISPLAY`) | The X11 client of ztk (`src/platform/x11.zig`) | The CPU renderer with `PutImage` | | No display | `ztk --headless`, or `ZTK_HEADLESS=1` for a bundled app | The CPU renderer, with no window | With the CPU renderer on Wayland, ztk writes the cause to stderr once. `ZTK_RENDERER=cpu` or `--cpu` selects the CPU renderer. `ZTK_WAYLAND_DEBUG=1` prints each Wayland event. ## What works on Wayland - The pointer shapes (`cursor-shape-v1`), the clipboard (`wl_data_device`), and the text of an input method (`text-input-v3`). - Drops of files and text from other apps, and drags out of a window: [ztk::dnd](commands/dnd.md). - Tray icons as StatusNotifierItems on the session bus: [ztk::tray](commands/tray.md). The item has no D-Bus menu yet, so a script posts its own menu. - The file dialogs through the `FileChooser` portal, when the session bus has `org.freedesktop.portal.Desktop`. A desktop with no portal gets the dialogs that ztk renders. - `wm attributes -fullscreen`. Wayland has no request for topmost, so ztk keeps the value of `-topmost` and sends nothing. - Less motion from the portal settings of GNOME and KDE, as [Animation](animation.md#reduced-motion) describes. - `wm iconphoto` with `xdg-toplevel-icon-v1`. ## What works on X11 The X11 client is a first version: one window, the keys with autorepeat, the buttons and the wheel, focus, resize, the close button, the title, the minimum size, and `wm iconphoto` (`_NET_WM_ICON`). It has no popups (ztk renders menus in the window), no clipboard, no input method, and no scale from `Xft.dpi` yet. ## Make an app `ztk bundle -o notes --desktop --name "My Notes" --icon notes.png notes.tcl` writes one program with the scripts inside it, a desktop entry, and an icon. [Install](install.md) has the options of `ztk bundle`. ## Not on Linux yet `ztk::taskbar`, `ztk::recent`, and `ztk::hotkey` give an error on Linux: [the platform table](commands/taskbar.md#platforms). `ztk::has` tells a script what this program has ([ztk::has](commands/tray.md#platform-features)). # On Windows ztk has a native backend for Windows 10 and 11. It uses Win32 for the windows and the input, and Direct3D 12 for the drawing, with no layer between ztk and Windows. ## Build and run Install [Zig 0.17.0](https://ziglang.org/download/). The build needs no other tool: the shaders compile at run time with the shader compiler that Windows has. ```sh git clone https://github.com/beetlebugorg/ztk cd ztk zig build -Doptimize=ReleaseFast # makes zig-out\bin\ztk.exe zig-out\bin\ztk.exe examples\demo.tcl # opens a window ``` `ztk --headless` works as on the other systems, with no window. The variable `ZTK_RENDERER` picks the output of the window: | Value | Output | |---|---| | (not set) | Direct3D 12, and the CPU renderer when the machine has no Direct3D 12 device | | `d3d12` | Direct3D 12 only. The program stops when no device exists. | | `warp` | Direct3D 12 on WARP, the software rasterizer of Windows | | `cpu` | The CPU renderer, with `SetDIBitsToDevice` | ## What works - Windows: a window for each toplevel, with its title and size, the close button, and the focus. - Scale: each window has the scale of its monitor (per-monitor DPI), and the scale changes when the window moves to another monitor. - Window icon: `wm iconphoto .w $photo` gives the window its small icon (the title bar and Alt+Tab) and its big icon (the taskbar), each one from the photo nearest to the size of the system at the DPI of the window. With `-default` the photos go to each toplevel made after the call too. Several photos of different sizes give the sharpest icons. - Drawing: Direct3D 12 on the first hardware GPU, then WARP. In the tests, each test scene equals the image of the CPU renderer within 2 levels in a channel. - Text: DirectWrite with the fonts of Windows. The default font is Segoe UI Variable with the optical size of each text size (Segoe UI on Windows 10), `monospace` is Cascadia Mono, and the glyphs have the grayscale antialiasing of Windows 11 apps. - Look: the controls have the Fluent look of Windows 11 from the theme resources of WinUI 3 (shapes, strokes, fills, sizes, and the accent of the system), in light and dark. See `src/themes/fluent-windows.css`. - Keys: the keysyms of Tk, the text of each key, and the modifiers Shift, Control, Alt, and the Windows key. Alt+F4 closes the window. - Pointer: motion, the buttons 1, 2, and 3, the two side buttons as 8 and 9, the wheel in both directions, and the cursor of each widget (`-cursor` and the CSS `cursor`). - Input methods: the Text Services Framework. The text of an input method goes into an entry or a spinbox. - Clipboard: `clipboard` and the copy and paste of an entry use the clipboard of Windows, as Unicode text. - Taskbar: `ztk::taskbar progress` shows a value, a paused or failed value, or a progress with no value on the taskbar button of `.`. `ztk::taskbar badge count` shows the count on a red disc over the icon, and `ztk::taskbar attention` flashes the button. - Recent documents: `ztk::recent add path` puts a file in the recent items of Windows and in the jump list of the app, when the app opens files of that type. `ztk::recent clear` empties the jump list of the app. `add` needs the real paths of the host, the default of the `ztk` program. - Global shortcuts: `ztk::hotkey add script` runs the script when the keys go down in any app, with `RegisterHotKey`. It needs `--allow hotkey`, and a shortcut that another app has is an error. - Drops from other apps: `tkdnd::drop_target register .w {DND_Files DND_Text}` lets Explorer and other apps drop files or text on `.w`, through OLE. `<>` gets the data in `%D`: a list of the paths, or the text. `<>`, `<>`, and `<>` follow the drag. A drag out: `ztk::dnd drag .w -files [list $path]` (or `-text`) from a `` binding runs the drag of Windows, and gives `copy`, `move` (with `-move 1`), or `none`. - Dark mode: with no `--dark`, ztk follows the dark mode of Windows, also when it changes while the program runs. The title bar and the frame of each window follow the scheme of the app. - Menus: the `-menu` of a toplevel is a menu bar of Windows, and `tk_popup` shows a menu of Windows. Alt and F10 open the bar. - Tray: `ztk::tray` shows an icon in the notification area, with its tooltip, its clicks, and its menu. - File dialogs: `tk_getOpenFile`, `tk_getSaveFile`, and `tk_chooseDirectory` show the dialogs of Windows, with the options of Tk. They need the file capability of ztcl, which the `ztk` program turns on by default and a program that embeds ztk grants. ## Limits - The text is shaped by DirectWrite on one font: a character that the font lacks shows as its missing glyph, because font fallback is not done yet, and right-to-left text keeps the order of the characters. The glyph images do not have the contrast and gamma of the system yet. - No input method has typed into ztk on a real desktop yet. The tests drive the text store of ztk the way an input method does. - The entry does not show the text that an input method composes. The input method shows its list of choices next to the entry. - The clipboard code has not run in a test with success, because the test machines gave the tests no clipboard access. - The frames come at 60 each second, also on a monitor with a faster refresh. - While a window moves or changes size, it shows its last frame until the move ends. - The menus of Windows have the light look, also in dark mode. - Notifications are not done yet. - The accent color of Windows is not in the themes yet. The design and the plan are in [docs/dev/windows.md](https://github.com/beetlebugorg/ztk/blob/main/docs/dev/windows.md). # On macOS ztk has a native backend for macOS 13 and later. It uses AppKit for the windows, the input, and the menus, and Metal for the drawing, with no layer between ztk and macOS. ## Build and run Install [Zig 0.16.0](https://ziglang.org/download/) and the Xcode command line tools (`xcode-select --install`). ```sh git clone https://github.com/beetlebugorg/ztk cd ztk zig build -Doptimize=ReleaseFast # makes zig-out/bin/ztk zig-out/bin/ztk examples/demo.tcl # opens a window ``` `ztk --headless` works as on the other systems, with no window. ## Make an app `ztk bundle` makes a macOS app, a folder `Name.app`, from a main script and its files: ```sh ztk bundle -o Notes.app --icon notes.png --id org.example.notes notes.tcl lib/ images/ open Notes.app ``` The app has a copy of the ztk program, the scripts and the files in `Contents/Resources/app`, an icon set made from the PNG, and an `Info.plist`. Each file keeps its path relative to the main script, as for [an app in one file](install.md#an-app-in-one-file). The app runs its main script with the folder `app` as the root of the file commands. Each word of the command line of the app is an argument of the script, so a flag cannot add a capability. `ZTK_HEADLESS=1` in the environment runs the app headless, for example `ZTK_HEADLESS=1 Notes.app/Contents/MacOS/Notes`. | Option | Meaning | |---|---| | `-o Name.app` | The app to write. The name of the app comes from it. | | `--name NAME` | Another name for the app. | | `--id ID` | The bundle identifier, such as `org.example.notes`. The default is `org.ztk.` and the name. | | `--version V` | The version. The default is 1.0. | | `--icon FILE.png` | The icon: a square 8-bit RGBA PNG, 1,024 pixels or less. | | `--allow CAPS` | The capabilities of the app, as for `ztk --allow`. The default is `file,channels`. | | `--menu-bar-only` | No Dock icon and no menu bar (`LSUIElement`), for an app that lives in a tray icon. | | `--target T` | `aarch64-macos` or `x86_64-macos`: the macOS ztk program to copy is `lib/ztk/runtime/T/ztk` next to the folder of `ztk`, or `--runner`. | | `--runner FILE` | The macOS ztk program to copy. The default is the program that runs the command. | | `--no-sign` | Leave the app unsigned. The default is an ad hoc signature with the entitlement `com.apple.security.cs.allow-jit`. | A bundle can come from Linux or Windows too: give `--target aarch64-macos` or a macOS ztk with `--runner`, for example `ztk bundle -o Notes.app --target aarch64-macos notes.tcl`. Windows has no mode bits for files, so an app from Windows needs `chmod +x Name.app/Contents/MacOS/Name` on the Mac. `ztk bundle` signs the app with an ad hoc signature: on macOS with `codesign`, and on Linux and Windows with its own signer, which writes `Contents/_CodeSignature/CodeResources` and the signature of the program. Run the app on the Mac that made it, or sign it as below before you give it to others. ## Sign and notarize an app An app for other people needs a Developer ID signature and a notarization from Apple, or macOS refuses to open it. Each step needs an Apple Developer account. 1. Sign the app with your Developer ID and the hardened runtime: ```sh codesign --force --options runtime --timestamp \ --sign "Developer ID Application: Your Name (TEAMID)" Notes.app ``` A ztk program that runs scripts with the JIT of ztcl needs the entitlement `com.apple.security.cs.allow-jit` as well: give a plist with it to `--entitlements`. 2. Send a zip of the app to Apple, wait for the answer, and staple the ticket to the app: ```sh ditto -c -k --keepParent Notes.app Notes.zip xcrun notarytool submit Notes.zip --keychain-profile notary --wait xcrun stapler staple Notes.app ``` `xcrun notarytool store-credentials notary` saves the profile one time. ## Window state `wm attributes .w -fullscreen 1` takes the window to the full screen of macOS (a space of its own, with the animation of the system), and `-fullscreen 0` brings it back. `-topmost 1` keeps it above the windows of other apps, at the level of floating panels. `ztk::animate` reads Reduce motion of the Accessibility settings at the start and again when it changes, and shows each end state at once while it is on. ## Drops from other apps A window that takes drops (`ztk::dnd`) gets the files of Finder and the text of other apps: the view registers for file URLs and plain text, as the window accepts them, and each phase of the drag (enter, over, leave, drop) is a `drop` event. The files are host paths. A drag that has no kind that the window takes shows no drop, and the app finds the widget at the point. A drag out of a window is `ztk::dnd drag`, below. ## Drags to other apps `ztk::dnd drag` drags files or text out of a window to other apps, from a binding of ``: an `NSDraggingSession` of the window, with the icon of each file, and it gives `copy`, `move` (with `-move 1`), or `none` when the drag ends. ## Direct APIs of macOS The commands of `ztk::mac::*` exist on each platform and give the error `ZTK MAC UNAVAILABLE` away from macOS. `ztk::has mac` gives 1 where they work. ```tcl menu .dock -tearoff 0 .dock add command -label "New Window" -command newWindow ztk::mac::dockmenu .dock ;# the menu of the Dock icon; no menu name removes it ztk::mac::tabbing . -mode preferred -group documents ``` `-mode` is `automatic` (the setting of the system), `preferred` (new windows open as tabs), or `disallowed` (no tab bar). Windows of one `-group` join one tab bar. A file dialog with `-parent` shows as a sheet of its window, and so does `tk_messageBox` (an `NSAlert` with the buttons of Tk, the default button on the right for Return). `tk_chooseColor` opens the color panel of macOS and gives its color when the panel closes; the panel has no Cancel, so the answer is the color at the close. The application menu has the Services menu. The design and the plan are in [docs/dev/macos.md](https://github.com/beetlebugorg/ztk/blob/main/docs/dev/macos.md). # Embed in Zig ztk is a Zig package. Your program makes a [ztcl](https://beetlebug.org/ztcl/) interpreter, a backend, and an `App`, and then runs a Tk script. To embed ztk in a web page, see [On the web](web.md). > [!WARNING] > The Zig API is the API of the `ztk` program, and it can change in any release. ## Add the package ```sh zig fetch --save git+https://github.com/beetlebugorg/ztk ``` ```zig // build.zig const dep = b.dependency("ztk", .{ .target = target, .optimize = optimize }); exe.root_module.addImport("ztk", dep.module("ztk")); exe.root_module.addImport("ztcl", dep.builder.dependency("ztcl", .{ .target = target, .optimize = optimize, }).module("ztcl")); ``` The options `.backends = "headless"` and `.vulkan = false` give a build with no system library. ## Run a script ```zig const std = @import("std"); const ztcl = @import("ztcl"); const ztk = @import("ztk"); pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var it: ztcl.Interp = undefined; try it.init(gpa); defer it.deinit(); const head = try ztk.headless.Headless.init(gpa); defer head.deinit(); const app = try ztk.App.init(gpa, &it, .{ .platform = head.platform() }); defer app.deinit(); app.max_frames = 1; try app.runScript( \\ttk::button .b -text "Hello from Zig" -command {puts clicked} \\pack .b -padx 20 -pady 20 ); try app.run(); } ``` `app.run()` runs the event loop until the window closes or `max_frames` frames are drawn. Add native commands to the interpreter with `it.register` before the script runs, and set `it.output` to get the text of `puts`. ## App options | Option | Use | |---|---| | `platform` | The backend: `ztk.headless.Headless`, `ztk.wayland.Wayland`, or `ztk.direct.Direct`. | | `dark` | True for the dark scheme. | | `style_root`, `io` | The folder that `ztk::style load` reads. With no folder, the command gives an error. | | `animations` | False shows each end state at once. | | `render_mode` | `.threaded` draws on a render thread. The default draws on the thread of the script. | | `on_exit` | What the command `exit` calls. | The ztk library turns on no capability of ztcl, so a script has no file or network access unless your program gives it. [`src/main.zig`](../src/main.zig) is a complete program with each backend. # The ztk:: commands ztk has the commands of Tk, and the commands below in the namespace `ztk::`. Each one has its reference here or in the guide of its area. | Command | What it does | Reference | |---|---|---| | `ztk::animate` | Animates the options of a widget, with easing. | [Animation](../animation.md#ztkanimate) | | `ztk::style`, `ztk::class` | Loads a stylesheet, and sets the style classes of a widget. | [Styling and themes](../styling.md) | | `ztk::tooltip` | Shows a text when the pointer rests on a widget. | [Frames, labels, and buttons](../widgets/basic.md) | | `ztk::terminal` | A terminal widget on libghostty-vt. | [Terminal](../widgets/terminal.md) | | `ztk::debug` | Gives the source of an option, the geometry chain, traces, and visual diffs. | [Debugging](../debugging.md) | | `ztk::tree`, `ztk::snapshot`, `ztk::inject` | Read the widget tree, render the window to an image, and send input, for tests and agents. | [For agents](../agents.md) | | `ztk::limit`, `ztk::clock` | Run one script with lower limits, and read or set the animation clock. | [ztk::limit](limit.md) | | `ztk::dnd`, `tkdnd::drop_target` | Drags to other apps and drops from them. | [ztk::dnd](dnd.md) | | `ztk::tray`, `ztk::has` | A tray icon, and a test for each platform feature. | [ztk::tray](tray.md) | | `ztk::taskbar`, `ztk::recent`, `ztk::hotkey` | The taskbar or Dock button, the recent documents, and global shortcuts. | [ztk::taskbar](taskbar.md) | | `ztk::win::backdrop`, `ztk::win::jumplist`, `ztk::win::thumbbar` | APIs of Windows. | [ztk::win](win.md) | | `ztk::mac::dockmenu`, `ztk::mac::tabbing` | The menu of the Dock icon, and the window tabs of macOS. | [On macOS](../macos.md#direct-apis-of-macos) | # ztk::dnd and tkdnd::drop_target A widget takes drops of files and text from other apps with `tkdnd::drop_target`, the names of the `tkdnd` package of Tk. `ztk::dnd drag` drags files or text out of a window to other apps. ## Synopsis ```tcl tkdnd::drop_target register window ?types? tkdnd::drop_target unregister window ztk::dnd drag window ?-files list? ?-text string? ?-move bool? ``` ## Drops on a widget `register` puts `window` on the list of drop targets. `types` is a list of `DND_Files`, `DND_Text`, or `*` (both). The default is `*`. `unregister` takes the widget off the list. The window of a toplevel accepts the union of the types of its targets. A drop goes to the widget under the pointer, or to the nearest parent on the list that accepts the type. The widget gets these virtual events: | Event | When | |---|---| | `<>` | The drag comes over the target. | | `<>` | The drag moves over the target. | | `<>` | The drag goes off the target, or the user cancels it. | | `<>` or `<>` | The user drops data of that type. | | `<>` | After the typed event of the drop. | In a binding, `%D` and `%d` give the data of the drop. The name of the typed event gives the type. The data of files is a list of full host paths, with `/` between the parts on each platform. The data of text is the text. ```tcl label .drop -text "Drop files here" -width 30 -height 6 -relief groove pack .drop -padx 20 -pady 20 tkdnd::drop_target register .drop DND_Files bind .drop <> {.drop configure -text "[llength %D] files"} ``` ## Drags out of a window `ztk::dnd drag` starts a drag from a binding of ``. It runs in the modal loop of the system until the user drops or cancels. It gives the action of the target: `copy`, `move`, or `none`. | Option | Value | Default | |---|---|---| | `-files list` | Full host paths of files to drag. | none | | `-text string` | Text to drag. | none | | `-move bool` | 1 offers a move to the target as well as a copy. | 0 | ```tcl bind .file { if {[ztk::dnd drag .file -files [list $path] -move 1] eq "move"} { file delete $path } } ``` ## Platforms | Platform | Drops | Drags | |---|---|---| | Windows | OLE drop targets | OLE drag source | | macOS | File URLs and plain text of the view | `NSDraggingSession`, with the icon of each file | | Linux, Wayland | The data device of the compositor | The data device of the compositor | | Linux, X11 and the web | No | No | ## Errors - `bad window path name "W"`: no widget has the name. - `bad type "T"`: a type other than `DND_Files`, `DND_Text`, or `*`. - `ZTK DND UNAVAILABLE` (the `errorCode`): `ztk::dnd drag` on a backend with no drags. The guides [On Windows](../windows.md) and [On macOS](../macos.md#drops-from-other-apps) give the details of each system. # ztk::tray and ztk::has `ztk::tray` shows an icon in the tray of the system, with a tooltip, a menu, and a command. `ztk::has` tells a script if the program has a platform feature. ## Synopsis ```tcl ztk::tray create ?-option value ...? ztk::tray configure name ?-option value ...? ztk::tray destroy name ztk::tray names ztk::has feature ``` ## Tray icons `create` makes a tray icon and gives its name, such as `tray1`. `configure` changes the options of the icon. `destroy` removes it. `names` gives the names of the icons. | Option | Value | |---|---| | `-image photo` | A photo image for the icon. A later change of the photo shows at the next `configure`. | | `-tooltip text` | The text that the system shows when the pointer stays on the icon. | | `-menu menu` | A menu widget. The system shows it as a native menu. | | `-command script` | Runs at an action of the user. `%a` in the script is the action: `click`, `double`, or `menu`. | | `-template bool` | macOS: 1 shows the image as a template image, in the colors of the menu bar. | ```tcl image create photo dot -width 16 -height 16 dot put #2c7be5 -to 2 2 14 14 menu .traymenu -tearoff 0 .traymenu add command -label Quit -command exit set t [ztk::tray create -image dot -tooltip "Backup" -menu .traymenu \ -command {if {"%a" eq "double"} {wm deiconify .}}] ``` The tray is on Windows (the notification area), macOS (the menu bar), and Linux on Wayland (a StatusNotifierItem on the session bus, for a panel that hosts these items). On Linux the item has no D-Bus menu yet: `-menu` has no effect there, so post the menu from `-command` when `%a` is `menu`. ## Platform features `ztk::has feature` gives 1 when the program has the feature on this platform, and 0 when it does not. | Feature | 1 when | |---|---| | `tray` | `ztk::tray create` can show an icon. | | `taskbar` | [`ztk::taskbar`](taskbar.md) reaches the taskbar or Dock button of the app. | | `recent` | [`ztk::recent`](taskbar.md#ztkrecent) reaches the recent documents of the system. | | `native-menus` | Menus show as menus of the system. | | `mac` | The [`ztk::mac::` commands](../macos.md#direct-apis-of-macos) work. | | `win` | The [`ztk::win::` commands](win.md) work. | ## Errors - `this platform has no tray`, or `the system has no tray`: `create` on a backend or a desktop with no tray. Test `ztk::has tray` first. - `tray "NAME" doesn't exist`. - `image "NAME" doesn't exist`, `"W" is not a menu`, `bad option "-X"`. - `bad feature "NAME"`: `ztk::has` with a name that is not in the table. # ztk::taskbar, ztk::recent, and ztk::hotkey These commands reach the shell of the desktop: the taskbar or Dock button of the app, the recent documents of the system, and global shortcuts. ## Synopsis ```tcl ztk::taskbar progress ?none|indeterminate|VALUE ?-state normal|paused|error?? ztk::taskbar badge ?COUNT? ztk::taskbar attention ?-critical? ztk::recent add PATH ztk::recent clear ztk::hotkey add SEQUENCE SCRIPT ztk::hotkey remove NAME ztk::hotkey names ``` ## ztk::taskbar The command changes the taskbar button (Windows) or the Dock icon (macOS) of the window `.`. - `progress VALUE` shows a progress bar. `VALUE` is a number from 0 to 1. `-state paused` and `-state error` show the bar in the colors of the system for a paused or a failed job. `indeterminate` shows a progress with no value, and `none` removes the bar. With no argument, `progress` gives the current value. - `badge COUNT` shows the count on the button. 0 removes the badge. With no argument, `badge` gives the current count. - `attention` asks the user to look at the app: the button flashes 3 times on Windows, and macOS makes an informational request on the Dock icon. With `-critical`, the button flashes until the app comes to the front, and macOS makes a critical request. macOS makes no request while the app is active. ```tcl for {set i 0} {$i <= 10} {incr i} { ztk::taskbar progress [expr {$i / 10.0}] after 200; update } ztk::taskbar progress none ztk::taskbar badge 3 ``` ## ztk::recent `add` puts a file in the recent documents of the system and in the jump list of the app. `clear` empties the list of the app. The system keeps the list, so the command keeps no state. `add` needs the file commands in host mode, with the real paths of the host. A path in the jail of `--root` is an error, because the system needs a real path. ## ztk::hotkey `add` registers a global shortcut and gives its name, such as `hotkey1`. The script runs at the global level when the keys go down, also when another app has the focus. `remove` removes a shortcut, and `names` gives the names. A sequence is the modifiers and one key symbol, joined with `-`, with or without the angle brackets of `bind`: `` or `Control-Alt-k`. The modifiers are `Control`, `Alt`, `Shift`, and `Super` (also `Command` and `Win`). An upper case letter adds Shift. A global shortcut reads keys of the whole desktop, so it needs a grant: `Options.hotkeys` of the embedder, or `ztk --allow hotkey`. ```tcl ztk::hotkey add {wm deiconify .; raise .} ``` ## Platforms | Command | Windows | macOS | Linux | Web | |---|---|---|---|---| | `ztk::taskbar` | Yes | Yes (the Dock icon) | No | No | | `ztk::recent` | Yes | No | No | No | | `ztk::hotkey` | Yes (`RegisterHotKey`) | No | No | No | `ztk::has taskbar` and `ztk::has recent` give 1 where the command works ([ztk::has](tray.md#platform-features)). ## Errors - `expected a number from 0 to 1, none, or indeterminate but got "X"`, `bad state "X"`, `-state needs a value from 0 to 1`. - `this platform has no list of recent documents`. - `ztk::recent add needs the file commands with the real paths of the host`. - `global shortcuts need a grant of the embedder (ztk --allow hotkey)`. - `this platform has no global shortcuts`. - `bad shortcut "X"`, `shortcut "NAME" doesn't exist`. - `the system refused the shortcut "X": another app may have it`. # ztk::win The `ztk::win::` commands reach APIs of Windows that a window needs. The commands exist on each platform. On a backend other than Windows each one gives the error code `ZTK WIN UNAVAILABLE`, so a script tests `ztk::has win` first. ## Synopsis ```tcl ztk::win::backdrop window ?auto|none|mica|acrylic|tabbed? ztk::win::jumplist ?task ...? ztk::win::thumbbar window ?button ...? ``` ## ztk::win::backdrop Sets the system backdrop of a toplevel: the material that Windows 11 renders behind the window (`DWMWA_SYSTEMBACKDROP_TYPE`). With no type, the command gives the type that it set last, or `auto`. The client area of ztk is opaque, so the backdrop shows in the title bar. ```tcl ztk::win::backdrop . mica ``` ## ztk::win::jumplist Sets the tasks of the jump list of the app: the items under "Tasks" in the menu of its taskbar button. Each task is a dict with the keys `title` and `args`, and optionally `description`, `icon`, and `iconindex`. A task starts this program again with `args`. With no task, the command removes the list of the app. ```tcl ztk::win::jumplist {title "New window" args --new} {title "Open recent" args --recent} ``` [`ztk::recent`](taskbar.md#ztkrecent) adds files to the "Recent" part of the same jump list. ## ztk::win::thumbbar Sets the buttons under the thumbnail of the taskbar button of a toplevel, at most 7. Each button is a dict with the keys `image` (a photo), `tooltip`, `command`, and `disabled`. A click runs `command` at the global level. ```tcl ztk::win::thumbbar . [list image play tooltip Play command {player toggle}] ``` ## Errors - `ZTK WIN UNAVAILABLE` (the `errorCode`), with the message `NAME is only on Windows`. - `ZTK WIN BACKDROP`: the version of Windows has no system backdrop. - `bad window path name "W"`, `"W" is not a toplevel`, `"W" has no window`. - `bad backdrop "X": must be acrylic, auto, mica, none, or tabbed`. - `a thumbnail has at most 7 buttons`, `bad key "K" of a button: must be command, disabled, image, or tooltip`, `image "NAME" doesn't exist`, `a task needs a title`. [On Windows](../windows.md) is the guide for the Windows backend. # ztk::limit and ztk::clock `ztk::limit` runs one script with a lower compute limit and memory limit. `ztk::clock` reads the clock of the animations, and sets it in the headless backend for tests. ## Synopsis ```tcl ztk::limit ?-compute UNITS? ?-memory BYTES? script ztk::clock get ztk::clock set MS ``` ## ztk::limit The command runs `script` in the frame of the caller with the lower limits. `-compute UNITS` allows the script at most `UNITS` compute units. `-memory BYTES` allows the script at most `BYTES` more than the memory in use when it starts. The compute units that the script uses count against the limit of the caller too. The old memory limit comes back at the end. A script inside cannot catch the end of its limit, and the caller of `ztk::limit` can. A child interpreter gets the limits of its caller, so `ztk::limit` also bounds a script in a child: ```tcl interp create -safe c if {[catch {ztk::limit -compute 1000 {interp eval c $text}} err]} { puts "stopped: $err" } ``` A limit above the limit of the caller has no effect: the command keeps the lower one. [The compute limit](https://beetlebug.org/ztcl/limits/#the-compute-limit) of ztcl defines a compute unit. ## ztk::clock `get` gives the time of the animation clock in milliseconds. `set MS` sets it. Only the headless backend can set the clock. A test sets the time to move each [animation](../animation.md) to a known point. ```tcl ztk::animate .l -background #2563eb -duration 400 ztk::clock set [expr {[ztk::clock get] + 200}] ;# halfway, in a headless run ``` ## Errors - `wrong # args: should be "ztk::limit ?-compute units? ?-memory bytes? script"`. - `compute limit reached` and the memory error of ztcl, from the script inside, to the caller. - `ztk::clock set needs the headless backend`. - `bad option "-X": must be -compute or -memory`, `expected a count of 0 or more but got "N"`. # Performance The goal is a smooth frame at 60 frames per second or more. The plan sets a budget of 8 ms of CPU time for a frame at the 99th percentile in each bench case, and 4 ms for a frame with 1,000 widgets. All numbers come from `zig build bench` with `ReleaseFast` on the development machine, an Intel Core i7-6700K, unless a row says otherwise. Other jobs shared the machine, so the times are higher than on a quiet machine. Run the cases yourself: ```sh zig build bench -Doptimize=ReleaseFast ``` ## Frame time CPU milliseconds for one frame. Lower is faster. | Case | Median | 99th percentile | Date | |---|---|---|---| | `frame-hover-1000`: the hover of one of 1,000 widgets | 0.66 | 0.85 | 2026-11-23 | | `frame-text-1000`: a text change beside 1,000 widgets | 0.65 | 0.89 | 2026-11-23 | | `anim-hover-1000`: a hover transition beside 1,000 widgets | 0.85 | 1.36 | 2026-11-24 | | `ttk-hover-1000`: a `ttk::style map` hover on 1,000 `ttk` widgets | 0.87 | 1.04 | 2026-11-25 | | `canvas-10000-scroll`: a canvas of 10,000 items scrolls | 1.05 | 1.52 | 2026-11-25 | | `sheet-10000-scroll`: the spreadsheet with 10,000 rows scrolls | 0.75 | 5.20 | 2026-11-25 | | `vector-10000-pan`: the vector tool with 10,000 shapes pans | 3.30 | 3.86 | 2026-11-25 | | `scroll-wheel`: wheel steps on an entry beside 1,000 widgets | 5.08 | 7.23 | 2026-11-25 | | `anim-1000`: 1,000 `ztk::animate` moves at once | 4.06 | 7.20 | 2026-11-24 | | `type-entry`: one key in an entry | 0.028 | 0.036 | 2026-11-25 | | `menu-open`: `tk_popup` of a menu of 20 entries beside 1,000 widgets, with the open move | 1.01 | 1.61 | 2026-11-25 | | `sash-drag`: a drag of the sash of a `panedwindow` with 500 widgets in each pane, one motion for each frame | 0.88 | 1.00 | 2026-11-25 | | `text-1mb-scroll`: a `text` widget with 1 MB of text (16,384 lines, `-wrap word`) scrolls by wheel steps from its middle | 0.43 | 0.72 | 2026-11-25 | | `text-1mb-type`: one key in the middle of the same text, through the class bindings | 0.51 | 0.78 | 2026-11-25 | | `tab-change`: a notebook of 3 tabs with 300 labels on each page changes its tab each 10 frames, with the slide and the fade | 0.29 | 0.56 | 2026-11-25 | ## Start, memory, and idle | Measure | Result | |---|---| | Start to the first frame, headless | 1.6 ms | | Start to the first frame, Wayland | 3.0 ms | | Private memory of the demo on Wayland | 11.2 MB | | An idle window | No frame and no wake-up: 0 frames in 5,000 ms | ## The render thread The script runs on one thread and makes a scene: a list of quads. A render thread draws the scene. The render thread also moves transitions, keyframes, switches, the slider of a scale, and the thumb of a scrollbar by its own clock. So these motions continue while the script is busy. A window with no change draws no frame. ## On the web `ztk.wasm` is 3.0 MB, or 1.0 MB with gzip. It loads when the first live demo scrolls into view. In Node.js, a frame of the gallery at scale 2 had a median of 5.1 ms. ## Not measured yet The frame rate on a real display, and the GPU path on a window. The Vulkan renderer works offscreen, and its window output is not written yet. # Differences from Tk ztk follows the widgets of Tk 8.6.16, with some commands of Tk 8.7 and 9. A script that runs in `wish` 8.6 runs in ztk when it uses the widgets and the commands that ztk has, also on Tcl 9.1 when the script has no difference of the language (below). This page lists what a script can see that differs, what is in progress, and what ztk leaves out on purpose. It was checked against ztk `main` on 2026-11-27. The full list, with each option and each test, is [the limits file](dev/stage2-limits.md). ## Tcl and Tk releases The `ztk` program, a program of `ztk bundle`, and the web build run a script on Tcl 9.1 by default, as the `ztcl` runner does, and report Tk 9.1.0 (`tk_version` 9.1, `package require Tk` 9.1.0, also as the package `tk`). Run a script of Tcl and Tk 8.6 with `ztk --tcl 8.6`, `ZTCL_TCL=8.6`, or `ztk bundle --tcl 8.6`: it then reports Tcl 8.6 and Tk 8.6.16. A bundled app keeps the release of its build. libztk, the drop-in libtk8.6, stays at 8.6. The release changes the language: an integer with a leading zero is decimal, a bad byte in an encoding is an error, and the other changes of [Tcl 9.1 and Tcl 8.6](https://github.com/beetlebugorg/ztcl/blob/main/docs/tcl91.md). The widgets of ztk are the same in both releases: the widget changes of Tk 9.0 and 9.1, such as `ttk::toggleswitch`, the screen reader support, and right-to-left text, are not in ztk yet. ## Platforms Each platform has a native backend of its own, with no toolkit library between ztk and the system. | Platform | Window and renderer | What the system gives a script | Reference | |---|---|---|---| | Linux, Wayland | The Wayland client of ztk, Vulkan into dma-bufs or the CPU renderer | The clipboard, drops and drags, tray icons, file dialogs through the portal, full screen, window icons, less motion | [On Linux](linux.md) | | Linux, X11 | The X11 client of ztk with the CPU renderer, for a desktop with no Wayland compositor | One window, the keys, the pointer, and window icons. No clipboard, no popups, and no input method yet | [On Linux](linux.md#what-works-on-x11) | | macOS 13 and later | AppKit and Metal, with live resize | Native menus and dialogs, Core Text with SF Pro, drops and drags, tray, the Dock menu and badge, window tabs, full screen | [On macOS](macos.md) | | Windows 10 and 11 | Win32 and Direct3D 12 | Native menus and dialogs, DirectWrite with Segoe UI Variable, the Fluent look, drops and drags, tray, taskbar, jump list, global shortcuts | [On Windows](windows.md) | | The web | WebGPU, WebGL 2, or a 2D canvas, in WebAssembly | One window (`.`) on a canvas. A second `toplevel` has no canvas | [On the web](web.md) | | No display | The headless backend with the CPU renderer | Screenshots and input for tests and agents | [For agents](agents.md) | `ztk::has` tells a script which platform features this program has ([ztk::has](commands/tray.md#platform-features)). ## Missing today | Feature of Tk | State in ztk | Issue | |---|---|---| | `send` | Not in ztk. | [#257](https://github.com/beetlebugorg/ztk/issues/257) | | Event sequences of more than one event, such as `` | `bind` gives an error. | [#256](https://github.com/beetlebugorg/ztk/issues/256) | | Text peers (`text peer create`) | `peer names` gives an empty list, and `peer create` gives an error. | [#249](https://github.com/beetlebugorg/ztk/issues/249) | | `canvas postscript` | Gives an error. | [#181](https://github.com/beetlebugorg/ztk/issues/181) | | Rotated canvas text (`-angle`) | The option is stored, and the text renders level. | | | Tk in a child interpreter (`load {} Tk child`) | Not in ztk. One app has one Tk. | | | `selection` with other apps | The selection works inside the app only. The clipboard is the clipboard of the system on Windows, macOS, and Wayland, and local to the app on X11 and the web. | | | `tk busy` | Keeps the busy mark of a window and does not block its input. | | | `tk fontchooser` | Keeps its options and shows no dialog. | | | Bold monospace text | ztk has the regular face of JetBrains Mono only, so `{TkFixedFont 9 bold}` renders in the regular weight. | [#300](https://github.com/beetlebugorg/ztk/issues/300) | ## In progress - Python tkinter apps on ztk, through a drop-in `libtk8.6` (libztk) with libztcl: [#223](https://github.com/beetlebugorg/ztk/issues/223). - Grapheme clusters in the text widgets, in the renderer, and in the cell widths of the terminal: [#296](https://github.com/beetlebugorg/ztk/issues/296). Fallback faces and color emoji: [#300](https://github.com/beetlebugorg/ztk/issues/300). - Well-known Tk apps: the Tk widget demo, tkcon, BWidget, Tablelist, tklib with Plotchart, and gitk run with no change. TkDiff and git gui are in progress ([Runs on ztk](apps.md)). ## Differences that a script can see ### Text and fonts - The fonts come with ztk: `TkDefaultFont` is Inter and `TkFixedFont` is JetBrains Mono on Linux, the web, and headless. macOS uses SF Pro through Core Text, and Windows uses Segoe UI Variable through DirectWrite. So text widths differ from `wish`. The reason: an app has the same layout on each Linux system and in each browser. - A font list with a named font as its family, such as `{TkFixedFont 9 bold}`, keeps the face of that named font with the new size and style, as Tk does. ### Windows - `tk windowingsystem` gives `ztk`, so a script that tests for `x11`, `win32`, or `aqua` gets none of them. The flag `--windowingsystem NAME` of the `ztk` program gives the name that such an app needs ([Install](install.md)). libztk, the library for Python's tkinter ([Python tkinter](python-tkinter.md)), gives `x11` on Linux. - `winfo rootx` and `rooty` of a widget in a second toplevel count from the corner of its own window on Wayland, because a Wayland program does not know the position of its windows. - `grab -global` acts as a local grab, and `grab status` reports `global`. - `tk_setPalette` makes the other colors from the background with its own rule: the foreground is black or white, and the active, select, and trough colors are the background 10 or 20 percent lighter or darker. The colors of `wish` differ a little. ### The look - The theme gives the border and the padding. So `-borderwidth`, `-padx`, and `-pady` of a label, a button, and a check button default to 0. A value of the script still applies ([Styling and themes](styling.md)). - Options for looks that the modern theme does not draw are stored and have no effect: for example `-highlightthickness`, `-activebackground`, `-overrelief`, `-troughcolor`, `-repeatdelay` of a scale, and the canvas stipples. The theme `classic` has the look of Tk on X11. - The modern scrollbar has no arrows, so `identify` never gives `arrow1` or `arrow2`, and `fraction` and `delta` count from the ends of the trough. - Canvas items that keep the default black of Tk render with the text color of the theme, so they stay visible in the dark scheme. `itemcget` still gives `#000000`. ### Menus - On macOS and Windows, the `-menu` of a toplevel is the menu bar of the system, and `tk_popup` shows a menu of the system. On Wayland, a posted menu and each cascade is a popup surface that can extend past the window. On X11 and the web, ztk renders the menus inside the window ([Menus](widgets/menus.md)). - The menu bar that ztk renders is a top inset of the toplevel, so `winfo height` of the toplevel includes the row of the bar. - A tearoff entry shows as a line. A click on it does not tear off the menu. - The entry options `-image`, `-bitmap`, `-compound`, `-hidemargin`, and `-columnbreak` are stored and have no effect on a menu that ztk renders. ### Styles and themes - `ttk::style configure` and `map` change the look through CSS for `-foreground`, `-background`, `-fieldbackground`, `-bordercolor`, `-borderwidth`, `-relief`, `-padding`, `-font`, and `-indicatorcolor`. Other options are stored for `lookup`. - `ttk::style layout` and `element create` store their data with no effect on the look, because CSS gives the look of each part ([ttk::style](styling.md#ttkstyle)). - In `ttk::style map`, a pair with more states wins over an earlier pair with fewer states. Tk takes the earlier pair. - The states `active` and `hover` are one flag. - The themes `default`, `clam`, and `alt` have the modern look. ### Behavior - A press on the trough of a scale or a scrollbar moves one step. Holding the button does not repeat. - A `scale` runs `-command` at once after a change by the user. `wish` runs it as an idle callback. - The list of a `ttk::combobox` is rendered by ztk in the window of the combobox, and no `$cb.popdown` toplevel or listbox exists. A combobox with no values does not open its list. `ttk::scale set` gives an empty result, where `wish` gives the result of `-command`. - A `listbox` binds the keys of the virtual events (`<>`, `<>`, and the others) to `event generate`, so `bind Listbox` has more patterns than in `wish`. The rows have the height of the theme. - `xview scroll` and `yview scroll` accept a fraction of a unit, and a scroll eases over 160 ms. - `` and `` follow Tk 8.7. The wheel does not send `` and ``. - `<>` deletes the selection before it inserts, as Tk does on Windows and macOS. - `grid` differs by one pixel from `wish` in a few layouts with overlapping spans. - A `panedwindow` that is smaller than its panes, with no pane that can stretch, cuts the last pane at its end. Over a sash, the pointer shape changes with no change of `-cursor`. - The row of tabs of a `ttk::notebook` has the height of the theme, so the place of a page differs from `wish`. `-image` and `-compound` of a tab are stored with no effect. ## Absent by design - No code of Tk and no Xlib: ztk is a new implementation. The behavior follows the manual pages of Tk and the results of `wish` 8.6.16 ([References](references/README.md)). Its X11 client is only a backend for a window. - No global grab: `grab -global` stays local, so an app cannot take the input of other apps. ## Additions ztk adds these commands and options. [The ztk:: commands](commands/README.md) lists the reference page of each. - `ztk::terminal`, a terminal widget on libghostty-vt, with `-shell` for the shell of ztcl ([Terminal](widgets/terminal.md)). - `ztk::style`, `ztk::class`, and `ztk::animate`: CSS styles, style classes, and animation ([Styling and themes](styling.md), [Animation](animation.md)). - `ztk::tooltip`, `ztk::limit`, and `ztk::clock` ([ztk::limit](commands/limit.md)). - `ztk::snapshot`, `ztk::tree`, and `ztk::inject` for tests and agents ([For agents](agents.md)), and `ztk::debug` with the Inspect panel and its Probe tab on the site ([Debugging](debugging.md)). - The platform commands: `ztk::dnd`, `ztk::tray`, `ztk::taskbar`, `ztk::recent`, `ztk::hotkey`, `ztk::win::*`, and `ztk::mac::*`. - `image create photo -density 2`: a photo made for a screen of scale 2. A widget lays it out at its logical size and renders its pixels 1:1 on such a screen. - `wm iconphoto` sets the window icon on each desktop platform, and the Dock icon on macOS. - The style classes `switch`, `segmented`, and `search`, `-placeholder` on entries, undo in entries, and fractional wheel steps. - Text widgets move, delete, and wrap by grapheme cluster (UAX #29), where Tk 8.6 steps by character. The text index unit `graphemes` is a ztk addition. # FAQ ## Is ztk a drop-in replacement for Tk? Not yet. ztk has the widgets on [the widgets page](widgets/README.md), and a script that uses only those runs in ztk and in `wish` 8.6. [Differences from Tk](differences.md) lists what is missing. ## Does it use the code of Tk? No. ztk has no code of Tk, and it links no third-party library. It runs on [ztcl](https://beetlebug.org/ztcl/), a Tcl 8.6 interpreter in Zig. [References](references/README.md) credits Tk and the other sources. ## Can I keep my look of Tk? Yes. `ztk::style theme classic` or `ttk::style theme use classic` gives the reliefs and the gray of Tk on X11. [Styling and themes](styling.md) shows both themes. ## Which platforms does it run on? Linux with Wayland, Windows with Win32 and Direct3D 12 ([On Windows](windows.md)), the browser, and a headless backend on Linux, macOS, and Windows. macOS has AppKit and Metal ([On macOS](macos.md)). ## Why does my script fail with `invalid command name "open"`? The `ztk` program gives a script no file or network access. A script can read style sheets from its folder with `ztk::style load`. An app that embeds ztk can turn on capabilities of ztcl. ## Does it work with screen readers? In the browser, ztk keeps a hidden tree of elements with ARIA roles and names over the canvas. Native accessibility is planned. ## Who wrote ztk? ztk is a project of [beetlebug](https://github.com/beetlebugorg). The code and the docs were written largely with AI coding agents, under human direction. Review the code before you depend on it. ## Where is the roadmap? The [plan](dev/plan.md#11-stages) has the stages. Report bugs and requests in the [issues](https://github.com/beetlebugorg/ztk/issues). # Changelog ## v1.0.0-beta.1 (2026-11-28) The first beta of ztk 1.0. ztk adds native clients for Wayland and X11 with no C library, the native look of each platform, drag and drop, the tray, the taskbar, and the jump lists, `ztk bundle --target` for each platform from any host, the `ttk` widgets, the canvas, `ztk::debug` and `ztk --mcp` for agents, and the WebGPU renderer of the web build. ztk follows Tcl 9.1 by default (the breaking change below). - **Breaking:** ztk follows Tcl and Tk 9.1 by default: the `ztk` program, the programs of `ztk bundle`, and the web build. Tk reports 9.1.0. A script of 8.6 can break on the differences of the language: an integer with a leading zero is decimal, a bad byte in an encoding is an error, and the other changes of [Tcl 9.1 and Tcl 8.6](https://github.com/beetlebugorg/ztcl/blob/main/docs/tcl91.md). Run such a script with `ztk --tcl 8.6`, `ZTCL_TCL=8.6`, or `ztk bundle --tcl 8.6`. The widgets are the same in both releases, and the widget changes of Tk 9.0 and 9.1 are not in ztk yet. libztk, the drop-in libtk8.6, stays at 8.6. See [Differences from Tk](docs/differences.md). - Adds the Wayland client of ztk, with no C library: the wire protocol, the XKB key map, the pointer shapes, the clipboard, and the input method. The static Linux programs of a release open a window. The main window renders with Vulkan into dma-bufs, or with the CPU renderer. See [On Linux](docs/linux.md). - Adds an X11 client for a Linux desktop with no Wayland compositor. - Adds drops of files and text from other apps (`tkdnd::drop_target`) and drags to them (`ztk::dnd drag`) on Windows, macOS, and Wayland. See [ztk::dnd](docs/commands/dnd.md). - Adds `ztk::tray` on Windows, macOS, and Linux (StatusNotifierItem), and `ztk::has`. See [ztk::tray](docs/commands/tray.md). - Adds `ztk::taskbar` (Windows and macOS), `ztk::recent`, and `ztk::hotkey` (Windows). See [ztk::taskbar](docs/commands/taskbar.md). - Adds `ztk::win::backdrop`, `ztk::win::jumplist`, and `ztk::win::thumbbar`, and `ztk::mac::dockmenu` and `ztk::mac::tabbing`. See [ztk::win](docs/commands/win.md) and [On macOS](docs/macos.md). - Adds the native look of each platform: Core Text with SF Pro, the native message box, color dialog, and file dialogs on macOS; DirectWrite with Segoe UI Variable, the Fluent controls of WinUI 3, the title bar in the scheme of the app, and the native dialogs on Windows; the `FileChooser` portal on Linux. - Adds `wm attributes -fullscreen` and `-topmost`, and follows the less-motion setting of the system, on macOS, Windows, and Wayland. - Adds `ztk bundle --target` for each platform from any host: a signed macOS app folder with `-o Name.app`, a Windows program with its icon, manifest, and version info, and a Linux program with a desktop entry. `ZTK_HEADLESS=1` runs a bundled app with no display. - Runs famous Tk apps on ztk, and adds the option database: `option add`, `clear`, `get`, and `readfile`. See [Runs on ztk](docs/apps.md). - Moves `ztk::terminal` to libghostty-vt through `ztcl::vt`, and adds `-shell` for the shell of ztcl. Runs the program of the terminal on the pseudo console of Windows. - Adds the reference pages of the `ztk::` commands in `docs/commands/`. - Adds builds for aarch64-windows, and an Arch Linux PKGBUILD in `packaging/arch/ztk-git`. - Adds `zig build runtimes`: the `ztk` program of each target of `ztk bundle --target`, with the full GUI backend of its platform, in `zig-out/lib/ztk/runtime/`. The release programs for Linux now have the Vulkan renderer. - `wm iconphoto` sets the window icon on Linux: `_NET_WM_ICON` on X11, and `xdg-toplevel-icon-v1` on Wayland. - Adds `ztk::debug sources`, `ztk::debug why`, and `ztk::debug geometry`: the source of each option of a widget and its geometry chain. - Adds `ztk::debug trace`: records of events, bindings, commands, option writes, geometry passes, dirty widgets, frames, focus, and grabs, with filters. - Adds `ztk::debug mark` and `ztk::debug diff`: the pixels and the widgets that changed between two captures. - Adds `ztk::debug explain`, `click`, `type`, `ran`, `changes`, and `tree`, short answers for agents, and `ztk --mcp`, which serves them as MCP tools. - Adds the page "Debug a form": a live form with three bugs to find with `ztk::debug`, and the Console of the live snippets. - The Inspect panel of the live snippets has tabs: the options with the source of each value, the bindings, the geometry chain, the scripts and procs, and the trace of the widget. A change of an option goes into the line of the code that set it. - The Inspect panel has a Probe tab: probes and breakpoints on the lines of the procs behind a widget (`ztcl::probe`), and their records. A breakpoint stops the frames of the snippet until Continue. - `ztk::debug why` gives `fileline`, the line of a command in its file, also inside a proc. A change of an option in the Inspect panel then goes into the line in the proc. - Adds the `ttk` widgets `ttk::button`, `ttk::checkbutton`, `ttk::radiobutton`, `ttk::label`, `ttk::frame`, `ttk::labelframe`, `ttk::entry`, `ttk::separator`, and `ttk::sizegrip`, the command `ttk::style`, and the `classic` theme. - Adds `spinbox`, entry validation, `-placeholder`, the search field, undo, and the `clipboard` command. - Adds the `canvas` widget with all item types, scrolling, `image create photo`, and item animation. - Adds `scrollbar`, the scroll protocol, and the mouse wheel. - Moves keyframes, color animations, the parts of widgets, and drags to the render thread. - Adds the examples `themes.tcl`, `themes-classic.tcl`, and `counter.tcl`. - Adds the example apps `examples/spreadsheet.tcl` (10 000 rows on a canvas, with formulas) and `examples/vector.tcl` (a drawing tool with SVG export and a script console), their tests in `tests/apps.sh`, their bench cases, and their live cards on the site. - Adds `ztk::limit`, the `interp` command, and `ztk::style scheme`. - Adds the WebGPU renderer of the web build (`webgpu.js`). `"auto"` selects WebGPU, then WebGL 2, then the CPU renderer. The web canvas has the size of its window at each pixel ratio. ## v0.2.0-beta (2026-11-25) - Adds `pack`, `place`, `checkbutton`, `radiobutton`, `toplevel`, `labelframe`, `message`, `grab`, `ztk::tooltip`, and `scale`. - Adds CSS transitions, `@keyframes`, `ztk::animate`, and the frame clock. - Adds the web backend with WebGL 2, and the live examples on the site. - Adds the plan, the Stage 1 tasks, the review checklist, and the references. - Adds the tools that measure the size of Tk. - Adds the docs site, the CI and release workflows, and the Homebrew formula template. - Licensed under BSD-2-Clause. - Adds the npm package `@beetlebug/ztk`, with types, and a workflow that publishes it on a version tag. `ztk.js` has `mount`, a CPU renderer for a browser with no WebGL 2, and `destroy`. See `docs/web.md` and `docs/dev/npm.md`. # Contributing ztk is experimental. Open an issue before a large change. 1. Read [WRITING.md](WRITING.md), [AGENTS.md](AGENTS.md), and [the plan](docs/dev/plan.md). 2. When the repository has a `build.zig`, run `zig build test` with Zig 0.17.0. The tests must pass. 3. Run `sh tools/check-repo.sh` and `python3 tools/build-docs.py site`. 4. Open a PR. PRs merge by rebase. Contributions are licensed under BSD-2-Clause. Do not submit code copied from Tk or from a project with a GPL, LGPL, or AGPL license. Credit each source in [the references](docs/references/README.md). # Security ztk is experimental and has no release. Do not use it to run scripts from a source that you do not trust. The plan has these rules for later code: - The ztk library turns on no capability of ztcl. - Only the `ztk` program turns on a capability, from a flag. ## Report a problem Use a private report through the GitHub **Security** tab of [beetlebugorg/ztk](https://github.com/beetlebugorg/ztk/security/advisories/new). Include a script that shows the problem. You can also write to [opensource@beetlebug.org](mailto:opensource@beetlebug.org). Put "security" in the subject, and do not file a public issue.