button1 = tkinter.Button(frame, text="Say hi", command=print)
button2 = tkinter.Button(frame, text="foo", command=print)
button3 = tkinter.Button(frame, text="bar", command=print)

你可能发现了我程序中的漏洞:print无法指定参数。这使整件事变得毫无用处和错误。很明显,有点像
command=print("foo")

将在对象实际实例化时调用该函数,并使该函数调用的返回值(如果有)。(不是我想要的)
那么,如何在上述场景中指定参数,并避免为每个按钮定义单独的command函数?

最佳答案

一个简单的解决方案是使用lambda,它允许您创建匿名函数。

button1 = tkinter.Button(frame, text="Say hi", command=lambda: print("Say hi")
button2 = tkinter.Button(frame, text="foo", command=lambda: print("foo"))
button3 = tkinter.Button(frame, text="bar", command=lambda: print("bar"))

另一种选择是使用functools.partial,在这个答案中有一点解释:https://stackoverflow.com/a/2297423/7432

10-01 15:58
查看更多