如何在 Python 中绑定 Tcl 回调

How to bind Tcl callbacks in Python

我在读 msgcat

引自文档:

::msgcat::mcunknown locale src-string ?arg arg ...?

This routine is called by ::msgcat::mc in the case when a translation for src-string is not defined in the current locale. The default action is to return src-string passed by format if there are any arguments. This procedure can be redefined by the application, for example to log error messages for each unknown string. The ::msgcat::mcunknown procedure is invoked at the same stack context as the call to ::msgcat::mc. The return value of ::msgcat::mcunknown is used as the return value for the call to ::msgcat::mc. Note that this routine is only called if the concerned package did not set a package locale unknown command name.

如何使用 tkinter 在我的 Python 代码中创建 ::msgcat::mcunknown 处理程序?

需要两个步骤。首先,您使用 register 方法建立从 Tcl 端到您的代码的桥梁。

def mcunknown_handler(locale, src, *args):
    # Stuff in here

handler = tcl.register(mcunknown_handler)

然后你需要让 Tcl 端在正确的时间调用它。这需要一点小心,因为我们不想在 Tcl 端重命名命令,因为 Python 绑定是如何工作的(里面有点乱)。幸运的是,我们可以轻松地将一个 Tcl 命令委托给另一个命令。

tcl.eval("package require msgcat; interp alias {} msgcat::mcunknown {} " + handler)

总的来说:

>>> import tkinter
>>> tcl = tkinter.Tcl()
>>> def mcunknown_handler(locale, src, *args):
...     print("Hello", locale, src, "World")
...     return src
... 
>>> handler = tcl.register(mcunknown_handler)
>>> tcl.eval("package require msgcat; interp alias {} msgcat::mcunknown {} " + handler)
'msgcat::mcunknown'
>>> tcl.eval("msgcat::mc foo bar")
Hello en_gb foo World
'foo'

当然,您的语言环境可能不同。