代码
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QLineEdit
from PyQt5.QtGui import QIcon
from random import randint
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.num = randint(1, 100)
def initUI(self):
self.setGeometry(300, 300, 600, 600)
self.setWindowTitle('学点编程吧--猜数字')
self.setWindowIcon(QIcon('./ico/Porsche.ico'))
self.bt1 = QPushButton('确定猜测', self)
self.bt1.setGeometry(250, 300, 100, 50)
self.bt1.setToolTip('<b>点击这里猜数字</b>')
self.bt1.clicked.connect(self.showMessage)
self.text = QLineEdit('在这里输入数字', self)
self.text.setToolTip('<b>这里输入你的猜测</b>')
self.text.selectAll()
self.text.setFocus()
self.text.setGeometry(100, 50, 400, 30)
def showMessage(self):
try:
guessnumber = int(self.text.text())
print("答案: {}".format(guessnumber))
except Exception as e:
print("ERROR ==> {}".format(e))
self.text.setFocus()
return
if guessnumber > self.num:
QMessageBox.about(self, 'useless', '猜大了')
self.text.setFocus()
elif guessnumber < self.num:
QMessageBox.about(self, 'useless', '猜小了')
self.text.setFocus()
else:
QMessageBox.about(self, 'useless', '答对了,进入下一轮!')
self.num = randint(1, 100)
self.text.clear()
self.text.setFocus()
def closeEvent(self, event):
reply = QMessageBox.question(self, 'useless', '确认退出吗', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
print("reply: {}".format(reply))
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Example()
main.show()
sys.exit(app.exec_())