本帖最后由 KyleKing 于 2023-3-23 15:34 编辑
最近在学习pyqt5,想起了高中老师随机抽取学生回答问题的抽奖小程序,自己也试着做了一个,用法很简单,输入总数比如100,那么点击开始抽奖,就开始滚动大屏幕,点击停止,抽出中奖数字,大家可以根据自己的实际情况来进行进一步优化和改进,有想法也可以留言给我。
附上源码
[Python] 纯文本查看 复制代码 import sys
import random
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QLineEdit
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, QThread, pyqtSignal
class LotteryThread(QThread):
signal = pyqtSignal(int)
def __init__(self, max_num):
super().__init__()
self.max_num = max_num
def run(self):
while True:
num = random.randint(1, self.max_num)
self.signal.emit(num)
self.msleep(50)
class Lottery(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('抽奖程序')
self.setGeometry(300, 300, 500, 400)
self.title_label = QLabel(self)
self.title_label.setText('XXX抽奖活动') #这里修改抽奖活动的标题
self.title_label.setFont(QFont('Arial', 20))
self.title_label.setAlignment(Qt.AlignCenter)
self.title_label.setGeometry(0, 50, 500, 50)
self.num_label = QLabel(self)
self.num_label.setText('0')
self.num_label.setFont(QFont('Arial', 100))
self.num_label.setAlignment(Qt.AlignCenter)
self.num_label.setGeometry(0, 150, 500, 100)
self.input_edit = QLineEdit(self)
self.input_edit.setGeometry(210, 300, 80, 30)
self.input_edit.setPlaceholderText("请输入总数")
self.start_button = QPushButton('开始抽奖', self)
self.start_button.setGeometry(50, 350, 100, 30)
self.start_button.clicked.connect(self.start_lottery)
self.stop_button = QPushButton('停止抽奖', self)
self.stop_button.setGeometry(350, 350, 100, 30)
self.stop_button.clicked.connect(self.stop_lottery)
self.lottery_thread = LotteryThread(1)
self.lottery_thread.signal.connect(self.update_num)
def start_lottery(self):
max_num = int(self.input_edit.text())
self.lottery_thread.max_num = max_num
self.lottery_thread.start()
def stop_lottery(self):
self.lottery_thread.terminate()
def update_num(self, num):
self.num_label.setText(str(num))
if __name__ == '__main__':
app = QApplication(sys.argv)
lottery = Lottery()
lottery.show()
sys.exit(app.exec_()) |