Touch and the screen
A Tk script runs as an app on an Android or iOS phone or tablet. The app fills the screen, and the widgets of Tk and ttk work by touch. The same script runs on a desktop with ztk main.tcl, so you can write and try it there first.
This page has the parts that are the same on Android and on iOS: touch, the soft keyboard, the screen, the life of the app, and the saved data. The Android and iOS sections show how to build and run the app on each platform.
Touch
The first finger on the screen is the pointer. A finger down is a press of button 1, a move is <B1-Motion>, and a finger up is a release of button 1. So a binding for the mouse works for a finger with no change:
- A tap is a click. A tap on a button, a check button, a radio button, or a tab of a notebook invokes it.
- A tap on a row of a listbox or a treeview selects the row.
- A tap on a menubutton or a combobox opens its menu or its list. A tap on an entry of the menu or the list picks it.
- A tap on an option menu of
tk_optionMenuopens it over its button, with the current value under the finger. A tap on an entry picks it. A slide of the finger to an entry and a lift there picks it too. - A drag in an entry selects text, as a drag of the mouse does.
- A drag of the thumb of a scrollbar scrolls the view. The modern theme shows the thumb while the view scrolls and while the pointer is over the scrollbar, so the thumb shows when a finger touches the scrollbar.
- A drag on a canvas with no
-scrollregiongives<B1-Motion>to the bindings of the canvas and of its items.
Scroll with a finger
A drag in a text widget, a listbox, a treeview, or a canvas with a -scrollregion scrolls its view, as on the other apps of a phone. The content moves with the finger, and after a fast lift it glides on and slows down. A touch on a view that glides stops it, and that touch is no click. A drag on a widget inside a view that scrolls, such as a button in a text widget, scrolls the view too.
On these views the press of button 1 waits for the finger:
- A lift before a move of 10 pixels is a tap: the press and the release of button 1 come at the lift. A tap selects a row or puts the insert cursor in the text.
- A finger that stays for half a second without a move presses button 1 then, as a mouse does. A drag after it selects text or rows.
A drag keeps the meaning that it has with a mouse on a scrollbar, a scale, an entry, a spinbox, a combobox, a menubutton, and a paned window. It keeps it also on a widget with a binding of its own for <B1-Motion>, <<TouchBegan>>, or <<TouchMoved>>, and on an item of a canvas with a binding for a press or a drag of button 1. So a game that reads the finger on its canvas gets each event at once:
canvas .c -scrollregion {0 0 400 2000} -yscrollcommand {.s set}
scrollbar .s -command {.c yview}
pack .s -side right -fill y
pack .c -side left -fill both -expand 1
.c create rectangle 20 20 120 80 -fill orange -tags knob
# A drag on the knob moves it; a drag elsewhere scrolls the canvas.
.c bind knob <B1-Motion> {.c coords knob \
[expr {[.c canvasx %x]-50}] [expr {[.c canvasy %y]-30}] \
[expr {[.c canvasx %x]+50}] [expr {[.c canvasy %y]+30}]}
A gesture of the system, such as a swipe from the edge of the screen or a call, cancels a touch. The press then ends with a release and a <Leave>, so a grab and the press of a button end.
A long press
A finger that stays for half a second, with a move of less than 10 pixels, is a long press. On a widget with a binding of a press of button 3, in one of its tags, a long press is a press of button 3 at the point of the finger, and the lift is its release. So the context menu of a desktop app opens on a phone with no change:
text .t
pack .t -fill both -expand 1
menu .m -tearoff 0
.m add command -label Copy -command {tk_textCopy .t}
.m add command -label Paste -command {tk_textPaste .t}
bind .t <Button-3> {tk_popup .m %X %Y}
The menu of tk_popup opens under the finger, and stays open when the finger lifts there. A tap on an entry picks it, and a tap out of the menu closes it. On such a widget a tap waits for the lift, as on a view that scrolls.
On a widget with no binding of button 3, a long press presses button 1 at the point of the finger, so a drag after it selects text or rows.
Each finger
Each finger, the first one too, also gives virtual events to the widget where it went down:
| Event | When |
|---|---|
<<TouchBegan>> |
The finger goes down. |
<<TouchMoved>> |
The finger moves. |
<<TouchEnded>> |
The finger goes up, or the system cancels the touch. |
%x and %y are the point of the finger in that widget, and %d is the number of the finger. The widget keeps the events of a finger when the finger moves out of it. Use these events for two or more fingers at a time, for example for two buttons of a game. This canvas draws a dot under each finger:
canvas .pad -width 300 -height 200 -background white
pack .pad
bind .pad <<TouchBegan>> {
.pad create oval [expr {%x-15}] [expr {%y-15}] \
[expr {%x+15}] [expr {%y+15}] -fill blue -tags f%d
}
bind .pad <<TouchMoved>> {.pad moveto f%d [expr {%x-15}] [expr {%y-15}]}
bind .pad <<TouchEnded>> {.pad delete f%d}
Two fingers
Two fingers on the screen give a pinch to the widget under the first finger:
| Event | When |
|---|---|
<<PinchBegan>> |
The second finger goes down. |
<<PinchMoved>> |
One of the two fingers moves. |
<<PinchEnded>> |
One of the two fingers goes up. |
%x and %y are the point between the two fingers in that widget, and %d is the distance of the fingers over their distance at <<PinchBegan>>: 1.0 at the start, 2.0 when the fingers are twice as far apart, and 0.5 at half the distance. A third finger has no part in the pinch. This canvas zooms its items about the point between the fingers:
canvas .c -width 300 -height 300 -background white
pack .c -fill both -expand 1
.c create rectangle 100 100 200 200 -fill orange
bind .c <<PinchBegan>> {set ::last 1.0}
bind .c <<PinchMoved>> {
.c scale all %x %y [expr {%d / $::last}] [expr {%d / $::last}]
set ::last %d
}
A second finger ends the scroll of a view and the wait of a tap: the first finger gives no more click.
The soft keyboard
The soft keyboard opens when an entry, a spinbox, a combobox, or a text widget gets the focus. A tap on one of these widgets gives it the focus. The keyboard closes when the focus goes to a widget of another kind, so focus . closes it:
ttk::entry .e
pack .e -padx 20 -pady 20
bind .e <Return> {focus .}
The keys of the keyboard go to the widget as key events, so the bindings of <Return>, <BackSpace>, and <KeyPress> work. The text that each keyboard types is on On Android and On iOS.
The screen
The window . fills the screen. Sizes are in logical pixels: a point on iOS, and a density-independent pixel (dp) on Android. winfo width . and winfo height . give the size of the screen in logical pixels. <Configure> comes to . at each change of the size, such as a turn of the phone.
| Command | What it does |
|---|---|
tk touchscreen |
Gives 1 on a phone or a tablet, and 0 on a desktop. |
wm attributes . -orientation landscape |
Keeps the screen in landscape. The values are any (the default), landscape, and portrait. |
wm attributes . -zoom 1.5 |
Makes the content of the window larger. The window keeps its pixels, and its size in logical pixels divides by the factor. The factor is from 0.25 to 8. |
tk insets ?window? |
Gives the parts of a toplevel under the bars of the system and the soft keyboard. |
A desktop keeps the values of -orientation and -zoom with no effect, so one script runs on both:
if {[tk touchscreen]} {
wm attributes . -orientation landscape
wm attributes . -zoom 1.5
}
Insets
A phone draws the app under its status bar, the bar of the home gesture, a notch or a cutout, and the soft keyboard. tk insets gives a dict with top, left, bottom, right, and keyboard, in logical pixels. keyboard is the height of the part of the window under the soft keyboard. <<Insets>> comes to the toplevel at each change. On a desktop each value is 0.
This form keeps its widgets inside the insets and above the keyboard:
ttk::frame .main -padding 12
ttk::label .main.l -text "Name"
ttk::entry .main.e
ttk::button .main.ok -text "Save" -command {focus .}
pack .main.l .main.e .main.ok -fill x -pady 6
pack .main -fill both -expand 1
bind .main.e <Return> {focus .}
bind . <<Insets>> {
set i [tk insets .]
set bottom [expr {max([dict get $i bottom], [dict get $i keyboard])}]
pack configure .main -padx [list [dict get $i left] [dict get $i right]] \
-pady [list [dict get $i top] $bottom]
}
The size of text
The size of text in the settings of the system (the font size of Android, Dynamic Type of iOS) scales these fonts:
- The named fonts, such as
TkDefaultFont, and a font offont createwith a size. - The text of the styles, and the sizes in px and pt of a style sheet (Styling).
A size in a -font value, such as -font {Helvetica 12}, stays as it is. Use the named fonts for text that must follow the setting. A change of the setting while the app runs goes to the app at once.
Dark mode
The colors of the themes follow the light or dark mode of the system, also when it changes while the app runs. ztk::style scheme gives light or dark. A rule of a style sheet in @media (prefers-color-scheme: dark) gives the colors of the dark scheme (Styling).
At a change of the mode, . gets <<SchemeChanged>>, after the themes have their new colors. A script that draws with colors of its own, such as the items of a canvas, draws them again there:
proc paint {} {
set ink [expr {[ztk::style scheme] eq "dark" ? "#e8e8ec" : "#202024"}]
.c itemconfigure label -fill $ink
}
bind . <<SchemeChanged>> paint
The life of the app
The system can stop an app that is not in front. ztk sends these virtual events to .:
| Event | When |
|---|---|
<<AppBackground>> |
The app goes to the background. In the background the app draws no frame. |
<<AppForeground>> |
The app comes back to the front. ztk draws each window again. |
<<LowMemory>> |
The system is short of memory. Drop the data that the app can make again. |
<<AppTerminate>> |
iOS ends the app while it runs. Android does not send this event. |
The system can end the process of an app in the background with no event. The next launch then runs the script from the start. So save the state of the app at <<AppBackground>>, and read it at the start.
Where to save
tk appdata gives a writable folder of the app, as the file commands name it. In an app of ztk bundle, that folder is the root folder of the file commands, so tk appdata gives /. On a desktop it gives an empty string. The app copies its files from ztk bundle into this folder at each start. So save data in a file with a name of its own, and not in a file of the app.
set ::count 0
proc statefile {} {
set dir [tk appdata]
if {$dir eq ""} {return count.txt}
return [file join $dir count.txt]
}
if {[file exists [statefile]]} {
set f [open [statefile]]
set ::count [read -nonewline $f]
close $f
}
proc save_state {} {
set f [open [statefile] w]
puts $f $::count
close $f
}
ttk::button .b -textvariable ::count -command {incr ::count}
pack .b -padx 40 -pady 40
bind . <<AppBackground>> save_state
These commands need the file and channels capabilities. An app of ztk bundle has them by default.
An example: the games of the Toys page
The games of the Games page run on a phone with no change, through a host written only with the commands of this page: docs/toys/native/toyhost.tcl. An app of a game is the game script and the host, with a main script of two lines that sources both (docs/toys/native/NAME.tcl):
ztk bundle -o Lamplighter.apk --target aarch64-linux-android \
docs/toys/native/lamplighter.tcl docs/toys/lamplighter.tcl \
docs/toys/native/toyhost.tcl
ztk --ios docs/toys/native/lamplighter.tcl docs/toys/lamplighter.tcl \
docs/toys/native/toyhost.tcl
No game has a d-pad: each one reads the finger on its canvas. Lamplighter and Tin Moon keep the screen in landscape, and Skate Pond turns with the phone. iOS features and Android features show the games on each phone.
On a touch screen, the host sets the orientation of the game with -orientation, and makes the game fill the screen with -zoom inside tk insets. Each game reads taps, swipes, and drags on its own canvas with the pointer bindings of Tk (Touch). For a game that does not read touch, the host puts a d-pad, A, B, and Start in the margins beside the game. Each finger holds its own button through <<TouchBegan>> and <<TouchEnded>>. The game keeps its saved state in toy.save in tk appdata.
Limits
- A finger gives no button 2. Button 3 comes only from a long press (A long press).
- ztk has no zoom of its own for a pinch: a script zooms with the pinch events (Two fingers).
- The composition of an input method (Chinese, Japanese, and Korean), a word from a swipe on the keyboard, and the corrections of the keyboard do not go to the widget.
- Native APIs of the phone, such as the location and the sensors, are not available yet.