Miscellaneous Classes

This page contains documentation of classes that represent different kinds of things.

Colors

class teek.Color(*args)[source]

Represents an RGB color.

There are a few ways to create color objects:

  • Color(red, green, blue) creates a new color from an RGB value. The red, green and blue should be integers between 0 and 255 (inclusive).
  • Color(hex_string) creates a color from a hexadecimal color string. For example, Color('#ff0000') is equivalent to Color(0xff, 0x00, 0x00) where 0xff is hexadecimal notation for 255, and 0x00 is 0.
  • Color(color_name) creates a color object from a Tk color. There is a long list of color names in colors(3tk).

Examples:

>>> Color(255, 255, 255)    # r, g and b are all maximum, this is white
<Color '#ffffff': red=255, green=255, blue=255>
>>> Color('white')     # 'white' is a Tk color name
<Color 'white': red=255, green=255, blue=255>

The string argument things are implemented by letting Tk interpret the color, so all of the ways to define colors as strings shown in Tk_GetColor(3tk) are supported.

Color objects are hashable, and they can be compared with ==:

>>> Color(0, 0, 255) == Color(0, 0, 255)
True
>>> Color(0, 255, 0) == Color(0, 0, 255)
False

Color objects are immutable. If you want to change a color, create a new Color object.

red
green
blue

These are the values passed to Color().

>>> Color(0, 0, 255).red
0
>>> Color(0, 0, 255).green
0
>>> Color(0, 0, 255).blue
255

Assigning to these like some_color.red = 255 raises an exception.

classmethod from_tcl(color_string)[source]

Color.from_tcl(color_string) returns Color(color_string).

This is just for compatibility with type specifications.

to_tcl()[source]

Return this color as a Tk-compatible string.

The string is often a hexadecimal '#rrggbb' string, but not always; it can be also e.g. a color name like 'white'. Use red, green and blue if you want a consistent representation.

>>> Color(255, 0, 0).to_tcl()
'#ff0000'
>>> Color('red').to_tcl()
'red'
>>> Color('red') == Color(255, 0, 0)
True

Callbacks

class teek.Callback[source]

An object that calls functions.

Example:

>>> c = Callback()
>>> c.connect(print, args=["hello", "world"])
>>> c.run()   # runs print("hello", "world"), usually teek does this
hello world
>>> c.connect(print, args=["hello", "again"])
>>> c.run()
hello world
hello again
connect(function, args=(), kwargs=None)[source]

Schedule callback(*args, **kwargs) to run.

If some arguments are passed to run(), they will appear before the args given here. For example:

>>> c = Callback()
>>> c.connect(print, args=['hello'], kwargs={'sep': '-'})
>>> c.run(1, 2)     # print(1, 2, 'hello', sep='-')
1-2-hello

The callback may return None or 'break'. In the above example, print returned None. If the callback returns 'break', two things are done differently:

  1. No more connected callbacks will be ran.
  2. run() returns 'break', so that the code that called run() knows that one of the callbacks returned 'break'. This is used in bindings.
disconnect(function)[source]

Undo a connect() call.

Note that this method doesn’t do anything to the args and kwargs passed to connect(), so when disconnecting a function connected multiple times with different arguments, only the first connection is undone.

>>> c = Callback()
>>> c.connect(print, ["hello"])
>>> c.connect(print, ["hello", "again"])
>>> c.run()
hello
hello again
>>> c.disconnect(print)
>>> c.run()
hello
run(*args)[source]

Run the connected callbacks.

If a callback returns 'break', this returns 'break' too without running more callbacks. If all callbacks run without returning 'break', this returns None. If a callback raises an exception, a traceback is printed and None is returned.

Fonts

There are different kinds of fonts in Tk:

  • Named fonts are mutable; if you set the font of a widget to a named font and you then change that named font (e.g. make it bigger), the widget’s font will change as well.
  • Anonymous fonts don’t work like that, but they are handy if you don’t want to create a font object just to set the font of a widget.

For example, if you have Label

>>> window = teek.Window()
>>> label = teek.Label(window, "Hello World")
>>> label.pack()

…and you want to make its text bigger, you can do this:

>>> label.config['font'] = ('Helvetica', 20)

This form is the teek equivalent of the alternative [3] in the FONT DESCRIPTIONS part of font(3tk). All of the other font descriptions work as well.

If you then get the font of the label, you get a teek.Font object:

>>> label.config['font']
Font('Helvetica 20')

With a named font, the code looks like this:

>>> named_font = teek.NamedFont(family='Helvetica', size=20)
>>> label.config['font'] = named_font
>>> named_font.size = 50    # even bigger! label will use this new size automatically

