python 版隨機點名器
阿新 • • 發佈:2021-11-19
import random import sys import os from PyQt5 import QtGui from PyQt5.QtCore import QTimer, Qt from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import * class MyApp(QMainWindow, QWidget): def __init__(self): super().__init__() # 名字的區域 self.name_list = [] with open("test.txt", encoding='utf-8') as f: for line in f.readlines(): line = line.strip('\n') # 去掉列表中每一個元素的換行符 self.name_list.append(line) # 圖片的區域 self.images = [] for root, dirs, files in os.walk(r'E:\home\webContainer\ntmssResource'): # 遍歷檔案 for f in故鄉明files: self.images.append(os.path.join(root, f)) self.App() def App(self): # 設定主體框架 # 設定窗體名字 self.setWindowTitle('隨機點名器') # 設定窗體大小 self.resize(1000, 600) # 設定字型大小 self.font = QtGui.QFont() self.font.setPointSize(23) # 設定start按鈕 self.start_button = QPushButton('Start', self) self.start_button.resize(200, 100) self.start_button.move(650, 100) self.start_button.setFont(self.font) # 設定stop按鈕 self.stop_button = QPushButton('Stop', self) self.stop_button.resize(200, 100) self.stop_button.move(650, 450) self.stop_button.setFont(self.font) # 設定名字顯示 self.name_lable = QLineEdit(self) self.name_lable.move(100, 450) self.name_lable.resize(350, 100) self.name_lable.setText('這個人是誰呢?') self.name_lable.setAlignment(Qt.AlignCenter) self.name_lable.setFont(self.font) # 設定圖片顯示 self.image_lable = QLabel(self) # 為圖片顯示設定一個畫布 位置大小 self.image_lable.setGeometry(50, 50, 470, 300) # 為圖片設定屬性 self.image_lable.setStyleSheet("border: 1px solid blue") # 插入圖片 self.showPics() # 設定開始和結束 self.start_button.clicked.connect(lambda: self.start_app()) self.stop_button.clicked.connect(lambda: self.stop_app()) self.stop_button.clicked.connect(lambda: self.btn_enabled_app(self.start_button)) # 開始程式 def start_app(self): self.start_button.setEnabled(False) # 將start按鈕設定成禁止點選 self.timer = QTimer(self) self.timer.timeout.connect(self.setname_image) self.timer.start(1000) # 圖片播放的時間 # 程式結束 def stop_app(self): self.timer.stop() # def btn_enabled_app(self, btn): # 按下按鈕後解除禁止可以繼續點選 btn.setEnabled(True) def setname_image(self): # 點名系統 name = self.name_list[random.randint(0, len(self.name_list) - 1)] self.name_lable.setText(name) self.name_lable.setAlignment(Qt.AlignCenter) # 設定文字對齊方式 居中對齊 self.name_lable.setFont(self.font) # 插入圖片 self.showPics() def showPics(self): imagename = self.images[random.randint(0, len(self.images) - 1)] self.pnx = QPixmap(imagename) # 載入圖片路徑 self.image_lable.setPixmap(self.pnx) # 將圖片顯示畫布上 self.image_lable.setScaledContents(True) # 圖片自適應視窗 if __name__ == '__main__': app = QApplication(sys.argv) myapp = MyApp() myapp.show() sys.exit(app.exec_())