将python变量传递给tcl

时间:2019-09-17 14:00:31

标签: python tkinter tcl

我正在python中使用Tkinter模块,并试图将python中的varibales传递给tcl

我知道我可以像

这样传递变量
tclsh = Tkinter.Tcl()
num = 1 
tclsh.eval("set num {}".format(1))

还有其他方法可以做到吗?由于我要传递许多变量,所以我希望有一种优雅的方式来传递变量

类似于此帖子Pass Python variables to `Tkinter.Tcl().eval()`

但是我尝试过,对我不起作用

2 个答案:

答案 0 :(得分:4)

我不认为可以将任何变量批量添加到tcl解释器中。但是,可以使用eval来代替call和字符串格式。与call相比,eval的优势在于,call将处理正确引用所有参数的细节。

call通过提供每个单词作为参数,使您可以像在tcl中一样调用tcl proc。您问题中的示例如下所示:

tclsh.call("set", "num", num)

但是,这仅适用于基本数据类型,例如字符串和数字。没有将列表和字典等对象自动转换为基础tcl数据类型的功能。

答案 1 :(得分:0)

这是一个稍微整洁的版本,它将对Tcl全局变量的访问包装为Python类:

import tkinter

class TclGlobalVariables(object):
    def __init__(self, tclsh):
        self.tclsh = tclsh

    def __setattr__(self, name, value):
        if name == "tclsh":
            object.__setattr__(self, name, value)
        else:
            # The call method is perfect for this job!
            self.tclsh.call("set", "::" + name, str(value))

    def __getattr__(self, name):
        if name == "tclsh":
            return object.__getattr__(self, name)
        else:
            # Tcl's [set] with only one argument reads the variable
            return self.tclsh.call("set", "::" + name)

演示:

tcl = TclGlobalVariables(tkinter.Tcl())
# Write to a Tcl variable
tcl.x = 123
# Read from it
print("From Python: x =", tcl.x)
# Show that it is really there by sending commands to the underlying Tcl interpreter
tcl.tclsh.eval('puts "From Tcl: x = $x"')
# Show that manipulations on the Tcl side are carried through
tcl.tclsh.eval('incr x 2')
print("From Python again: x =", tcl.x)
# Show that manipulations on the Python side are carried through
tcl.x += 3
tcl.tclsh.eval('puts "From Tcl again: x = $x"')

哪个产生以下输出:

From Python: x = 123
From Tcl: x = 123
From Python again: x = 125
From Tcl again: x = 128

请注意,这假设您仅在Tcl端访问简单的全局变量(不是命名空间变量,而不是数组),并且不处理类型映射。可能会进行更深层次的映射...但是会变得非常复杂。