Of course, Font and NamedFont objects can also be set to label.config['font'].

class teek.Font(font_description)[source]

Represents an anonymous font.

Creating a Font object with a valid font name as an argument returns a NamedFont object. For example:

>>> teek.Font('Helvetica 12')  # not a font name
Font('Helvetica 12')
>>> teek.Font('TkFixedFont')   # special font name for default monospace font
NamedFont('TkFixedFont')
>>> teek.NamedFont('TkFixedFont')    # does the same thing
NamedFont('TkFixedFont')
family
size
weight
slant
underline
overstrike

See font(3tk) for a description of each attribute. size is an integer, underline and overstrike are bools, and other attributes are strings. You can set values to these attributes only with NamedFont.

The values of these attributes are looked up with font actual in font(3tk), so they might differ from the values passed to Font(). For example, the 'Helvetica' family can meany any Helvetica-like font, so this line of code gives different values platform-specifically:

>>> teek.Font('Helvetica 12').family     # doctest: +SKIP
'Nimbus Sans L'
classmethod families(*, allow_at_prefix=False)[source]

Returns a list of font families as strings.

On Windows, some font families start with '@'. I don’t know what those families are and how they might be useful, but most of the time tkinter users (including me) ignore those, so this method ignores them by default. Pass allow_at_prefix=True to get a list that includes the '@' fonts.

classmethod from_tcl(font_description)[source]

Font.from_tcl(font_description) returns Font(font_description).

This is just for compatibility with type specifications.

measure(text)[source]

Calls font measure documented in font(3tk), and returns an integer.

metrics()[source]

Calls font metrics documented in font(3tk), and returns a dictionary that has at least the following keys:

  • The values of 'ascent', 'descent' and 'linespace' are integers.
  • The value of 'fixed' is True or False.
to_named_font()[source]

Returns a NamedFont object created from this font.

If this font is already a NamedFont, a copy of it is created and returned.

to_tcl()[source]

Returns the font description passed to Font(font_description).

class teek.NamedFont(name=None, **kwargs)[source]

A font that has a name in Tcl.

NamedFont is a subclass of Font; that is, all NamedFonts are Fonts, but not all Fonts are NamedFonts:

>>> isinstance(teek.NamedFont('toot'), teek.Font)
True
>>> isinstance(teek.Font('Helvetica 12'), teek.NamedFont)
False

If name is not given, Tk will choose a font name that is not in use yet. If name is given, it can be a name of an existing font, but if a font with the given name doesn’t exist, it’ll be created instead.

The kwargs are values for family, size, weight, slant, underline and overstrike attributes. For example, this…

shouting_font = teek.NamedFont(size=30, weight='bold')

…does the same thing as this:

shouting_font = teek.NamedFont()
shouting_font.size = 30
shouting_font.weight = 'bold'
delete()[source]

Calls font delete.

The font object is useless after this, and most things will raise TclError.

classmethod get_all_named_fonts()[source]

Returns a list of all NamedFont objects.

Tcl Variable Objects

class teek.TclVariable(*, name=None)[source]

Represents a global Tcl variable.

In Tcl, it’s possible to e.g. run code when the value of a variable changes, or wait until the variable is set. Python’s variables can’t do things like that, so Tcl variables are represented as TclVariable objects in Python. If you want to set the value of the variable object, variable_object = new_value doesn’t work because that only sets a Python variable, and you need variable_object.set(new_value) instead. Similarly, variable_object.get() returns the value of the Tcl variable.

The TclVariable class is useless by itself. Usable variable classes are subclasses of it that override type_spec.

Use SomeUsableTclVarSubclass(name='asd') to create a variable object that represents a Tcl variable named asd, or SomeUsableTclVarSubclass() to let teek choose a variable name for you.

type_spec

This class attribute should be set to a type specification of what get() returns.

classmethod from_tcl(varname)[source]

Creates a variable object from a name string.

See Type Specifications for details.

get()[source]

Returns the value of the variable.

set(new_value)[source]

Sets the value of the variable.

The value does not need to be of the variable’s type; it can be anything that can be converted to tcl.

to_tcl()[source]

Returns the variable name as a string.

wait()[source]

Waits for this variable to be modified.

The GUI remains responsive during the waiting. See tkwait variable in tkwait(3tk) for details.

write_trace

A Callback that runs when the value of the variable changes.

The connected functions will be called with one argument, the variable object. This is implemented with trace add variable, documented in trace(3tcl).

class teek.StringVar
class teek.IntVar
class teek.FloatVar
class teek.BooleanVar

