lesson 1
目录
- 安装 python 3
- 生成一个 .py 源代码文件
- 在命令提示符窗口运行源代码
- 把源代码打包成 .exe 可执行文件
一、安装 python 3
- 向 ChatGPT 提问:“如何安装 python 3 ?”
- python是一门解释性的脚本语言,写好的 .py 源代码需要安装 python 解释器软件才能执行
二、生成一个 .py 源代码文件
- 在桌面上新建一个文件夹,在文件夹内创建一个 .txt 文本文档,并将下面的代码复制到文件当中
- 然后保存文件,并将文件名修改成 login.py
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QMessageBox
class LoginApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('登录界面')
self.setGeometry(600, 600, 500, 200)
self.init_ui()
def init_ui(self):
self.lbl_username = QLabel('用户名:')
self.edit_username = QLineEdit()
self.lbl_password = QLabel('密码:')
self.edit_password = QLineEdit()
self.edit_password.setEchoMode(QLineEdit.Password)
self.btn_login = QPushButton('登录')
self.btn_login.clicked.connect(self.login)
layout = QVBoxLayout()
layout.addWidget(self.lbl_username)
layout.addWidget(self.edit_username)
layout.addWidget(self.lbl_password)
layout.addWidget(self.edit_password)
layout.addWidget(self.btn_login)
self.setLayout(layout)
def login(self):
username = self.edit_username.text()
password = self.edit_password.text()
QMessageBox.information(self, '登录结果', f'用户名: {username}\n密码: {password}\n')
if __name__ == '__main__':
app = QApplication([])
window = LoginApp()
window.show()
app.exec_()
三、在命令提示符窗口运行源代码
- 在新建的文件夹内按住键盘 shift 键并单击鼠标右键,选择“在此处打开 Powershell 窗口”,这将打开命令提示符
- 在弹出的窗口中输入命令:
pip install pyqt5
- 这将安装 login 程序运行时需要的第三方库。安装完成后,继续输入命令:
python login.py
- 此时程序将运行,可以尝试使用该程序,在文本框里输入一些内容并点击登录按钮
四、把源代码打包成 .exe 可执行文件
pip install pyinstaller
pyinstaller --noconsole login.py
- 打包完成后,在新建文件夹中找到文件夹 disk 并打开,找到 login.exe 并双击启动,这样就可以像使用普通的桌面应用一样使用 login 程序了