Python:数组中的按钮命令

Python: Button Command in Array

我正在尝试简化计算器的代码。

我没有为每个按钮编写代码,而是试图将它们全部放在一个 for 循环中,但事实证明让按钮真正具有单独的命令很困难。

目前代码如下:

from tkinter import *
from functools import partial

win = Tk()

counter = 0
button_text = ("M", "(", ")", "C", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "*", "AC", "0", ".", "=")
button_ids = []
label = Label(text="Enter text here", )
label.grid(row=10, column=1, columnspan=4)


def click(n):
    global label
    # get index and ID of button
    print(n)
    button_name = (button_ids[n])
    button_name.configure(text=f"clicked {button_ids[n]}")
    label.config(text=f"{button_ids[n]} clicked")


for r in range(5):
    for c in range(4):
        # create buttons & assign unique arg (i) to run function (change)
        button = Button(win, width=15, text=button_text[counter], command=partial(click, r))
        button.grid(row=r, column=c)
        # add ID to list
        button_ids.append(button)
        # update counter for next button text
        counter += 1

print(button_ids)

win.mainloop()

只用一个 for 循环就可以了,但是添加第二个 for 循环来创建数组就不行了。

如何让每个按钮正确地 work/register?

使用command=partial(click, counter),因为函数click需要button_ids[n].

如果您需要显示按钮名称,也可以将 button_ids 更改为 button_text

from tkinter import *
from functools import partial

win = Tk()

counter = 0
button_text = ("M", "(", ")", "C", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "*", "AC", "0", ".", "=")
button_ids = []
label = Label(text="Enter text here", )
label.grid(row=10, column=1, columnspan=4)


def click(n):
    global label
    # get index and ID of button
    print(n)
    button_name = (button_ids[n])
    # button_name.configure(text=f"clicked {button_ids[n]}")
    label.config(text=f"{button_text[n]} clicked")


for r in range(5):
    for c in range(4):
        print(counter, r, c)
        # create buttons & assign unique arg (i) to run function (change)
        button = Button(win, width=15, text=button_text[counter], command=partial(click, counter))
        button.grid(row=r, column=c)
        # add ID to list
        button_ids.append(button)
        # update counter for next button text
        counter += 1

print(button_ids)

win.mainloop()