Handy TclVariable subclasses for variables with str, int, float and bool values, respectively.

Images

class teek.Image(**kwargs)[source]

Represents a Tk photo image.

If you want to display an image to the user, use Label with its image option. See examples/image.py.

Image objects are wrappers for things documented in image(3tk) and photo(3tk). They are mutable, so you can e.g. set a label’s image to an image object and then later change that image object; the label will update automatically.

Note

PNG support was added in Tk 8.6. Use GIF images if you want backwards compatibility with Tk 8.5.

If you want to create a program that can read as many different kinds of images as possible, use teek.extras.image_loader.

Creating a new Image object with Image(...) calls image create photo followed by the options in Tcl. See image(3tk) for details.

Keyword arguments are passed as options to photo(3tk) as usual, except that if a data keyword argument is given, it should be a bytes object of data that came from e.g. an image file opened with 'rb'; it will be automatically converted to base64.

Image objects can be compared with ==, and they compare equal if they represent the same Tk image; that is, image1 == image2 returns image1.to_tcl() == image2.to_tcl(). Image objects are also hashable.

config

Similar to the widget config attribute.

blank()[source]

See imageName blank in photo(3tk).

copy(**kwargs)[source]

Create a new image with the same content as this image so that changing the new image doesn’t change this image.

This creates a new image and then calls copy_from(), so that this…

image2 = image1.copy()

…does the same thing as this:

image2 = teek.Image()
image2.copy_from(image1)

Keyword arguments passed to image1.copy() are passed to image2.copy_from(). This means that it is possible to do some things with both copy() and copy_from(), but copy() is consistent with e.g. list.copy() and dict.copy().

copy_from(source_image, **kwargs)[source]

See imageName copy sourceImage documented in photo(3tk).

Options are passed as usual, except that from=something is invalid syntax in Python, so this method supports from_=something instead. If you do image1.copy_from(image2), the imageName in photo(3tk) means image1, and sourceImage means image2.

delete()[source]

Calls image delete documented in image(3tk).

The image object is useless after this, and most things will raise TclError.

classmethod from_tcl(name)[source]

Create a new image object from the name of a Tk image.

See Type Specifications for details.

get(x, y)[source]

Returns the Color of the pixel at (x,y).

classmethod get_all_images()[source]

Return all existing images as a list of Image objects.

get_bytes(format_, **kwargs)[source]

Like write(), but returns the data as a bytes object instead of writing it to a file.

The format_ argument can be any string that is compatible with the -format option of imageName write documented in photo(3tk). All keyword arguments are same as for write().

height

See width.

in_use()[source]

True if any widget uses this image, or False if not.

This calls image inuse documented in image(3tk).

read(filename, **kwargs)[source]

See imageName read filename in photo(3tk).

redither()[source]

See imageName redither in photo(3tk).

to_tcl()[source]

Returns the Tk name of the image as a string.

transparency_get(x, y)[source]

Check if the pixel at (x,y) is transparent, and return a bool.

The x and y are pixels, as integers. See imageName transparency get in photo(3tk).

transparency_set(x, y, is_transparent)[source]

Make the pixel at (x,y) transparent or not transparent.

See imageName transparency set in photo(3tk) and transparency_get().

width

The current width of the image as pixels.

Note that image.width is different from image.config['width']; image.width changes if the image’s size changes, but image.config['width'] often represents the width that the image had when it was first created. tl;dr: Usually it’s best to use image.width instead of image.config['width'].

write(filename, **kwargs)[source]

See imageName write in photo(3tk).

See also

Use get_bytes() if you don’t want to create a file.

Screen Distance Objects

class teek.ScreenDistance(value)[source]

Represents a Tk screen distance.

If you don’t know or care what screen distances are, use the pixels attribute. The value can be an integer or float of pixels or a string that Tk_GetPixels(3tk) accepts; for example, 123 or '2i'.

ScreenDistance objects are hashable, and they can be compared with each other:

>>> funny_dict = {ScreenDistance(1): 'lol'}
>>> funny_dict[ScreenDistance(1)]
'lol'
>>> ScreenDistance('1c') == ScreenDistance('1i')
False
>>> ScreenDistance('1c') < ScreenDistance('1i')
True
pixels

The number of pixels that this screen distance represents as an int.

This is implemented with winfo pixels, documented in winfo(3tk).

fpixels

The number of pixels that this screen distance represents as a float.

This is implemented with winfo fpixels, documented in winfo(3tk).

classmethod from_tcl(value_string)[source]

Creates a screen distance object from a Tk screen distance string.

See Type Specifications for details.

to_tcl()[source]

Return the value as a string.