Build a PyQt5 Number‑Guessing Game UI from Scratch
This tutorial walks you through creating a number‑guessing game interface with PyQt5, covering Qt Designer setup, Pyuic conversion, UI layout design, and the full Python implementation—including initialization, random number generation, user input handling, game logic, reset functionality, and keyboard shortcuts.
1. Using Qt Designer
In PyCharm open File → Settings → Tools → External Tools, add a new tool named qt5 and set the Program field to the path of the Qt Designer executable. After saving, the External Tools menu appears and you can launch Qt Designer.
2. Pyuic
Similarly add another external tool named Pyuic with Program set to python.exe. Set Arguments to -m PyQt5.uic.pyuic sample.ui -o sample.py, Working directory to the folder containing sample.ui. Running this converts the .ui file into a .py file that can be imported directly.
The generated Python file can be used as a base class for the GUI.
3. Creating the UI File
Open Qt Designer, drag the required widgets onto the form and save it as a .ui file. In this example a vertical layout contains a QLineEdit, three QLabel s and three QPushButton s labeled “Confirm”, “Exit Game” and “Restart”.
4. Implementing the Game Logic
The converted .py file looks like this:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(504, 551)
self.layoutWidget = QtWidgets.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(170, 200, 137, 151))
self.layoutWidget.setObjectName("layoutWidget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.label = QtWidgets.QLabel(self.layoutWidget)
self.label.setText("")
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.label_2 = QtWidgets.QLabel(self.layoutWidget)
self.label_2.setText("")
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_2.setObjectName("pushButton_2")
self.verticalLayout.addWidget(self.pushButton_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_3.setObjectName("pushButton_3")
self.verticalLayout_2.addWidget(self.pushButton_3)
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(170, 60, 161, 16))
self.label_3.setObjectName("label_3")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "确认"))
self.pushButton_2.setText(_translate("Form", "退出游戏"))
self.pushButton_3.setText(_translate("Form", "重新开始"))
self.label_3.setText(_translate("Form", "微信公众号:Python高效编程"))Using this UI class, the main program inherits it and adds the game logic:
# Generate the right bound of the random range
random_choice = [i * 100 for i in range(1, 20)]
class MyMainWindow(QtWidgets.QMainWindow, Ui_Form):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.setupUi(self)
self.guess_range = None
self.guess_num = None
self.left = None
self.right = None
self.random_num()
self.initUi()
def init_range(self):
self.left = 1
self.right = self.guess_range
@property
def _random_range(self):
return random.choice(self.random_choice)
def random_num(self):
self.guess_range = self._random_range
self.guess_num = random.randint(1, self.guess_range)
self.init_range()
def initUi(self):
self.label.setText('数值的范围是:{}-{}'.format(self.left, self.right))
self.pushButton.clicked.connect(self.guess)
self.pushButton_2.clicked.connect(qApp.quit)
self.pushButton_3.clicked.connect(self.reset)
def guess(self):
text = self.lineEdit.text()
try:
text = float(text)
except:
self.label.setText(' 输入不合法')
self.label_2.setText('数值的范围:{}-{}'.format(self.left, self.right))
self.lineEdit.clear()
text = ''
if text:
num = math.floor(text)
if self.guess_num == num:
QMessageBox.question(self, '胜利', '恭喜你猜中了:{}'.format(self.guess_num), QMessageBox.Yes)
self.reset()
elif self.guess_num > num:
if num > self.left:
self.left = num
self.label.setText('数值的范围:{}-{}'.format(self.left, self.right))
self.label_2.setText(' 猜小了')
else:
if num < self.right:
self.right = num
self.label.setText('数值的范围:{}-{}'.format(self.left, self.right))
self.label_2.setText(' 猜大了')
self.lineEdit.clear()
def reset(self):
self.guess_range = None
self.guess_num = None
self.left = None
self.right = None
self.random_num()
self.label.setText('')
self.label_2.setText('')
self.initUi()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Return:
self.guess()
elif e.key() == Qt.Key_Escape:
qApp.quit()
elif e.key() == Qt.Key_R:
self.reset()5. Running the Application
The program initializes the random number, updates the displayed range, processes user guesses, provides feedback, and supports shortcuts: Enter to confirm, Esc to quit, and R to restart.
Python课程全新升级,全栈、web、数据分析、爬虫、AI全新上线。网络班开班倒计时2天, 120天冲击年薪30万 ,改变速约~~~~
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
