在Tkinter.Tcl()中使用Python函数

Rei*_*ica 3 python integration dsl tcl

  1. 我有一堆Python函数.让我们给他们打电话foo,barbaz.它们接受可变数量的字符串参数,并执行其他复杂的操作(如访问网络).

  2. 我希望"用户"(让我们假设他只熟悉Tcl)使用这些函数在Tcl中编写脚本.

以下是用户可以提出的一个示例(取自Macports):

post-configure {
    if {[variant_isset universal]} {
        set conflags ""
        foreach arch ${configure.universal_archs} {
            if {${arch} == "i386"} {append conflags "x86 "} else {
                if {${arch} == "ppc64"} {append conflags "ppc_64 "} else {
                    append conflags ${arch} " "
                }
            }
        }

        set profiles [exec find ${worksrcpath} -name "*.pro"]
        foreach profile ${profiles} {
            reinplace -E "s|^(CONFIG\[ \\t].*)|\\1 ${conflags}|" ${profile}

            # Cures an isolated case
            system "cd ${worksrcpath}/designer && \
                    ${qt_dir}/bin/qmake -spec ${qt_dir}/mkspecs/macx-g++ -macx \
                    -o Makefile python.pro"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里,variant_issset,reinplace是如此(比Tcl的内建其他)上被实现为Python函数.if,foreach,set,等都是正常的Tcl结构.post-configure是一个Python函数,它接受一个Tcl代码块,以后可以执行(反过来显然最终会调用上面提到的Python"函数").

这可以用Python做吗?如果是这样,怎么样?

from Tkinter import *; root= Tk(); root.tk.eval('puts [array get tcl_platform]') 是我所知道的唯一集成,显然非常有限(更不用说它在mac上启动X11服务器的事实).

Bry*_*ley 7

通过一些实验,我发现你可以做这样的事情来创建一个tcl解释器,注册一个python命令,并从Tcl调用它:

import Tkinter

# create the tcl interpreter
tcl = Tkinter.Tcl()

# define a python function
def pycommand(*args):
    print "pycommand args:", ", ".join(args)

# register it as a tcl command:
tcl_command_name = "pycommand"
python_function = pycommand
cmd = tcl.createcommand(tcl_command_name, python_function)

# call it, and print the results:
result = tcl.eval("pycommand one two three")
print "tcl result:", result
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到:

$ python2.5 /tmp/example.py
pycommand args: one, two, three
tcl result: None
Run Code Online (Sandbox Code Playgroud)