Version 0 of Python-Tcl-Interactions

Updated 2021-05-23 07:20:32 by drolli

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 is created from the Python program by importing Tkinter module and using its provide Tcl method:

import tkinter
tcl = tkinter.Tcl()

The create 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 allow therefore defining explicitly the name of the exposed Tcl function. The create 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 is again 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")