Python 如何在tkinter中提供单独的按钮功能,但所有按钮都是在for循环中制作的
这是我的代码,但唯一附加的是目录中的一个文件,我可以给每个按钮一个特定的实体,以便以后调用它吗Python 如何在tkinter中提供单独的按钮功能,但所有按钮都是在for循环中制作的,python,tkinter,Python,Tkinter,这是我的代码,但唯一附加的是目录中的一个文件,我可以给每个按钮一个特定的实体,以便以后调用它吗 对于类名中的fle: cur#u but=tk.按钮(根,宽度=but_width,高度=高度,bg='#8a081e',命令=lambda fle=fle:print(fle)) cur\u but.place(x=0,y=add\u键) 添加键+=但添加高度 但您应该真正考虑如何格式化代码(因为在我看来,它看起来很棒,因为它不可读) 无论如何,另一种选择是使用partial,因此在开始时,您将:
对于类名中的fle:
cur#u but=tk.按钮(根,宽度=but_width,高度=高度,bg='#8a081e',命令=lambda fle=fle:print(fle))
cur\u but.place(x=0,y=add\u键)
添加键+=但添加高度
但您应该真正考虑如何格式化代码(因为在我看来,它看起来很棒,因为它不可读)
无论如何,另一种选择是使用partial,因此在开始时,您将:
从functools导入部分
然后使用:
command=partial(打印,fle)
将您的功能替换为:
import os
import tkinter as tk
used_list = []
image_list= os.listdir("Faces")
class_names = []
for file in image_list:
class_names.append(os.path.splitext(file)[0])
add_key = 0
width = '400'
height = '800'
width_int = int(width)
height_int = int(height)
but_height = height_int / len(image_list)
but_width = width_int / len(image_list)
lbl_add = but_height / 2
but_width = int(but_width)
but_height = int(but_height)
root = tk.Tk()
root.geometry(f"{width}x{height}")
for fle in class_names:
def fun2():
print(fle)
cur_but = tk.Button(root,width = but_width,height = height_int,bg='#8a081e',command = lambda:[fun2()])
cur_but.place(x = 0,y = add_key)
add_key += but_height
for thing in class_names:
txt = tk.Label(root,text = f"{thing}",bg='#8a081e',fg = 'white')
txt.place(x = (width_int / 2) - 30,y =lbl_add)
lbl_add += but_height
big_text = tk.Label(root,text = ' Pick Two Files to see if both people have matching faces',width = 100,height = 5, anchor='w')
big_text.place(x=0,y=0)
root.mainloop()
另外,将您的命令:
command=lambda:fun2(fle)
替换为command=lambda i=fle:fun2(i)
为什么要将代码打包在一起?如果在两行之间留出空行,则更易于阅读和调试。特别是在函数之间:根据PEP 8,函数定义前后应该有两个空行。这是否回答了您的问题?谢谢你这么多的工作,我已经被困在这个这么长时间:)Np,请接受这个答案,如果它解决了你的问题@阿玛尼亚兹
def fun2(flee):
print(flee)