如果您正在询问如何创建使用“数据”字段的绑定(即:%d替换),则必须调用一些tcl代码才能实现.这需要两个步骤:创建一个调用python函数的tcl命令,并使用tcl将事件绑定到该函数.
首先,让我们创建一个python程序,它可以创建一个事件并设置“data”字段(这假定存在一个名为root的全局变量,我们稍后会创建它).调用此函数时,它将生成一个自定义事件,其中数据字段由字符串填充.
def create_custom_event():
root.event_generate("<>", data="Hello, world")
接下来,让我们创建一个程序,在按下按钮时调用该功能
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="click me", command=create_custom_event)
button.pack(side="top", padx=20, pady=20)
root.mainloop()
接下来,我们需要创建一个在生成事件时调用的函数.我们计划设置数据字段,因此该函数必须接受一个值,即%d替换的值.
def callback(detail):
print("detail: %s" % detail)
因为你想使用%d替换,我们必须通过Tcl创建绑定.但是,tcl不会自动知道我们的python函数,因此我们必须使用tcl注册该函数.然后,只需通过tcl接口调用bind来设置绑定.
然后,第一步是注册回调.我们已经创建了这个函数,我们只需要创建一个调用这个函数的tcl函数.幸运的是,tkinter使用register命令为我们提供了一种方法.你这样使用它:
cmd = root.register(callback)
这需要一个python函数(在这种情况下是回调),并创建一个tcl命令来调用该函数. register返回我们存储在名为cmd的变量中的tcl命令的名称(名称无关紧要)
接下来,我们需要通过Tcl设置绑定来调用此命令.如果我们在实际的tcl脚本中执行此操作,该命令将看起来像这样(其中“.”表示根窗口):
bind . <> {callback %d}
python等价物是这样的:
root.tk.call("bind", root, "<>", cmd + " %d")
请注意,调用参数和tcl参数之间存在1:1的对应关系.方便的是,tkinter小部件的默认字符串表示形式是内部tcl名称,因此我们可以直接在调用中使用小部件(但是,迂腐地说,也许我们应该使用str(root)).
把它们放在一起给了我们这个,当你点击按钮时会打印出“细节:Hello,world”:
import tkinter as tk
def callback(detail):
print("detail: %s" % detail)
def create_custom_event():
root.event_generate("<>", data="Hello, world")
root = tk.Tk()
button = tk.Button(root, text="click me", command=create_custom_event)
button.pack(side="top", padx=20, pady=20)
cmd = root.register(callback)
root.tk.call("bind", root, "<>", cmd + " %d")
root.mainloop()