Interpreter#

Tkinter is a thin layer over a Tcl interpreter, and every widget carries a handle to it. Most of the time that boundary is invisible. These methods are the places you cross it deliberately: turning Tcl’s values into Python ones, exposing a Python function so Tcl can call it, and asking which Tk you are running on.

Converting Tk values#

Tk hands some values back as strings, and its idea of a boolean is broader than Python’s — "yes", "true", "1" and "on" are all true. These helpers apply Tk’s rules, so use them instead of int() or truth-testing a string: in Python every non-empty string is truthy, including "0" and "false".

getboolean(s)

Convert a Tk boolean to a Python bool.

Parameters:

s – a Tk boolean — "yes"/"no", "true"/"false", "on"/"off", 1/0.

Returns:

the value.

Return type:

bool

Raises:

ValueError – if s isn’t a recognized boolean.

getint(s)

Convert a Tk value to a Python int.

Parameters:

s – the value to convert.

Return type:

int

getdouble(s)

Convert a Tk value to a Python float.

Parameters:

s – the value to convert.

Return type:

float

Exposing a callback to Tcl#

A few Tk options take a Tcl command name rather than a Python callable — most notably validatecommand, which also needs substitution codes like %P. register wraps a Python function as a Tcl command and gives you back its name.

check = app.register(lambda proposed: proposed.isdigit())
ttk.Entry(app, validate="key", validatecommand=(check, "%P"))

Validation does this for you — reach for register only when you are wiring a Tcl-level option by hand.

register(func, subst=None, needcleanup=1)

Register a Python callable as a Tcl command.

Parameters:
  • func – the callable to expose.

  • subst – an optional callable applied to the arguments first.

  • needcleanup – whether to delete the command when the widget is destroyed.

Returns:

the Tcl command name to hand to the option.

Return type:

str

deletecommand(name)

Delete a Tcl command created by register, releasing the Python callable. Calling the name afterward raises TclError.

Parameters:

name (str) – the command name register returned.

Returns:

None.

Which Tk is this#

info_patchlevel()

The exact Tk version behind this interpreter — useful when a feature is gated on it.

Returns:

a version tuple (major, minor, micro, releaselevel, serial); str() of it gives "8.6.17".

See also

  • Configuration — reading option values, which is where Tk’s types usually surface.

  • Validation — the wrapper around register you normally want.