假设我有以下内容Button
在 Python 中使用 Tkinter 制作:
import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)
方法action
当我按下按钮时调用,但是如果我想向该方法传递一些参数怎么办action
?
我尝试过以下代码:
button = Tk.Button(master=frame, text='press', command=action(someNumber))
这只是立即调用该方法,按下按钮不会执行任何操作。
See Python Argument Binders https://stackoverflow.com/questions/277922/python-argument-binders for standard techniques (not Tkinter-specific) for solving the problem. Working with callbacks in Tkinter (or other GUI frameworks) has some special considerations because the return value from the callback is useless.
If you try to create multiple Buttons in a loop, passing each one different arguments based on the loop counter, you may run into problems due to what is called late binding. Please see tkinter creating buttons in for loop passing command arguments https://stackoverflow.com/questions/10865116/ for details.