函数不随 for 循环改变 python
Function not changing with for-loop python
我有一个 Tkinter GUI,如果单击一个按钮,它的文本将更改为列表中的相应项目 matches
。
列表matches
和列表buttons
未知。我的代码看起来像这样:
#Defining the buttons
buttons = []
for i in range(len(matches)):
buttons.append(Button(my_frame, text = " ",
font = ("Helvetica", 20), height = 1, width = 1,
command = lambda: change(i)))
def change(index):
if buttons[index]['text'] == matches[i]:
buttons[index]['text'] = " "
else:
buttons[index]['text'] = matches[i]
无论我按下哪个按钮,文本只会为最后一个按钮发生变化。我该如何解决这个问题?
那是因为lambda's late bindings
为避免这种情况,请使用 functools.partial
而不是 command = lambda: change(i)))
import functools
buttons = []
for i in range(len(matches)):
buttons.append(
Button(
my_frame,
text=" ",
font=("Helvetica", 20),
height=1,
width=1,
command=functools.partial(change, i)
)
)
另一个更简单的选择是替换
command = lambda: change(i)))
和
command = lambda i=i: change(i)))
我有一个 Tkinter GUI,如果单击一个按钮,它的文本将更改为列表中的相应项目 matches
。
列表matches
和列表buttons
未知。我的代码看起来像这样:
#Defining the buttons
buttons = []
for i in range(len(matches)):
buttons.append(Button(my_frame, text = " ",
font = ("Helvetica", 20), height = 1, width = 1,
command = lambda: change(i)))
def change(index):
if buttons[index]['text'] == matches[i]:
buttons[index]['text'] = " "
else:
buttons[index]['text'] = matches[i]
无论我按下哪个按钮,文本只会为最后一个按钮发生变化。我该如何解决这个问题?
那是因为lambda's late bindings
为避免这种情况,请使用 functools.partial
而不是 command = lambda: change(i)))
import functools
buttons = []
for i in range(len(matches)):
buttons.append(
Button(
my_frame,
text=" ",
font=("Helvetica", 20),
height=1,
width=1,
command=functools.partial(change, i)
)
)
另一个更简单的选择是替换
command = lambda: change(i)))
和
command = lambda i=i: change(i)))