事件与页面切换

事件与页面切换

控件事件绑定

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QLineEdit, QSpinBox

事件绑定三要素: xxx发生xx就做xx
事件源 发生 事件 就 执行某个操作(事件驱动程序)
绑定程序:事件源.事件.connect(操作对应的函数)

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.create_ui()
        self.setGeometry(200, 100, 800, 600)
        self.setWindowTitle('图书管理系统首页')
        self.show()

    def create_ui(self):
        btn1 = QPushButton('确定', self)
        btn1.move(50, 10)
        # 按钮点击事件
        btn1.clicked.connect(self.btn_action)

        self.input1 = QLineEdit(self)
        self.input1.setPlaceholderText('请输入手机号')
        self.input1.move(50, 60)
        # 输入框内容改变事件
        self.input1.textChanged.connect(self.input_text_action)


        num_input = QSpinBox(self)
        num_input.move(100, 100)
        num_input.valueChanged.connect(self.num_action)

    def num_action(self, value):
        print('数值改变', value)

    def btn_action(self, value):
        print('按钮被点击', value, self.input1.text())


    def input_text_action(self, value):
        print('输入框内容改变', value)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

图片的使用

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
from PyQt5.QtGui import QImage, QIcon, QPixmap, QPalette
from PyQt5.QtCore import QSize
from PyQt5.QtCore import Qt
import requests

def download_image():
    response = requests.get('https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=158268377,3003399912&fm=26&gp=0.jpg')
    if response.status_code == 200:
        return response.content
    print('请求失败!', response)
    return None


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.create_ui()
        self.setGeometry(200, 100, 800, 450)
        self.setWindowTitle('图书管理系统首页')
        self.show()

    def create_ui(self):
        # 1. 设置窗口图标
        icon = QIcon('files/logo.png')
        self.setWindowIcon(icon)

        # 2. 显示图片
        self.bg_label = QLabel(self)
        self.bg_label.setGeometry(0, 0, 800, 450)
        self.bgpix = QPixmap('files/bg.jpg')
        self.bg_label.setPixmap(self.bgpix)

        username = QLabel('用户名:', self)
        username.move(100, 100)
        username.setStyleSheet('QLabel{color: rgb(255, 255, 255); font-size:30px;}')

        # 3.显示网络图片
        # 下载图片
        image_data = download_image()
        # 使用网络图片数据创建图片对象
        image = QImage.fromData(image_data)
        # 对图片进行缩放
        image = image.scaled(200, 200)
        pix = QPixmap.fromImage(image)
        # 显示图片
        btn = QLabel(self)
        btn.setGeometry(200, 100, 200, 200)
        btn.setPixmap(pix)

        # 思考:怎么将图片放在按钮上?






    # 在窗口的大小发送改变的时候会被自动调用
    def resizeEvent(self, a0) -> None:
        # 获取到最新的窗口大小
        w_size = self.size()

        # 对原图进行缩放
        image = QImage('files/bg.jpg')
        new_image = image.scaled(w_size.width(), w_size.height())
        pix = QPixmap.fromImage(new_image)

        # 将显示图片的label进行缩放
        self.bg_label.setGeometry(0, 0, w_size.width(), w_size.height())
        self.bg_label.setPixmap(pix)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

菜单

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QAction, QMenu
from PyQt5.QtGui import QIcon

如果想要在窗口上添加菜单,那么窗口的类型必须是QMainWindow或QMainWindow的子类

# 第一步,让窗口类继承QMainWindow
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.create_ui()
        self.setGeometry(200, 100, 800, 600)
        self.setWindowTitle('图书管理系统首页')
        self.show()

    def create_ui(self):
        # 第二步:添加各种菜单
        # 1. 获取当前窗口上菜单栏
        menu_bar = self.menuBar()
        menu_bar.setNativeMenuBar(False)     # mac需要添加,否则菜单栏不显示

        # 2.在菜单栏上添加菜单
        file_menu = menu_bar.addMenu('File')
        edit_menu = menu_bar.addMenu('&Edit')

        # 3.在菜单上添加选项
        fa1 = QAction('New Project', self)    # 创建选项
        fa1.triggered.connect(self.new_project)    # 给选项绑定事件

        fa2 = QAction(QIcon('files/naozhong.png'), 'Open', self)
        fa2.triggered.connect(self.open_action)
        fa2.setShortcut('ctrl+o')       # 添加快捷键

        # 将选项添加到菜单上
        file_menu.addActions([fa1, fa2])

        # 4. 添加子菜单
        file_p_menu = QMenu('File Projecties', self)
        file_menu.addMenu(file_p_menu)

        fpa1 = QAction('File Encoding', self)
        fpa2 = QAction('Remove BOM', self)
        fpa3 = QAction('Make File Read-Only', self)
        file_p_menu.addActions([fpa1, fpa2, fpa3])

    # 在窗口上点鼠标右键的时候会被自动调用
    def contextMenuEvent(self, event) -> None:
        # 创建菜单对象
        right_menu = QMenu(self)

        # 在右键菜单上添加选项或者子菜单
        a1 = QAction('copy', self)
        a2 = QAction('Paste', self)
        a3 = QAction('Cut', self)
        right_menu.addActions([a1, a2, a3])

        # 让菜单显示在当前窗口鼠标所在的位置
        right_menu.exec_(self.mapToGlobal(event.pos()))

