Version 4 of Python-Tcl-Interactions

Updated 2021-05-23 07:51:40 by drolli

Andreas Drollinger 2021-05-23 - This page shows how using the Tcl interpreter part of the Python Tkinter module.

The de factor standard GUI library for Python, Tkinter, contains a full-featured Tcl interpreter, together with the Tk GUI toolkit. This allows running Tcl commands from Python, as well as Python commands from Tcl after performing the some setup.

Tkinter is included with standard Linux, Windows and Mac OS X installation of Python.

Call Tcl from Python

The Tcl interpreter can be generated from the Python interpreter after importing the Tkinter module:

import tkinter
tcl = tkinter.Tcl()

The created Tcl interpreter exposes the method eval to run Tcl commands from the Python program:

res = tcl.eval('expr 12+23')

The result evaluated in the Tcl interpreter is returned to the Python interpreter:

res
=> '35'

Call Python from Tcl

This section shows the basics to run Python commands from the Tcl interpreter.

The Python functions that should be accessible from the Tcl interpreter have first to be registered as Tcl commands. For demonstration purposes, lets create a Python function that takes a unspecified number of arguments, and register it then as Tcl command. The registration function returns the Tcl function name:

def my_python_function(*argv):
        print("my_python_function", argv)

tcl_cmd = tcl.register(my_python_function)

The Tcl function name may be different from the Python function, so it is important to remember it:

tcl_cmd
=> '2013100028616my_python_function'

The exposed function can now be executed from the Tcl interpreter. Since my_python_function accepts an arbitrary number of arguments, various options are shown:

res = tcl.eval(tcl_cmd)
res = tcl.eval(tcl_cmd + ' 1')
res = tcl.eval(tcl_cmd + ' "Hello" "I" "am" "Jeff"')

Call Python from Tcl, use a more elegant registration command

The fact that the created Tcl command name differs from the Python name is a bit nasty. The following proposed custom registration command to register Tcl functions allows defining explicitly the name of the exposed Tcl function. The created Tcl function is simply renamed into the desired name. If no Tcl function name is provided, the Python function name is used:

def register(my_python_function, tcl_cmd_name=None):
    if tcl_cmd_name is None:
        tcl_cmd_name = my_python_function.__name__
    tcl_cmd = tcl.register(my_python_function)
    tcl.eval("rename " + tcl_cmd + " " + tcl_cmd_name)
    return tcl_cmd_name

Next, our Python function will again be registered, but this time with the custom registration command:

register(my_python_function)

And now, the Tcl function can be executed using using the original python function name:

res = tcl.eval("my_python_function")
res = tcl.eval("my_python_function 1")
res = tcl.eval("my_python_function Hello I am Jeff")

See also: