# Python怎么通過PyQt5實現登錄界面
## 一、前言
在現代軟件開發中,圖形用戶界面(GUI)是提升用戶體驗的重要組成部分。Python作為一門功能強大且易于學習的編程語言,提供了多個GUI開發工具包,其中PyQt5因其豐富的組件庫和跨平臺特性廣受歡迎。本文將詳細介紹如何使用PyQt5實現一個功能完整的登錄界面,包含以下核心內容:
1. 環境準備與PyQt5安裝
2. 基礎窗口創建
3. 界面布局設計
4. 信號與槽機制實現
5. 登錄功能邏輯處理
6. 樣式美化技巧
7. 完整代碼示例
## 二、環境準備
### 1. 安裝PyQt5
```bash
pip install PyQt5
pip install PyQt5-tools
首先創建一個最基本的窗口框架:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class LoginWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('用戶登錄系統')
self.setGeometry(300, 300, 400, 300)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = LoginWindow()
sys.exit(app.exec_())
這段代碼創建了一個400×300像素的窗口,標題為”用戶登錄系統”。
我們需要以下核心組件: - 用戶名輸入框 - 密碼輸入框 - 登錄按鈕 - 記住密碼復選框
from PyQt5.QtWidgets import (QLabel, QLineEdit,
QPushButton, QCheckBox,
QVBoxLayout, QWidget)
class LoginWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 主窗口設置
self.setWindowTitle('用戶登錄系統')
self.setFixedSize(400, 300)
# 創建中央部件和布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout()
# 用戶名組件
self.label_username = QLabel('用戶名:')
self.edit_username = QLineEdit()
self.edit_username.setPlaceholderText('請輸入用戶名')
# 密碼組件
self.label_password = QLabel('密碼:')
self.edit_password = QLineEdit()
self.edit_password.setPlaceholderText('請輸入密碼')
self.edit_password.setEchoMode(QLineEdit.Password)
# 記住密碼選項
self.check_remember = QCheckBox('記住密碼')
# 登錄按鈕
self.btn_login = QPushButton('登錄')
# 添加到布局
layout.addWidget(self.label_username)
layout.addWidget(self.edit_username)
layout.addWidget(self.label_password)
layout.addWidget(self.edit_password)
layout.addWidget(self.check_remember)
layout.addWidget(self.btn_login)
# 設置布局
central_widget.setLayout(layout)
使用QFormLayout可以創建更規范的表單布局:
from PyQt5.QtWidgets import QFormLayout
# 替換之前的QVBoxLayout
form_layout = QFormLayout()
form_layout.addRow(self.label_username, self.edit_username)
form_layout.addRow(self.label_password, self.edit_password)
form_layout.addRow(self.check_remember)
form_layout.addRow(self.btn_login)
PyQt5使用信號(signal)與槽(slot)機制處理事件:
# 在initUI方法中添加連接
self.btn_login.clicked.connect(self.handle_login)
# 新增處理方法
def handle_login(self):
username = self.edit_username.text()
password = self.edit_password.text()
if not username or not password:
self.show_message('錯誤', '用戶名和密碼不能為空')
return
# 這里添加實際的驗證邏輯
if username == 'admin' and password == '123456':
self.show_message('成功', '登錄成功')
else:
self.show_message('失敗', '用戶名或密碼錯誤')
def show_message(self, title, content):
from PyQt5.QtWidgets import QMessageBox
QMessageBox.information(self, title, content)
from PyQt5.QtWidgets import QHBoxLayout, QToolButton
from PyQt5.QtGui import QIcon
# 在密碼行創建水平布局
password_layout = QHBoxLayout()
password_layout.addWidget(self.edit_password)
# 添加顯示密碼按鈕
self.btn_show_pwd = QToolButton()
self.btn_show_pwd.setIcon(QIcon('eye.png')) # 需要準備圖標
self.btn_show_pwd.setCheckable(True)
self.btn_show_pwd.toggled.connect(self.toggle_password_visibility)
password_layout.addWidget(self.btn_show_pwd)
# 添加到表單
form_layout.addRow(self.label_password, password_layout)
# 切換密碼可見性方法
def toggle_password_visibility(self, checked):
if checked:
self.edit_password.setEchoMode(QLineEdit.Normal)
self.btn_show_pwd.setIcon(QIcon('eye_closed.png'))
else:
self.edit_password.setEchoMode(QLineEdit.Password)
self.btn_show_pwd.setIcon(QIcon('eye.png'))
import json
import os
from PyQt5.QtCore import QStandardPaths
def load_saved_credentials(self):
config_path = os.path.join(
QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation),
'login_config.json'
)
try:
with open(config_path, 'r') as f:
data = json.load(f)
self.edit_username.setText(data.get('username', ''))
self.edit_password.setText(data.get('password', ''))
self.check_remember.setChecked(True)
except:
pass
def save_credentials(self):
if not self.check_remember.isChecked():
return
config_dir = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)
if not os.path.exists(config_dir):
os.makedirs(config_dir)
config_path = os.path.join(config_dir, 'login_config.json')
data = {
'username': self.edit_username.text(),
'password': self.edit_password.text()
}
with open(config_path, 'w') as f:
json.dump(data, f)
self.setStyleSheet("""
QMainWindow {
background-color: #f5f5f5;
}
QLabel {
font-size: 14px;
color: #333;
}
QLineEdit {
border: 1px solid #ccc;
border-radius: 4px;
padding: 5px;
min-width: 200px;
}
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
QPushButton:hover {
background-color: #45a049;
}
""")
from PyQt5.QtGui import QIcon
self.setWindowIcon(QIcon('app_icon.png'))
import sys
import json
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel,
QLineEdit, QPushButton, QCheckBox,
QFormLayout, QWidget, QMessageBox,
QHBoxLayout, QToolButton)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QStandardPaths
class LoginWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.load_saved_credentials()
def initUI(self):
# 主窗口設置
self.setWindowTitle('用戶登錄系統')
self.setWindowIcon(QIcon('app_icon.png'))
self.setFixedSize(400, 300)
# 樣式設置
self.setStyleSheet("""
QMainWindow {
background-color: #f5f5f5;
}
QLabel {
font-size: 14px;
color: #333;
}
QLineEdit {
border: 1px solid #ccc;
border-radius: 4px;
padding: 5px;
min-width: 200px;
}
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
QPushButton:hover {
background-color: #45a049;
}
""")
# 創建中央部件和布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
form_layout = QFormLayout()
# 用戶名組件
self.label_username = QLabel('用戶名:')
self.edit_username = QLineEdit()
self.edit_username.setPlaceholderText('請輸入用戶名')
# 密碼組件
self.label_password = QLabel('密碼:')
self.edit_password = QLineEdit()
self.edit_password.setPlaceholderText('請輸入密碼')
self.edit_password.setEchoMode(QLineEdit.Password)
# 密碼顯示/隱藏按鈕
password_layout = QHBoxLayout()
password_layout.addWidget(self.edit_password)
self.btn_show_pwd = QToolButton()
self.btn_show_pwd.setIcon(QIcon('eye.png'))
self.btn_show_pwd.setCheckable(True)
self.btn_show_pwd.toggled.connect(self.toggle_password_visibility)
password_layout.addWidget(self.btn_show_pwd)
# 記住密碼選項
self.check_remember = QCheckBox('記住密碼')
# 登錄按鈕
self.btn_login = QPushButton('登錄')
self.btn_login.clicked.connect(self.handle_login)
# 添加到布局
form_layout.addRow(self.label_username, self.edit_username)
form_layout.addRow(self.label_password, password_layout)
form_layout.addRow(self.check_remember)
form_layout.addRow(self.btn_login)
# 設置布局
central_widget.setLayout(form_layout)
def toggle_password_visibility(self, checked):
if checked:
self.edit_password.setEchoMode(QLineEdit.Normal)
self.btn_show_pwd.setIcon(QIcon('eye_closed.png'))
else:
self.edit_password.setEchoMode(QLineEdit.Password)
self.btn_show_pwd.setIcon(QIcon('eye.png'))
def handle_login(self):
username = self.edit_username.text()
password = self.edit_password.text()
if not username or not password:
self.show_message('錯誤', '用戶名和密碼不能為空')
return
# 這里添加實際的驗證邏輯
if username == 'admin' and password == '123456':
self.show_message('成功', '登錄成功')
self.save_credentials()
else:
self.show_message('失敗', '用戶名或密碼錯誤')
def show_message(self, title, content):
QMessageBox.information(self, title, content)
def load_saved_credentials(self):
config_path = os.path.join(
QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation),
'login_config.json'
)
try:
with open(config_path, 'r') as f:
data = json.load(f)
self.edit_username.setText(data.get('username', ''))
self.edit_password.setText(data.get('password', ''))
self.check_remember.setChecked(True)
except:
pass
def save_credentials(self):
if not self.check_remember.isChecked():
return
config_dir = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)
if not os.path.exists(config_dir):
os.makedirs(config_dir)
config_path = os.path.join(config_dir, 'login_config.json')
data = {
'username': self.edit_username.text(),
'password': self.edit_password.text()
}
with open(config_path, 'w') as f:
json.dump(data, f)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = LoginWindow()
sys.exit(app.exec_())
本文詳細介紹了使用PyQt5創建登錄界面的完整流程,包括:
通過這個示例,您可以掌握PyQt5開發GUI應用的基本方法,并可以在此基礎上擴展更復雜的功能,如: - 添加注冊功能 - 實現密碼加密存儲 - 連接數據庫驗證 - 添加驗證碼功能 - 實現多語言支持
PyQt5提供了豐富的組件和靈活的布局系統,能夠滿足各種GUI開發需求。希望本文能幫助您快速入門PyQt5開發。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。