Python 如何使用for循环为按钮提供功能?

Python 如何使用for循环为按钮提供功能?,python,for-loop,button,tkinter,calculator,Python,For Loop,Button,Tkinter,Calculator,所以我想用for循环在Tkinter中给我的按钮一个函数。当我这样做的时候,我得到一个错误信息,这些按钮没有定义。我尝试了几件事,但无论如何都没有成功。如果你能帮助我,我会很高兴的。顺便说一下,这是一台计算器 这是循环的外观: for s in range(0, 10): def add_(s): entry_box.insert(1000, str(number)) 这就是我制作按钮的方法: button_zero = Button(main_window, tex

所以我想用for循环在Tkinter中给我的按钮一个函数。当我这样做的时候,我得到一个错误信息,这些按钮没有定义。我尝试了几件事,但无论如何都没有成功。如果你能帮助我,我会很高兴的。顺便说一下,这是一台计算器

这是循环的外观:

for s in range(0, 10):
    def add_(s):
         entry_box.insert(1000, str(number))
这就是我制作按钮的方法:

button_zero = Button(main_window, text='0', padx=30, pady=25, command=add_0)
button_zero.place(x=67,y=430)

根据您提供的信息,button中的命令参数不等于任何定义的函数。也许只是一个打字错误:

for s in range(0,10):
    def add_0(s):
        entry_box.insert(1000,str(number))
如果您有10个按钮(0-9),所有这些按钮都在
输入框
中插入一个数字,我将创建一个函数工厂

def add_(s):
    def wrapped():
        entry_box.insert(1000, s)
    return wrapped
调用
add_u2
时,返回一个函数,该函数在调用时将
2
添加到输入框中

add_2 = add_("2")
add_2()  # adds 2 to the entry box, returns None
然后,您可以遍历按钮,并为每个按钮分配一个命令

for i, button in enumerate([button_zero, button_one, button_two, ...]):
    button.configure(command=add_(str(i)))

既然可以使用python中已经包含的函数工厂:
functools.partial
@Novel personal preference,为什么还要创建函数工厂呢
functools.partial
不会为我节省很多程序员时间,但这意味着我必须记住导入
functools
!YMMV,它实际上根本不会影响最终的代码。