Pyqt5 简明教程
PyQt5 - Hello World
使用 PyQt 创建简单的 GUI 应用程序涉及以下步骤 −
Creating a simple GUI application using PyQt involves the following steps −
-
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
-
Create an application object of QApplication class.
-
A QWidget object creates top level window. Add QLabel object in it.
-
Set the caption of label as "hello world".
-
Define the size and position of window by setGeometry() method.
-
Enter the mainloop of application by app.exec_() method.
以下是 PyQt 中执行 Hello World 程序的代码:
Following is the code to execute Hello World program in PyQt −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b = QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle("PyQt5")
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −

还可以为上述代码开发面向对象的解决方案。
It is also possible to develop an object oriented solution of the above code.
-
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
-
Create an application object of QApplication class.
-
Declare window class based on QWidget class
-
Add a QLabel object and set the caption of label as "hello world".
-
Define the size and position of window by setGeometry() method.
-
Enter the mainloop of application by app.exec_() method.
以下是面向对象解决方案的完整代码:
Following is the complete code of the object oriented solution −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class window(QWidget):
def __init__(self, parent = None):
super(window, self).__init__(parent)
self.resize(200,50)
self.setWindowTitle("PyQt5")
self.label = QLabel(self)
self.label.setText("Hello World")
font = QFont()
font.setFamily("Arial")
font.setPointSize(16)
self.label.setFont(font)
self.label.move(50,20)
def main():
app = QApplication(sys.argv)
ex = window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
