import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
items = ['计算', 'back', '', 'close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
# 指定位置
positions = [(i, j) for i in range(5) for j in range(4)]
#print(positions)
# 让button的位置和名字做一个捆绑
for postion, name in zip(positions, items):
# 如果名字为空,则跳过。不创建按钮,也不安放按钮位置
if name == '':
continue
# 创建button控件,并给 button 赋值
button = QPushButton(name)
# 如果有多个位置参数,则利用 *position
grid.addWidget(button, *postion)
# 指定窗口在屏幕上显示的初试位置
self.move(800, 150)
self.setWindowTitle("网格布局")
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Example()
demo.show()
sys.exit(app.exec_())
运行效果截图: