Table of contents
1. Run interface framework
import sys
from PyQt5.QtWidgets import QApplication,QWidget
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()
2. Basic controls
Goal 1: Add button
Required module: QPushButton
# 按钮
btn = QPushButton('按钮')
# 将按钮放置在窗口中
btn.setParent(w)
code:
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 按钮
btn = QPushButton('按钮')
# 将按钮放置在窗口中
btn.setParent(w)
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()
Method Two:
# 按钮(并将按钮放置在窗口w中)
btn = QPushButton('按钮',w)
code:
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 按钮(并将按钮放置在窗口w中)
btn = QPushButton('按钮',w)
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()
Goal 2: Added text:
Module required: QLabel
# 文本(并将文本放置在窗口w中)
label = QPushButton('账号:', w)
code:
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton, QLabel
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 按钮(并将按钮放置在窗口w中)
btn = QPushButton('按钮',w)
# 文本(并将文本放置在窗口w中)
label = QLabel('账号:', w)
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()
As you can see from the illustration, the components are stacked together (then you need to set his position)
Goal 3: Set the location
label.setGeometry(60,60,60,30)
code:
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton, QLabel
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 按钮(并将按钮放置在窗口w中)
btn = QPushButton('按钮',w)
# 文本(并将文本放置在窗口w中)
label = QLabel('账号:', w)
# 设置坐标+大小(x,y,w,h)
label.setGeometry(60,60,60,30)
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()
The final beautified code
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton, QLabel
if __name__ == '__main__':
# 接收参数(仅有一个)
app = QApplication(sys.argv)
# 创建一个窗口
w = QWidget()
# 窗口标题
w.setWindowTitle("pyqt5程序")
# 按钮(并将按钮放置在窗口w中)
btn = QPushButton('确认',w)
# 设置坐标+大小(x,y,w,h)
btn.setGeometry(300, 50, 60, 30)
# 文本(并将文本放置在窗口w中)
label = QLabel('账号:', w)
# 设置坐标+大小(x,y,w,h)
label.setGeometry(50,50,60,30)
# 展示窗口
w.show()
# 程序进入循环等待
app.exec_()