代码之家  ›  专栏  ›  技术社区  ›  Sridhar Ratnakumar

在tkinter.tcl()中使用python函数

  •  3
  • Sridhar Ratnakumar  · 技术社区  · 16 年前
    1. 我有很多python函数。我们叫他们 foo , bar baz . 它们接受可变数目的字符串参数,并执行其他复杂的操作(如访问网络)。

    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服务器)。

    2 回复  |  直到 13 年前
        1
  •  7
  •   Bryan Oakley    16 年前

    通过一些实验,我发现您可以这样做来创建一个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
    
        2
  •  -1
  •   Vince S    14 年前

    @布莱恩-为了得到正确的结果我不得不做实验

    from Tkinter import Tcl
    tcl = Tcl()
    result = tcl.eval(' puts "hello, world" ')
    

    注意单引号和双引号的位置。这给了我预期的结果:你好,世界

    单引号或双引号的任何其他组合都会导致以下回溯:

      File "<stdin>", line 1, in <module>
    _tkinter.TclError: can not find channel named "hello,"
    

    ---水力压裂