可以用命令列表Tkin创建一个按钮列表吗

2024-09-28 22:02:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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")

这段代码被设计用来筛选一系列按钮,并在其中添加命令,用文件列表中的名称设置标签。但是,它只是将最终名称添加到所有按钮的所有命令中,这意味着它们都将标签设置为最后一个文件的文本。在


Tags: textinconfigforgreentempsidelabel
1条回答
网友
1楼 · 发布于 2024-09-28 22:02:20

问题是'temp'函数使用'file'的当前值,而不是添加到列表时的值。这就是所谓的“后期绑定”。要解决这个问题,您需要生成一个closure,它将'file'的值烘焙到函数中。最简单的方法是使用functools.partial函数:

from functools import partial

for file in get_files():
    closure = partial(file_label.config, bg="green", text=str("File Selected: "+file))
    button = Button(fileframe,activebackground="green",text=file, width=300, command=closure)
    button.pack(side="top")

相关问题 更多 >