filebuttons=[]
fileframe=Frame(main,height=1080)
fileframe.pack(side="right",fill="both")
file_label=Label(fileframe, text="File Selected: ",font=('Times New Roman',24))
filecommands=[]
for file in get_files():
def temp():
file_label.config(bg="green",text=str("File Selected: "+file))
filecommands.append(temp)
filebuttons.append(Button(fileframe,activebackground="green",text=file, width=300))
for n in range(0,len(filebuttons)):
print(file)
filebuttons[n].config(command=filecommands[n])
for button in filebuttons:
button.pack(side="top")
这段代码被设计用来筛选一系列按钮,并在其中添加命令,用文件列表中的名称设置标签。但是,它只是将最终名称添加到所有按钮的所有命令中,这意味着它们都将标签设置为最后一个文件的文本。在
问题是'temp'函数使用'file'的当前值,而不是添加到列表时的值。这就是所谓的“后期绑定”。要解决这个问题,您需要生成一个closure,它将'file'的值烘焙到函数中。最简单的方法是使用
functools.partial
函数:相关问题 更多 >
编程相关推荐