首页 > 解决方案 > 使用 for 循环在 tkinter 中创建小部件网格

问题描述

我正在尝试减少在使用 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)

这是它给我的东西在此处输入图像描述

标签: for-looptkinterwidgetpython-3.6

解决方案


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

如果您遍历列表并使用枚举,它会更 Pythonic 并且更容易阅读代码:

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)

推荐阅读