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. Thered,greenandblueshould be integers between 0 and 255 (inclusive).Color(hex_string)creates a color from a hexadecimal color string. For example,Color('#ff0000')is equivalent toColor(0xff, 0x00, 0x00)where0xffis hexadecimal notation for 255, and0x00is 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 = 255raises an exception.
-
classmethod
from_tcl(color_string)[source]¶ Color.from_tcl(color_string)returnsColor(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'. Usered,greenandblueif 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
Noneor'break'. In the above example,printreturnedNone. If the callback returns'break', two things are done differently:
-
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
-
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
Fontobject with a valid font name as an argument returns aNamedFontobject. 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.
sizeis an integer,underlineandoverstrikeare bools, and other attributes are strings. You can set values to these attributes only withNamedFont.The values of these attributes are looked up with
font actualin font(3tk), so they might differ from the values passed toFont(). 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. Passallow_at_prefix=Trueto get a list that includes the'@'fonts.
-
classmethod
from_tcl(font_description)[source]¶ Font.from_tcl(font_description)returnsFont(font_description).This is just for compatibility with type specifications.
-
metrics()[source]¶ Calls
font metricsdocumented 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.
- The values of
-
-
class
teek.NamedFont(name=None, **kwargs)[source]¶ A font that has a name in Tcl.
NamedFontis a subclass ofFont; 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
nameis not given, Tk will choose a font name that is not in use yet. Ifnameis 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
kwargsare values forfamily,size,weight,slant,underlineandoverstrikeattributes. 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'
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
TclVariableobjects in Python. If you want to set the value of the variable object,variable_object = new_valuedoesn’t work because that only sets a Python variable, and you needvariable_object.set(new_value)instead. Similarly,variable_object.get()returns the value of the Tcl variable.The
TclVariableclass is useless by itself. Usable variable classes are subclasses of it that overridetype_spec.Use
SomeUsableTclVarSubclass(name='asd')to create a variable object that represents a Tcl variable namedasd, orSomeUsableTclVarSubclass()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.
-
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.
-
wait()[source]¶ Waits for this variable to be modified.
The GUI remains responsive during the waiting. See
tkwait variablein tkwait(3tk) for details.
-
write_trace¶ A
Callbackthat 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).
-
Images¶
-
class
teek.Image(**kwargs)[source]¶ Represents a Tk photo image.
If you want to display an image to the user, use
Labelwith itsimageoption. 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
Imageobject withImage(...)callsimage create photofollowed 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
datakeyword argument is given, it should be abytesobject 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 == image2returnsimage1.to_tcl() == image2.to_tcl(). Image objects are also hashable.-
config¶ Similar to the widget config attribute.
-
blank()[source]¶ See
imageName blankin 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 toimage2.copy_from(). This means that it is possible to do some things with bothcopy()andcopy_from(), butcopy()is consistent with e.g.list.copy()anddict.copy().
-
copy_from(source_image, **kwargs)[source]¶ See
imageName copy sourceImagedocumented in photo(3tk).Options are passed as usual, except that
from=somethingis invalid syntax in Python, so this method supportsfrom_=somethinginstead. If you doimage1.copy_from(image2), theimageNamein photo(3tk) meansimage1, andsourceImagemeansimage2.
-
delete()[source]¶ Calls
image deletedocumented 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_bytes(format_, **kwargs)[source]¶ Like
write(), but returns the data as abytesobject instead of writing it to a file.The
format_argument can be any string that is compatible with the-formatoption ofimageName writedocumented in photo(3tk). All keyword arguments are same as forwrite().
-
in_use()[source]¶ True if any widget uses this image, or False if not.
This calls
image inusedocumented in image(3tk).
-
read(filename, **kwargs)[source]¶ See
imageName read filenamein photo(3tk).
-
redither()[source]¶ See
imageName reditherin photo(3tk).
-
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 getin photo(3tk).
-
transparency_set(x, y, is_transparent)[source]¶ Make the pixel at (x,y) transparent or not transparent.
See
imageName transparency setin photo(3tk) andtransparency_get().
-
width¶ The current width of the image as pixels.
Note that
image.widthis different fromimage.config['width'];image.widthchanges if the image’s size changes, butimage.config['width']often represents the width that the image had when it was first created. tl;dr: Usually it’s best to useimage.widthinstead ofimage.config['width'].
-
write(filename, **kwargs)[source]¶ See
imageName writein 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
pixelsattribute. Thevaluecan be an integer or float of pixels or a string that Tk_GetPixels(3tk) accepts; for example,123or'2i'.ScreenDistanceobjects 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.
-