对话框

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,QPushButton, QMessageBox, QInputDialog, QColorDialog, QFontDialog, QFileDialog
from PyQt5.QtGui import QPalette, QColor

class Value:
    Yes = 16384
    No = 65536


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.create_ui()
        self.setGeometry(200, 100, 800, 600)
        self.setWindowTitle('图书管理系统首页')
        self.show()

    def create_ui(self):
        message_btn = QPushButton('确定', self)
        message_btn.move(100, 20)
        message_btn.clicked.connect(self.show_message_box)

        self.color_label = QLabel('你好', self)
        pa = QPalette()
        pa.setColor(self.backgroundRole(), QColor(255, 0, 0))
        self.setPalette(pa)
        self.autoFillBackground()

    def show_message_box(self):
        print('显示消息框!')
        # 1. QMessageBox
        # 消息类型:information、question、warning、critical、about
        # QMessageBox.消息类型()

        # QMessageBox.information(self, '对话框', '中午好!', QMessageBox.Ok)

        # result = QMessageBox.question(self, '问题', '是否删除改数据?', QMessageBox.Yes|QMessageBox.No)
        # if result == Value.Yes:
        #     print('YES')
        # else:
        #     print('NO')

        # 2. QInputDialog
        # result = QInputDialog.getText(self, '', '请输入名字:')
        # print(result)

        result = QColorDialog.getColor()
        print(result.rgb())

        pa = QPalette()
        pa.setColor(self.backgroundRole(), result)
        self.setPalette(pa)
        self.autoFillBackground()

        # QFontDialog.getFont()

        # QFileDialog.getOpenFileUrl()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

作业

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,QMessageBox
from PyQt5.QtWidgets import QLabel, QLineEdit, QPushButton
from PyQt5.QtGui import QPalette, QColor
import pymysql

def operating_database(acount,ps):
    conn = pymysql.Connect(
        host='localhost',
        port =3306,
        user = 'root',
        password='ly19950926.',
        database='library',
        autocommit=True
    )
    try:
        with conn.cursor() as cursor:
            cursor.execute(f"select * from tb_user where user_acount='{acount}' and user_ps='{ps}';")
            return cursor.fetchall()
    except IndexError:
        pass
    finally:
        conn.close()



class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.acount = None
        self.ps = None
        self.style_sheet()
        self.create_ui()
        self.setGeometry(200, 100, 800, 600)
        self.setWindowTitle('图书管理系统首页')
        self.show()

    def style_sheet(self):
        self.setStyleSheet(
        '''
        QLabel{color:rgb(95,60,55); font-size:15px;}
        QLineEdit{height: 35px; width:250px; border: 1px solid rgb(95,60,55);  border-radius: 8px;}
        QPushButton{height: 35px; width:100px; border: 1px solid rgb(95,60,55); background-color: rgb(119,78,45); color: rgb(255, 245, 235); border-radius: 8px;}
        ''')
        # self.setStyleSheet('QLineEdit{width: 200px;}')

    def check(self):
        # print(self.acount,self.ps,type(self.acount),type(self.ps))
        result = operating_database(self.acount,self.ps)
        print(result)
        if not result:
            print('账号或密码错误!')
            QMessageBox.information(self,'提示','账号或密码错误!',QMessageBox.Ok)
        else:
            print('登录成功!')
            QMessageBox.information(self, '提示', '登录成功!', QMessageBox.Ok)




    def acount_text(self,value):
        print(value)
        self.acount = value

    def ps_text(self,value):
        print(value)
        self.ps = value


    def create_ui(self):
        # 设置窗口背景颜色
        # self.setStyleSheet('QWidget{background-color: rgb(205,193,168);}')
        pa = QPalette()
        pa.setColor(self.backgroundRole(), QColor(205, 193, 168))
        self.setPalette(pa)
        self.autoFillBackground()

        # 大盒子
        box = QHBoxLayout(self)
        # 中间内容盒子
        box1 = QVBoxLayout()

        box.addStretch(1)
        box.addLayout(box1)
        box.addStretch(1)

        # 标题
        box4 = QHBoxLayout()
        title_label = QLabel('千锋图书管理系统', self)
        title_label.setStyleSheet('QLabel{color: rgb(91, 64, 37); font-size: 30px; font-weight:900;}')
        box4.addStretch(1)
        box4.addWidget(title_label)
        box4.addStretch(1)

        # 输入账号密码
        box2 = QGridLayout()
        username = QLabel('用户名:', self)
        username_input = QLineEdit(self)
        username_input.textChanged.connect(self.acount_text)
        pw = QLabel('密    码:', self)
        pw_input = QLineEdit(self)
        pw_input.textChanged.connect(self.ps_text)

        box2.addWidget(username, 1, 1)
        box2.addWidget(username_input, 1, 2)
        box2.addWidget(pw, 2, 1)
        box2.addWidget(pw_input, 2, 2)

        # 登录和退出按钮
        box3 = QHBoxLayout()
        btn1 = QPushButton('登录', self)
        btn1.clicked.connect(self.check)
        btn2 = QPushButton('退出', self)
        box3.addWidget(btn1)
        box3.addStretch(1)
        box3.addWidget(btn2)

        box1.addStretch(1)
        box1.addLayout(box4)
        box1.addStretch(2)
        box1.addLayout(box2)
        box1.addStretch(2)
        box1.addLayout(box3)
        box1.addStretch(20)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值