Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以使用命令列表Tkinter创建按钮列表_Python_User Interface_Tkinter - Fatal编程技术网

Python 是否可以使用命令列表Tkinter创建按钮列表

Python 是否可以使用命令列表Tkinter创建按钮列表,python,user-interface,tkinter,Python,User Interface,Tkinter,这段代码设计用于筛选按钮列表,并向按钮列表中添加命令,使用文件列表中的名称设置标签。但是,它只是将最终名称添加到所有按钮的所有命令中,这意味着它们都将标签设置为最后一个文件的文本。问题在于,“temp”函数使用的是“file”的当前值,而不是添加到列表中时的值。这被称为“后期绑定”。要解决这个问题,您需要创建一个函数,它将“file”的值烘焙到函数中。最简单的方法是使用functools.partial函数: filebuttons=[] fileframe=Frame(main,height=

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

问题在于,“temp”函数使用的是“file”的当前值,而不是添加到列表中时的值。这被称为“后期绑定”。要解决这个问题,您需要创建一个函数,它将“file”的值烘焙到函数中。最简单的方法是使用
functools.partial
函数:

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”的当前值,而不是您将其添加到列表中时的值。这被称为“后期绑定”。要解决这个问题,您需要创建一个函数,它将“file”的值烘焙到函数中。最简单的方法是使用
functools.partial
函数:

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

非常感谢,这很好用。无法要求更好的答案:)。非常感谢,这非常有效。无法要求更好的答案:)。