for-loop - 使用 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)
这是它给我的东西在此处输入图像描述
解决方案
您将每行中的所有按钮放在同一行和同一列中: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)
推荐阅读
- javascript - 在 JavaScript 中返回 Select 选项值
- python - Django:为相关表构建动态 Q 查询
- java - JPA org.postgresql.util.PSQLException
- javascript - 确定数字的精度,包括尾随零
- flutter - Flutter FCM 导航 onResume/onLaunch
- php - 弃用 symfony 解决方案
- python - 如何在不保存的情况下直接将 Flask 图像显示为 HTML?
- python - shutil.move 不能在驱动器之间移动
- javascript - Javascript中的整个单词正则表达式匹配和超链接
- javascript - 在 vscode 中格式化后括号消失