在Tkinter.Tcl()中使用Python函数 [英] Using Python functions in Tkinter.Tcl()
问题描述
-
我有很多Python函数。我们称它们为
foo
,bar
和baz
。它们接受可变数量的字符串参数,并执行其他复杂的操作(例如访问网络)。
I have a bunch of Python functions. Let's call them
foo
,bar
andbaz
. 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.
这里是一个示例(摘自 Macports ):
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"
}
}
}
在这里, variant_issset
, reinplace
等等(Tcl内置函数除外)被实现为Python函数。 if
, foreach
, set
等是正常的Tcl构造。 post-configure
是一个Python函数,可以接受一个Tcl代码块,该代码块稍后可以执行(这显然会最终调用上述Python函数 )。
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").
这可以在Python中完成吗?如果是,怎么办?
Is this possible to do in Python? If so, how?
从Tkinter导入*; root = Tk(); root.tk.eval('puts [array get tcl_platform]')
是我所知道的唯一集成,这显然非常有限(更不用说它在Mac上启动X11服务器的事实)
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).
推荐答案
通过一些实验,我发现您可以执行以下操作来创建tcl解释器,注册python命令并从Tcl调用它:
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
这篇关于在Tkinter.Tcl()中使用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!