PyQt5 - 加入线程

代码

# -*- coding: utf-8 -*-
# @Author   : zbz

import random
import sys
import threading
import time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

now = lambda: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
titles: str = "Python2 Python3 Java Go PHP JavaScript C C++ C#"
titles: list = titles.split(" ")
titles_d = {key: 0 for key in titles}
ico_file_path = "../qt/ico/Lamborghini.ico"  # ==> 窗口图标的路径


class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.resize(1000, 600)
        self.setWindowIcon(QIcon(ico_file_path))  # ==> 给窗口设置图标
        self.now_btn = QPushButton(self)
        self.now_btn.setGeometry(300, 100, 400, 100)  # ==> 按钮大小
        self.now_btn.setToolTip("此按钮只显示当前时间,点击无效")
        self.now_btn.setFont(QFont("Monaco", 22))

        t1 = threading.Thread(target=self.show_now_time)  # ==> 子线程
        t2 = threading.Thread(target=self.random_window_title)  # ==> 子线程
        t1.setDaemon(True)
        t2.setDaemon(True)
        t1.start()
        t2.start()
        self.btn = QPushButton("退出", self)
        self.btn.setToolTip("退出窗口程序")
        self.btn.setGeometry(450, 400, 100, 30)
        self.btn.clicked.connect(self.when_btn_click)

    def random_window_title(self):
        while True:
            window_title = random.choice(titles)
            titles_d[window_title] += 1
            self.setWindowTitle("{} 共计出现{}次".format(window_title, titles_d[window_title]))
            time.sleep(1)

    def show_now_time(self):
        while True:
            self.now_btn.setText(now())
            time.sleep(1)

    def when_btn_click(self):
        print("Bye Bye")
        QApplication.instance().quit()

    def mousePressEvent(self, mouse):
        print("鼠标按下")

    def mouseReleaseEvent(self, mouse):
        print("鼠标释放")

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "useless", "不爱我了对不对?")
        print(reply)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值