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

本文探讨了如何在Python中创建一个Tcl解释器,注册Python命令,并允许Tcl脚本通过这些Python函数进行操作。实例展示了如何使用Tcl调用Python函数并处理字符串参数。关键在于理解如何在两种语言间传递和执行代码块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a bunch of Python functions. Let's call them foo, bar and baz. They accept variable number of string arguments and does other sophisticated things (like accessing the network).

I want the "user" (let's assume he is only familiar with Tcl) to write scripts in Tcl using those functions.

Here's an example (taken from Macports) that user can come up with:

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"

}

}

}

Here, variant_issset, reinplace are so on (other than Tcl builtins) are implemented as Python functions. if, foreach, set, etc.. are normal Tcl constructs. post-configure is a Python function that accepts, well, a Tcl code block that can later be executed (which in turns would obviously end up calling the above mentioned Python "functions").

Is this possible to do in Python? If so, how?

from Tkinter import *; root= Tk(); root.tk.eval('puts [array get tcl_platform]') is the only integration I know of, which is obviously very limited (not to mention the fact that it starts up X11 server on mac).

解决方案

With a little experimentation I discovered you can do something like this to create a tcl interpreter, register a python command, and call it from 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

When I run the above code I get:

$ python2.5 /tmp/example.py

pycommand args: one, two, three

tcl result: None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值