For loop 使用for循环在tkinter中创建小部件网格

For loop 使用for循环在tkinter中创建小部件网格,for-loop,tkinter,widget,python-3.6,For Loop,Tkinter,Widget,Python 3.6,我正试图减少使用tkinter和python 3.6在一个简单的计算器应用程序中生成4x4按钮网格所需的代码量。到目前为止,我已经为每行按钮创建了单独的列表和for循环,如下所示 firstRow = ['1','2','3',] secondRow = ['4','5','6','*'] thirdRow = ['7','8','9','/'] forthRow = ['.','0','-','+'] for b in range(len(firs

我正试图减少使用tkinter和python 3.6在一个简单的计算器应用程序中生成4x4按钮网格所需的代码量。到目前为止,我已经为每行按钮创建了单独的列表和for循环,如下所示

    firstRow = ['1','2','3',] 
    secondRow = ['4','5','6','*']
    thirdRow = ['7','8','9','/']
    forthRow = ['.','0','-','+']


    for b in range(len(firstRow)):
        firstBtns = tk.Button(self, text=firstRow[b],
                              command=lambda i=firstRow[b]: entry.insert('end',i),
                              width=5)
        firstBtns.grid(row=0, column=b)

    for b in range(len(secondRow)):
        secondBtns = tk.Button(self, text=secondRow[b], width=5)
        secondBtns.grid(row=1, column=b)

    for b in range(len(thirdRow)):
        thirdBtns = tk.Button(self, text=thirdRow[b], width=5)
        thirdBtns.grid(row=2, column=b)

    for b in range(len(forthRow)):
        forthBtns = tk.Button(self, text=forthRow[b], width=5)
        forthBtns.grid(row=3, column=b)
我想知道是否有一种方法可以做到这一点,在一个列表中使用4个列表,并使用单个for循环,或者使用嵌套for循环?这是我试过但无法正确显示的内容

buttonRows = [['1','2','3','AC'],['4','5','6','/'],
                ['7','8','9','*',],['.','0','-','+']] 

    for lst in range(len(buttonRows)):

        for b in buttonRows[lst]:          
            print(len(buttonRows[lst]))
            btns = tk.Button(self, text=b, width=5)
            btns.grid(row=lst, column=lst)

下面是它给我的信息

您正在将每行中的所有按钮放在同一行和同一列中:
btns.grid(row=lst,column=lst)

如果在列表上循环并使用enumerate:

import tkinter as tk

root = tk.Tk()

buttonRows = [['1','2','3','AC'],['4','5','6','/'],
              ['7','8','9','*',],['.','0','-','+']] 

for row_index, row in enumerate(buttonRows):
    for cell_index, cell in enumerate(row):
        btns = tk.Button(root, text=cell, width=5)
        btns.grid(row=row_index, column=cell_index)

所以我们使用enumerate来增加单元格和行索引,行是每个列表,单元格是列表中的每个项目?在第二个循环中,每个项目都增加后,增加的行是否正确?是。为清晰起见,您可能希望在内部循环中生成一条语句,以打印
行索引
单元格索引
单元格
。你会看到索引和单元格值是如何变化的。完美是的,我为每一个都做了一个打印语句,以便更好地了解发生了什么我记得不久前学习了enumerate,但完全忘记了它做了什么。非常感谢你,我相信我现在会更多地使用enumerate。