Provides a simple touch driven event based GUI interface for the Pyboard when used with a TFT display. The latter should be based on SSD1963 controller with XPT2046 touch controller. Such displays are available in electronics stores e.g. and on eBay. The software is based on drivers for the TFT and touch controller from Robert Hammelrath.
It now uses and requires uasyncio V3.
It is targeted at hardware control and display applications.
For hardware notes see this reference. An extension for plotting simple graphs is described here.
For sample images, go here. A video may be seen here.
- Release notes
- Pre requisites
2.1 Pre installation
2.2 Library Documentation
2.3 Python files
2.4 Running the demos - Icons
- Concepts
4.1 Terminology
4.2 Coordinates
4.3 Colors
4.4 Callbacks
4.5 Screens - Program Structure
- Class Screen
6.1 Class methods
6.2 Constructor
6.3 Callback methods
6.4 Method - Display Widgets Non touch sensitive displayable objects.
7.1 Class Label
7.2 Class Dial
7.3 Class LED
7.4 Class Meter
7.5 Class IconGauge
7.6 Vector display - Control Widgets Touch sensitive displayable objects
8.1 Class Slider
8.2 Class Knob
8.3 Class Checkbox
8.4 Class Button
8.5 Class ButtonList: emulate a button with multiple states
8.6 Class RadioButtons
8.7 Class IconButton also checkbox
8.8 Class IconRadioButtons
8.9 Class Listbox
8.10 Class Dropdown - Dialog Boxes
9.1 Class Aperture
9.2 Class DialogBox - Developer Notes
Release 0.7 16th Jun 2020 Refactored as a Python package (see below). Add
vector display widgets.
Release 0.6 15th Jun 2020 Uses (and requires) uasyncio V3.
Release 0.51 14th Feb 2017 add Screen.after_open method.
Release 0.5 7th Jan 2017. Uses uasyncio in place of usched.
Release 0.2 17th Nov 2016. Uses fonts created with the font_to_py.py utility.
This has been refactored as a Python package. This enables a modular design and reduces RAM use to the point where frozen bytecode is not usually required. All test scripts apart from the icon test will run without frozen code.
Applications will require changes to import statements.
Before running the GUI the hardware should be tested. The display may
optionally be calibrated according to the instructions on Robert Hammelrath's
site.
Resistive touch panels work best when activated by a stylus or fingernail. They
are also subject to jitter to a degree which varies between display models: the
touch library uses digital filtering to reduce the effect of jitter. This uses
two values confidence and margin which may be fine tuned to the unit in
use prior to running the GUI. The optimum values, together with calibration
data, should be stored in the file tft_local.py listed below.
Some familiarity with callbacks and event driven programming will be of help in developing applications. The GUI classes are in two categories, those rendered using icons and those drawn by means of graphics primitives. Either (or both) may be used in a project.
Smaller applications not using icon controls will run without frozen bytecode. Users planning larger applications should familiarise themselves with building Micropython from source, and with the technique for installing Python modules as frozen bytecode. Official instructions on how to do this may be found here. At the time of writing these did not reflect the new "manifest" system, which is described here.
To ensure the correct version of uasyncio firmware must be a daily build or a
release build later than V1.12.
Documentation for the underlying libraries may be found at these sites.
Robert Hammelrath's drivers:
XPT2046 driver
TFT driver
Other references:
Proposed standard font format
TFT driver fork
Robert Hammelrath's driver adapted for above font format.
uasyncio libraries and notes
The simplest way to install this library is to copy the tft directory and all
its contents to the Pyboard's filesystem.
Hardware driver in tft/driver:
TFT_io.pyLow level TFT driver. Cannot be frozen.
Core files in tft/driver:
tft.pyTFT driver.touch_bytecode.pyTouch panel driver.ugui.pyThe micro GUI library.constants.pyConstants such as colors and shapes (import usingfrom tft.driver.constants import *)tft_local.pyLocal hardware definition (user defined settings including optional calibration data). This file should be edited to match your hardware.
Synchronisation primitives in tft/primitives:
delay_msA software retriggerable timer.
Optional files used by test programs:
Fonts in tft/fonts:
font10.pyFont file.font14.pyDitto.
Icons in tft/icons:
radiobutton.pyIcon file for icon radio buttonscheckbox.pyIcon file for icon checkboxes.iconswitch.pyIcon file for an on/off switch.traffic.pyIcons for traffic light buttongauge.pyIcons for linear gaugeflash.pyIcons for flashing buttonthreestate.pyIcon for 3-state checkbox
Test/demo programs in tft/demos:
vst.pyA test program for vertical linear sliders.hst.pyTests horizontal slider controls, meters and LED.buttontest.pyPushbuttons and checkboxes.knobtest.pyRotary controls, a dropdown list, a listbox. Also shows the two styles of "greying out" of disabled controls.screentest.pyTest of multiple screens.dialog.pyA modal dialog box.ibt.pyTest of icon buttons.vtest.pyVector display: clock and compass displays.
If you don't intend to use icons, icon files and demo 7 may be ignored.
By the standards of the Pyboard this is a large library. All test scripts will
run without frozen bytecode with the exception of ibt.py. Larger applications
and any using icons will require freezing some modules to conserve RAM.
When freezing files create the same directory structure in your frozen modules directory. For example, create the directory 'tft/icons' and copy all icons there. This allows the import statements to be unchanged.
Preferred candidates for freezing are icons (if used), fonts and drivers. The
hardware driver listed above cannot be frozen as it uses inline assembler and
Viper code. It's probably unwise to freeze tft_local.py as it may need to be
edited for calibration values etc.
Instructions on creating icon files may be found in the
TFT driver README. Fonts
should be created using
font_to_py.py. The
-x argument should be employed.
Demos run on import, which is done using the following syntax:
from tft.demos import hstIf you experience memory errors after running more than one demo, issue ctrl-d to reset the board.
Most classes use graphics primitives to draw objects on the screen. A few employ icons: this is arguably prettier but less "micro". It uses large icon files which must be frozen as bytecode. By contrast objects drawn with graphics primitives are scalable. Further, properties such as colors can efficiently be changed at runtime: to achieve this with an icon-based object would require a set of colored icons to be created at design time. The library is usable without the icon classes.
Instructions and a utility for creating icon files may be found in Robert Hammelrath's TFT driver README.
GUI objects are created on a Screen instance which normally fills the entire
physical screen. Displayable GUI objects comprise control and display
instances. The former can respond to touch (e.g. Pushbutton instances) while
the latter cannot (LED or Dial instances).
In common with most displays, the top left hand corner of the display is (0, 0) with increasing values of x to the right, and increasing values of y downward. Display objects exist within a rectangular bounding box; in the case of touch sensitive controls this corresponds to the sensitive region. Locations are defined as a 2-tuple (x, y). The location of an object is defined as the location of the top left hand corner of the bounding box.
These are defined as a 3-tuple (r, g, b) with values of red, green and blue in range 0 to 255. The interface and this document uses the American spelling (color) throughout for consistency with the TFT library.
The interface is event driven. Controls may have optional callbacks which will be executed when a given event occurs. A callback function receives positional arguments. The first is a reference to the object raising the callback. Subsequent arguments are user defined, and are specified as a tuple or list of items. Callbacks are optional, as are the argument lists - a default null function and empty list are provided. Callbacks are usually bound methods - see the Screens section for a reason why this is useful.
All controls and displays have a tft property. This enables callbacks to
access drawing primitives.
GUI controls and displays are rendered on a Screen instance. A user program
may instantiate multiple screens, each with its own set of GUI objects. The
Screen class has class methods enabling runtime changes of the screen being
rendered to the physical display. This enables nested screens. The feature is
demonstrated in screentest.py.
Applications should be designed with a Screen subclass for each of the
application's screens (even if the app uses only a single screen). This
faciitates sharing data between GUI objects on a screen, and also simplifies
the handling of control callbacks. These will be methods bound to the user
screen. They can access the screen's bound variables via self and the
control's bound methods via the callback's first argument (which is a reference
to the control). A simple example can be seen in the KnobScreen example in
screentest.py.
The Screen class has 3 null methods which may be implemented in subclasses:
on_open which runs when a screen is opened but prior to its display,
after_open which is called after display, and on_hide which runs when a
screen change is about to make the screen disappear. These may be used to
instantiate or control tasks and to retrieve results from a modal dialog box.
The Screen class is configured in tft_local.py.
The following illustrates the structure of a minimal program:
from tft.driver.ugui import Screen
from tft.driver.constants import *
from tft.driver.tft_local import setup
from tft.fonts import font14
from tft.widgets.buttons import Button
class BaseScreen(Screen):
def __init__(self):
super().__init__()
Button((10, 10), font = font14, fontcolor = BLACK, text = 'Hi')
setup()
Screen.change(BaseScreen)The last line causes the Screen class to instantiate your BaseScreen and to
start the scheduler using that screen object. Control then passes to the
scheduler: any code following this line will not run until the GUI is shut down
and the scheduler is stopped (by calling Screen.shutdown()).
The Screen class presents a full-screen canvas onto which displayable objects
are rendered. Before instantiating GUI objects a Screen instance must be
created. This will be the current one until another is instantiated. When a GUI
object is instantiated it is associated with the current screen.
The best way to use the GUI, even in single screen programs, is to create a
user screen by subclassing the Screen class. GUI objects are instantialited
in the constructor after calling the Screen constructor. This arrangement
facilitates communication between objects on the screen. The following presents
the outline of this approach:
def backbutton(x, y):
def back(button):
Screen.back()
Button((x, y), height = 30, font = font14, fontcolor = BLACK, callback = back,
fgcolor = CYAN, text = 'Back', shape = RECTANGLE, width = 80)
class Screen_0(Screen):
def __init__(self):
super().__init__()
Label((0, 0), font = font14, width = 400, value = 'Test screen')
backbutton(390, 242)
setup()
Screen.change(Screen_0)Note that the GUI is started by issuing Screen.change with the class as its
argument rather than an instance. This assists in multi-screen programs:
screens are only instantiated when they are to be displayed. This allows RAM to
be reclaimed by the garbage collector when the screen is closed.
In normal use the following methods only are required:
changeChange screen, refreshing the display. Mandatory positional argument: the new screen class name. This must be a class subclassed fromScreen. The class will be instantiated and displayed. Optional keyword arguments:args=[],kwargs={}. These are arguments for the subclass constructor.backRestore previous screen.shutdownClear the screen and shut down the GUI.set_grey_styleSets the way in which disabled ('greyed-out') objects are displayed. The colors of disabled objects are dimmed by a factor and optionally desaturated (turned to shades of grey). Optional keyword arguments:desaturatedefaultTrueandfactordefault 2. AValueErrorwill result iffactoris <= 1. The default style is to desaturate and dim by a factor of
Other method:
get_tftReturn theTFTinstance. This allows direct drawing to the physical screen. Anything so drawn will be lost when the screen is changed. In normal use theTFTinstance is acquired via a GUI object'stftproperty.
See screentest.py and dialog.py for examples of multi-screen design.
This takes no arguments.
These do nothing, and are intended to be defined in subclasses if required.
on_openCalled when a screen is displayed.after_openCalled after a screen has been displayed.on_hideCalled when a screen ceases to be current.
reg_taskargstask,on_change=False. The first arg may be aTaskinstance or a coroutine. It is a convenience method which provides for the automatic cancellation of tasks. If a screen runs independent coros it can opt to register these. On shudown, any registered tasks of the base screen are cancelled. On screen change, registered tasks withon_changeTrueare cancelled. For finer control applications can ignore this method and handle cancellation explicitly in code.
These classes provide ways to display data and are not touch sensitive.
Displays text in a fixed length field. The height of a label is determined by the metrics of the specified font.
Constructor mandatory positional argument:
location2-tuple defining position.
Keyword only arguments:
fontMandatory. Font object to use.widthThe width of the object in pixels. Default:None- width is determined from the dimensions of the initial text.borderBorder width in pixels - typically 2. If omitted, no border will be drawn.fgcolorColor of border. Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.valueInitial text. Default:None.
Method:
valueArgumentvalstring, defaultNone. If provided, refreshes the label with the passed text otherwise clears the text in the label.
Displays angles in a circular dial. Angles are in radians with zero represented by a vertical pointer. Positive angles appear as clockwise rotation of the pointer. The object can display multiple angles using pointers of differing lengths (e.g. clock face).
Constructor mandatory positional argument:
location2-tuple defining position.
Keyword only arguments (all optional):
heightDimension of the square bounding box. Default 100 pixels.fgcolorColor of border. Defaults to system color.bgcolorBackground color of object. Defaults to system background.borderBorder width in pixels - typically 2. If omitted, no border will be drawn.pointersTuple of floats in range 0 to 0.9. Defines the length of each pointer as a proportion of the dial diameter. Default (0.9,) i.e. one pointer of length 0.9.ticksDefines the number of graduations around the dial. Default 4.
Method:
valueArguments:angle(mandatory),pointer(optional) the pointer index. Displays an angle. AValueErrorwill be raised if the pointer index exceeds the number of pointers defined by the constructorpointersargument.
Displays a boolean state. Can display other information by varying the color.
Constructor mandatory positional argument:
location2-tuple defining position.
Keyword only arguments (all optional):
heightDimension of the square bounding box. Default 30 pixels.fgcolorColor of border. Defaults to system color.bgcolorBackground color of object. Defaults to system background.borderBorder width in pixels - typically 2. If omitted, no border will be drawn.colorThe color of the LED. Default RED.
Methods:
valueArgumentvalboolean, defaultNone. If provided, lights or extinguishes the LED. Always returns its current state.colorArgumentcolor. Change the LED color without altering its state.
This displays a single value in range 0.0 to 1.0 on a vertical linear meter.
Constructor mandatory positional argument:
location2-tuple defining position.
Keyword only arguments:
heightDimension of the bounding box. Default 200 pixels.widthDimension of the bounding box. Default 30 pixels.fontFont to use in any legends. Default:NoneNo legends will be displayed.legendsA tuple of strings to display on the centreline of the meter. These should be short to physically fit. They will be displayed equidistantly along the vertical scale, with string 0 at the bottom. DefaultNone: no legends will be shown.divisionsCount of graduations on the meter scale. Default 10.fgcolorColor of border. Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.pointercolorColor of meter pointer. Defaults tofgcolor.valueInitial value to display. Default 0.
Methods:
valueOptional argumentval. If provided, refreshes the meter display with a new value.
Range 0.0 to 1.0: out of range values will be constrained to full scale or 0. Always returns its current value.
This can display any one of a set of icons at a location. The icon to be displayed can be selected by an integer index. Alternatively a float in range 0.0 to 1.0 can be displayed: the control shows the nearest icon.
Constructor mandatory positional argument:
location2-tuple defining position.
Mandatory keyword only argument:
icon_moduleThe name of the (already imported) icon file.
Optional keyword only argument:
initial_iconDefault 0. The index of the initial icon to be displayed.
Methods:
iconMandatory argument: index of an icon. Displays that icon.valueOptional argumentval. Range 0.0 to 1.0. If provided, selects the nearest icon and displays it. Always returns the control's current value.
Provides a means of displaying one or more vectors. A vector is a complex
with magnitude in the range of 0 to 1.0. In use a VectorDial is instantiated,
followed by a Pointer instance for each vector to be displayed on it. The
VectorDial can display its vectors as lines (as on a clock face) or as arrows
(as on a compass).
By contrast with the Dial class the pointers have lengths and colors which
can vary dynamically.
from micropython_ra8875.widgets.vectors import Pointer, VectorDialConstructor mandatory positional argument:
location2-tuple defining position.
Keyword only arguments (all optional):
height=100Dimension of the square bounding box.fgcolor=NoneForeground color. Defaults to system color.bgcolor=NoneBackground color of object. Defaults to system background.border=NoneBorder width in pixels - typically 2. Default: no border.ticks=4Defines the number of graduations around the dial.arrow=FalseIfTruevectors will appear as arrows.pip=NoneBy default a small circular "pip" is drawn at the centre of the dial. IfFalseis passed this is omitted. If a color is passed, it will be drawn using that color. If the shortest pointer has a length below a threshold the "pip" is omitted to ensure visibility.
Constructor mandatory positional arg:
dialThe dial on which it is to be displayed.
Method:
valueArgsv=None, col=None. Returns the current value. If acomplexis passed as the valuevit is scaled to ensure its magnitude is <= 1 and the pointer is redrawn. If a color is passed ascolthe pointer's color is updated.
These classes provide touch-sensitive objects capable of both the display and entry of data. If the user moves the control, its value will change and an optional callback will be executed. If another control's callback or a task alters a control's value, its appearance will change to reflect this.
Buttons and checkboxes are provided in two variants, one drawn using graphics primitives, and the other using icons.
These emulate linear potentiometers. Vertical Slider and horizontal
HorizSlider variants are available. These are constructed and used similarly.
The short forms (v) or (h) are used below to identify these variants. See the
note above on callbacks.
Constructor mandatory positional argument:
location2-tuple defining position.
Optional keyword only arguments:
fontFont to use for any legends. DefaultNone: no legends will be drawn.heightDimension of the bounding box. Default 200 pixels (v), 30 (h).widthDimension of the bounding box. Default 30 pixels (v), 200 (h).divisionsNumber of graduations on the scale. Default 10.legendsA tuple of strings to display near the slider. TheseLabelinstances will be distributed evenly along its length, starting at the bottom (v) or left (h).fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.slidecolorColor for the slider. Defaults to the foreground color.borderWidth of border. DefaultNone: no border will be drawn. If a value (typically 2) is provided, a border line will be drawn around the control.cb_endCallback function which will run when the user stops touching the control.cbe_argsA list or tuple of arguments for the above callback. Default[].cb_moveCallback function which will run when the user moves the slider or the value is changed programmatically.cbm_argsA list or tuple of arguments for the above callback. Default[].valueThe initial value. Default 0.0: slider will be at the bottom (v), left (h).
Methods:
greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.valueOptional argumentsval(defaultNone). If supplied the slider moves to reflect the new value and thecb_movecallback is triggered. The method constrains the range to 0.0 to 1.0. Always returns the control's value.colorMandatory argcolorThe control is rendered in the selected color. This supports dynamic color changes
This emulates a rotary control capable of being rotated through a predefined arc.
Constructor mandatory positional argument:
location2-tuple defining position.
Optional keyword only arguments:
heightDimension of the square bounding box. Default 100 pixels.arcAmount of movement available. Default 2*PI radians (360 degrees).ticksNumber of graduations around the dial. Default 9.fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.colorFill color for the control knob. Default: no fill.borderWidth of border. DefaultNone: no border will be drawn. If a value (typically 2) is provided, a border line will be drawn around the control.cb_endCallback function which will run when the user stops touching the control.cbe_argsA list or tuple of arguments for the above callback. Default[].cb_moveCallback function which will run when the user moves the knob or the value is changed.cbm_argsA list or tuple of arguments for the above callback. Default[].valueInitial value. Default 0.0: knob will be at its most counter-clockwise position.
Methods:
greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.valueOptional argumentval. If set, adjusts the pointer to correspond to the new value. The move callback will run. The method constrains the range to 0.0 to 1.0. Always returns the control's value.
Drawn using graphics primitives. This provides for boolean data entry and
display. In the True state the control can show an 'X' or a filled block of
color.
Constructor mandatory positional argument:
location2-tuple defining position.
Optional keyword only arguments:
heightDimension of the square bounding box. Default 30 pixels.fillcolorFill color of checkbox whenTrue. DefaultNone: an 'X' will be drawn.fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.borderWidth of border. DefaultNone: no border will be drawn. If a value (typically 2) is provided, a border line will be drawn around the control.callbackCallback function which will run when the value changes.argsA list or tuple of arguments for the above callback. Default[].valueInitial value. DefaultFalse.
Methods:
greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.valueOptional boolean argumentval. If the provided value does not correspond to the control's current value, updates it; the checkbox is re-drawn and the callback executed. Always returns the control's value.
Drawn using graphics primitives. This emulates a pushbutton, with a callback
being executed each time the button is pressed. Buttons may be any one of three
shapes: CIRCLE, RECTANGLE or CLIPPED_RECT.
Constructor mandatory positional argument:
location2-tuple defining position.
Mandatory keyword only argument:
fontFont for button text
Optional keyword only arguments:
shapeCIRCLE, RECTANGLE or CLIPPED_RECT. Default CIRCLE.heightHeight of the bounding box. Default 50 pixels.widthWidth of the bounding box. Default 50 pixels.fillBoolean. IfTruethe button will be filled with the currentfgcolor.fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.litcolorIf provided the button will display this color for one second after being pressed.textShown in centre of button. Default: an empty string.callbackCallback function which runs when button is pressed.argsA list of arguments for the above callback. Default[].onreleaseDefaultTrue. IfTruethe callback will occur when the button is released otherwise it will occur when pressed.lp_callbackCallback to be used if button is to respond to a long press. DefaultNone.lp_argsA list of arguments for the above callback. Default[].
Method:
greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.
Class variables:
lit_timePeriod in seconds thelitcoloris displayed. Default 1.long_press_timePress duration for a long press. Default 1 second.
Drawn using graphics primitives.
A ButtonList groups a number of buttons together to implement a button which
moves between states each time it is pressed. For example it might toggle
between a green Start button and a red Stop button. The buttons are defined and
added in turn to the ButtonList object. Typically they will be the same size,
shape and location but will differ in color and/or text. At any time just one
of the buttons will be visible, initially the first to be added to the object.
Buttons in a ButtonList should not have callbacks. The ButtonList has its
own user supplied callback which will run each time the object is pressed.
However each button can have its own list of args. Callback arguments
comprise the currently visible button followed by its arguments.
Constructor argument:
callbackThe callback function. Default does nothing.
Methods:
add_buttonAdds a button to theButtonList. Arguments: as per theButtonconstructor. Returns the button object.greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.valueOptional argument: a button in the set. If supplied and the button is not active the currency changes to the supplied button and its callback is run. Always returns the active button.
Typical usage is as follows:
from tft.driver.constants import *
from tft.widgets.buttons import ButtonList
from tft.fonts import font14
def callback(button, arg):
print(arg)
table = [
{'fgcolor' : GREEN, 'shape' : CLIPPED_RECT, 'text' : 'Start', 'args' : ['Live']},
{'fgcolor' : RED, 'shape' : CLIPPED_RECT, 'text' : 'Stop', 'args' : ['Die']},
]
bl = ButtonList(callback)
for t in table: # Buttons overlay each other at same location
bl.add_button((10, 10), font = font14, fontcolor = BLACK, **t)Drawn using graphics primitives.
These comprise a set of buttons at different locations. When a button is pressed, it becomes highlighted and remains so until another button is pressed. A callback runs each time the current button is changed.
Constructor positional arguments:
highlightColor to use for the highlighted button. Mandatory.callbackCallback when a new button is pressed. Default does nothing.selectedIndex of initial button to be highlighted. Default 0.
Methods:
add_buttonAdds a button. Arguments: as per theButtonconstructor. Returns the Button instance.greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it, showing it in its new state.valueOptional argument: a button in the set. If supplied, and the button is not currently active, the currency changes to the supplied button and its callback is run. Always returns the currently active button.
Typical usage:
def callback(button, arg):
print(arg)
table = [
{'text' : '1', 'args' : ['1']},
{'text' : '2', 'args' : ['2']},
{'text' : '3', 'args' : ['3']},
{'text' : '4', 'args' : ['4']},
]
x = 0
rb = RadioButtons(callback, BLUE) # color of selected button
for t in table:
rb.add_button((x, 180), font = font14, fontcolor = WHITE,
fgcolor = LIGHTBLUE, height = 40, **t)
x += 60 # Horizontal row of buttonsDrawn using an icon file which must be imported before instantiating. A
checkbox may be implemented by setting the toggle argument True and using
an appropriate icon file. An IconButton instance has a state representing the
index of the current icon being displayed. User callbacks can interrogate this
by means of the value method described below.
Constructor mandatory positional argument:
location2-tuple defining position.
Mandatory keyword only argument:
icon_moduleName of the imported icon module.
Optional keyword only arguments:
flashNumeric, default 0. Ifvalue> 0, button will display icon[1] forvaluesecs.toggleBoolean, default False. If True, each time the button is pressed it will display each icon in turn (modulo number of icons in the module).stateInitial button state (index of icon displayed). Default 0.callbackCallback function which runs when button is pressed. Default does nothing.argsA list of arguments for the above callback. Default[].onreleaseDefaultTrue. IfTruethe callback will occur when the button is released.lp_callbackCallback to be used if button is to respond to a long press. DefaultNone.lp_argsA list of arguments for the above callback. Default[].
Methods:
greyed_outOptional boolean argumentvaldefaultNone. IfNonereturns the current 'greyed out' status of the control. Otherwise enables or disables it. If greyed out, the button is displayed with colors dimmed.valueArgumentvaldefaultNone. If the argument is provided and is a valid index not corresponding to the current button state, changes the button state and displays that icon. The callback will be executed. Always returns the button state (index of the current icon being displayed).
Class variables:
long_press_timePress duration for a long press. Default 1 second.
Drawn using an icon file which must be imported before instantiating. These comprise a set of buttons at different locations. When initially drawn, all but one button will be in state 0 (i.e. showing icon[0]). The selected button will be in state 1. When a button in state 0 is pressed, the set of buttons changes state so that it is the only one in state 1 (showing icon[1]). A callback runs each time the current button changes.
Constructor positional arguments:
callbackCallback when a new button is pressed. Default does nothing.selectedIndex of initial button to be highlighted. Default 0.
Methods:
add_buttonAdds a button to the set. Arguments: as per theIconButtonconstructor. Returns the button instance.valueArgumentvaldefaultNone. If the argument is provided which is an inactive button in the set, that button becomes active and the callback is executed. Always returns the button which is currently active.
Constructor mandatory positional argument:
location2-tuple defining position.
Mandatory keyword only arguments:
fontelementsA list or tuple of strings to display. Must have at least one entry.
Optional keyword only arguments:
widthControl width in pixels, default 250.valueIndex of currently selected list item. Default 0.borderSpace between border and contents. Default 2 pixels. IfNoneno border will be drawn.fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.select_colorBackground color for selected item in list. DefaultLIGHTBLUE.callbackCallback function which runs when a list entry is picked.argsA list of arguments for the above callback. Default[].
Methods:
valueArgumentvaldefaultNone. If the argument is provided which is a valid index into the list that entry becomes current and the callback is executed. Always returns the index of the currently active entry.textvalueArgumenttexta string defaultNone. If the argument is provided and is in the control's list, that item becomes current. Returns the current string, unless the arg was provided but did not correspond to any list item. In this event the control's state is not changed andNoneis returned.
The callback is triggered whenever a listbox item is pressed, even if that item is already currently selected.
A dropdown list. The list, when active, is drawn below the control. The height of the control is determined by the height of the font in use.
Constructor mandatory positional argument:
location2-tuple defining position.
Mandatory keyword only arguments:
fontelementsA list or tuple of strings to display. Must have at least one entry.
Optional keyword only arguments:
widthControl width in pixels, default 250.valueIndex of currently selected list item. Default 0.fgcolorColor of foreground (the control itself). Defaults to system color.bgcolorBackground color of object. Defaults to system background.fontcolorText color. Defaults to system text color.select_colorBackground color for selected item in list. DefaultLIGHTBLUE.callbackCallback function which runs when a list entry is picked.argsA list of arguments for the above callback. Default[].
Methods:
valueArgumentvaldefaultNone. If the argument is provided which is a valid index into the list that entry becomes current and the callback is executed. Always returns the index of the currently active entry.textvalueArgumenttexta string defaultNone. If the argument is provided and is in the control's list, that item becomes current. Returns the current string, unless the arg was provided but did not correspond to any list item. In this event the control's state is not changed andNoneis returned.
The callback is triggered if an item on the dropdown list is touched and that item is not currently selected (i.e. when a change occurs).
In general Screen objects occupy the entire physical display. The principal
exception to this is modal dialog boxes: these are rendered in a window which
accepts all touch events until it is closed. Dialog boxes are created by
instantiating an Aperture which is a Screen superclass. In effect this is a
window, but a 'micro' implementation lacking chrome beyond a simple border and
occupying a fixed location on the screen.
In use the user program creates a class subclassed from Aperture. This is
populated in the same way as per Screen subclasses. The class name can then
be passed to Screen.change to invoke the dialog box. The GUI provides a
simple way to build dialog boxes based on a small set of pushbuttons such as
'Yes/No/Cancel' in the form of the DialogBox class.
A convenience method locn is provided to assist in populating dialog boxes.
Given coordinates relative to the dialog box, it provides an absolute
location 2-tuple suitable as a constructor argument for control or
display classes. See dialog.py for example usage.
Provides a window for objects in a modal dialog box.
Constructor mandatory positional args:
location2-tuple defining the window position.heightDimensions in pixels.width
Optional keyword only args:
draw_borderBoolean, defaultTrue. If set a single pixel window border will be drawn.bgcolorBackground color of window. Defaults to system background.fgcolorColor of border. Defaults to system foreground.
Instance variables:
location2-tuple defining the window position.heightDimensions in pixels.width
Method:
locnArgs: x, y. Returns an absolute location 2-tuple given a pair of coordinates relative to the dialog box.
Class method:
valueOptional argvaldefaultNone. Provides a mechanism for returning the outcome of a dialog box which can be queried by the calling object. If the arg is provided, the value is set. The arg may be any Python object. Returns the value of theApertureclass. The callingScreencan query this by implementing anon_openmethod which callsAperture.value().
Simplifies building simple dialog boxes based on a set of pushbuttons. Any button press will close the dialog. The caller can determine which button was pressed. The size of the buttons and the width of the dialog box are calculated from the strings assigned to the buttons. This ensures that buttons are evenly spaced and identically sized.
Constructor mandatory positional args:
fontThe font for buttons and label.
Optional keyword only args:
elementsA list or tuple of 2-tuples. Each defines the text and color of a pushbutton, e.g.(('Yes', RED), ('No', GREEN)).location2-tuple defining the dialog box location. Default (20, 20).labelText for an optional label displayed in the centre of the dialog box. DefaultNone.bgcolorBackground color of window. DefaultDARKGREEN.buttonwidthMinimum width of buttons. Default 25. In general button dimensions are calculated from the size of the strings inelements.closebuttonBoolean. If set, aclosebutton will be displayed at the top RH corner of the dialog box.
Pressing any button closes the dialog and sets the Aperture value to the text
of the button pressed or 'Close' in the case of the close button.
For developers wishing to extend the library with new controls or displays, see this reference.