Python 在tkinter中使用循环制作许多按钮?

Python 在tkinter中使用循环制作许多按钮?,python,tkinter,Python,Tkinter,我正在尝试用tkinter创建许多按钮,每个按钮都有自己的列和行,并且希望这样做不需要编写大量代码。我对编程比较陌生,所以不知道该怎么做。我不能在同一行上使用.grid(),因为我稍后将对代码进行处理。我在下面贴了一个例子。谢谢 def Create(): button1 = Button(root, text="button 1", command=1) button1.grid(row=7, column=0, pady=5) button2 =

我正在尝试用tkinter创建许多按钮,每个按钮都有自己的列和行,并且希望这样做不需要编写大量代码。我对编程比较陌生,所以不知道该怎么做。我不能在同一行上使用.grid(),因为我稍后将对代码进行处理。我在下面贴了一个例子。谢谢

def Create():
    button1 = Button(root, text="button 1", command=1)
    button1.grid(row=7, column=0, pady=5)
    button2 = Button(root, text="button 2", command=2)
    button2.grid(row=7, column=1, pady=5)
    button3 = Button(root, text = "button 3", command=3)
    button3.grid(row=7, column=2, pady=5)
    button4 = Button(root, text = "button 4", command=4)
    button4.grid(row=8, column=0, pady=5)
    button5 = Button(root, text = "button 5", command=5)
    button5.grid(row=8, column=1, pady=5)
    button6 = Button(root, text = "button 6", command=6)
    button6.grid(row=8, column=2, pady=5)
    button7 = Button(root, text = "button 7", command=7)
    button7.grid(row=9, column=0, pady=5)
    button8 = Button(root,text = "button 8", command=8)
    button8.grid(row=9, column=1, pady=5)
    button9 = Button(root,text = "button 9", command=9)
    button9.grid(row=9, column=2, pady=5)
   
    global packing
    packing = [button1, button2, button3, button4, button5, button6, button7, button8, button9]

将此添加到创建中:

packing = []
buttonNumber = 1
for rows in range(7, 10):
    for cols in range(0, 3):
        b = tk.Button(root, text = "Button {}".format(buttonNumber), command = lambda i = buttonNumber: print(i))
        b.grid(row = rows, column = cols, pady = 5)
        packing.append(b)
        buttonNumber += 1

这将遍历行和列,并创建一个按钮,单击该按钮时将打印其编号(替换为您要使用的命令)。然后,它使用行/列编号来定位按钮,并将其添加到列表中。

行的值更改,并非所有按钮都是7。@a121感谢您指出这一点,我没有注意到