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

标签 python integration tcl dsl

  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"
        }
    }
}

在这里,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 服务器的事实)。

最佳答案

通过一些实验,我发现你可以做这样的事情来创建一个 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

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

$ python2.5 /tmp/example.py
pycommand args: one, two, three
tcl result: None

关于python - 在 Tkinter.Tcl() 中使用 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2701909/

相关文章:

python - 该 ROC 曲线图看起来很奇怪(sklearn SVC)

python - "ImportError: file_cache is unavailable"为 Google 服务帐户 file_cache 使用 Python 客户端时

python - 属性错误 : module 'MySQLdb.constants.FIELD_TYPE' has no attribute 'JSON' while migrating in Django

debugging - Tcl 程序,其行为根据 "puts"语句而变化

tcl - TclInvalidateStringRep() 不应该重置长度吗?

由名称管道驱动的 Tcl/Expect 脚本意外地 block /缓冲区输出

python - 使用 python 3 在 docx 文件中插入注释

python - 如何在 Python 中使用 dorpi5 或 dop853

java - 如何将 drools 集成到 Jersey 休息 Web 服务中

ios - 是否有任何公开文件表明 Facebook 测试用户不能使用 iOS 6 集成?