pyqt5学习4
实例1:猜数字游戏
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QMessageBox from PyQt5.QtGui import QIcon from PyQt5.QtCore import QCoreApplication from random import randint class Example(QWidget): def __init__(self): super().__init__() self.init_ui() self.num = randint(1, 100)#生成随机数 def init_ui(self): self.setGeometry(1068, 612, 600, 600) self.setWindowTitle('天晟出品') self.setWindowIcon(QIcon('ComNet.ico')) self.qbtn = QPushButton('退出', self) #新建按钮对象 self.qbtn.clicked.connect(QCoreApplication.instance().quit) #按钮点击事件 self.qbtn.resize(100, 50) self.qbtn.move(450, 450) self.qbtn1 = QPushButton('我猜', self) #新建按钮对象 self.qbtn1.setGeometry(330, 450, 100, 50) self.qbtn1.setToolTip('<b>我们可以支付一些费用点击这里猜数字,猜对了会有很大的奖励,你想象不到的福利!!你愿意猜吗?</b>') #按钮提示 self.qbtn1.clicked.connect(self.show_message) self.text = QLineEdit('在这里输入数字', self) self.text.selectAll() self.text.setFocus() self.text.setGeometry(100, 250, 400, 50) self.show() def show_message(self): guessnumber = int(self.text.text())#将LineEdit的字符str转换为int类型 print(self.num) if guessnumber > self.num: QMessageBox.about(self, '看结果', '猜大了!') self.text.setFocus() elif guessnumber < self.num: QMessageBox.about(self, '看结果', '猜小了!') self.text.setFocus() else: QMessageBox.about(self, '看结果', '答对了!进入下一轮!') self.num = randint(1, 100) self.text.clear() self.text.setFocus() def closeEvent(self, event): # reply = QMessageBox.question(self, '确认', '确认退出吗', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # reply = QMessageBox.critical(self, '确认', '确认退出吗', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # reply = QMessageBox.warning(self, '确认', '确认退出吗', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) reply = QMessageBox.information(self, '确认', '确认退出吗', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())