下面是Python的PyQt5 HelloWorld完整使用攻略。
安装
首先需要安装PyQt5库,在命令行中使用pip安装:
pip install PyQt5
编写代码
使用PyQt5创建HelloWorld程序需要涉及到以下三个文件:
hello.py
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('Hello PyQt5')
window.setGeometry(100, 100, 280, 80)
helloMsg = QLabel('<h1>Hello World!</h1>', parent=window)
helloMsg.move(60, 15)
window.show()
sys.exit(app.exec_())
setup.py
import sys
from cx_Freeze import setup, Executable
setup(
name='HelloPyQt5',
version='0.1',
description='Hello World Program',
executables=[Executable('hello.py')],
)
build.sh
python setup.py build
运行程序
在命令行中进入项目的根目录,使用以下命令构建可执行文件:
sh build.sh
在构建结束后,进入build
目录下,可以看到生成的可执行文件。
使用终端执行可执行文件即可看到HelloWorld程序的运行结果。
示例说明
示例1:修改窗口的背景色
如果想要将HelloWorld程序窗口的背景色改变,只需要在hello.py
中添加一行即可:
window.setStyleSheet('background-color: pink;')
将整个hello.py
代码修改为:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('Hello PyQt5')
window.setGeometry(100, 100, 280, 80)
window.setStyleSheet('background-color: pink;')
helloMsg = QLabel('<h1>Hello World!</h1>', parent=window)
helloMsg.move(60, 15)
window.show()
sys.exit(app.exec_())
重新构建并运行程序,可以看到HelloWorld程序窗口的背景色已经变成了粉色。
示例2:添加按钮和按钮事件
如果想要给HelloWorld程序中添加按钮,并增加按钮点击事件,只需要在hello.py
中添加以下代码:
from PyQt5.QtWidgets import QPushButton
button = QPushButton('Click me', parent=window)
button.move(110,50)
button.clicked.connect(lambda: print('hello world'))
整个hello.py
代码修改为:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('Hello PyQt5')
window.setGeometry(100, 100, 280, 80)
window.setStyleSheet('background-color: pink;')
helloMsg = QLabel('<h1>Hello World!</h1>', parent=window)
helloMsg.move(60, 15)
button = QPushButton('Click me', parent=window)
button.move(110,50)
button.clicked.connect(lambda: print('hello world'))
window.show()
sys.exit(app.exec_())
重新构建并运行程序,可以看到HelloWorld程序窗口中增加了一个“Click me”按钮。当点击该按钮时,终端会输出“hello world”信息。
以上就是Python的PyQt5 HelloWorld的完整使用攻略。