Categories
General Python level 2 python

Learning PyQT and Building a High Low Guessing Game

Many of my followers or members of my Discord have asked me to do a tutorial on PyQT5. This is actually a tutorial on PyQT6. I figured I might as well show y’all the latest version if I’m going to learn a library. In this post we’re going to learn some PyQT and build a High Low Guessing Game.

Video version here:

To follow along you’ll need to install the PyQT library. You’re free to install PyQT5 if you want, I installed PyQT6. This is the command line command to install it:

pip install pyqt6

Import PyQT6 and Setup

As always we’re going to get started by importing the libraries we need. Since we’re building a High Low Guessing game, we’re going to need the random library. Obviously, this post is about PyQT5/PyQT6 so we’ll need the PyQT library as well. In this case, we aren’t going to import the whole library, we’re just going to import the QtWidgets library. What is the QtWidgets library? Well, it’s the library with the “widgets” aspect of the original Qt library from C++. After our imports we’ll use random to randomly generate a number between 0 and 100 to guess.

from PyQt6.QtWidgets import *
import random

num = random.randint(0, 100)

PyQT6 Alert Window and Game Logic

Now that we’ve imported our libraries and set up our game, it’s time to get the game logic handled. We’ll handle all the game logic of our High Low Guessing Game in the same function that we handle alerting our user. We’re going to alert our user with a PyQT QWidget called the QMessageBox(). The QMessageBox() is a widget used to give the user a message. In this case, we’re using it as an alert about whether your guess is too high or too low. We will also set a guessed variable to False. We’re going to be returning the guessed variable from this function to let our program know whether or not the user has guessed the right number.

After setting those two things up, we simply set up the logic of the game. If the guess is too high or too low let the user know. If the guess is spot on, then tell the user they’ve won and set guessed to True. After using the game logic to set the text of our QMessageBox() we will then exec() it. This is one of the differences between PyQT5 and PyQT6. PyQT6 uses exec() while PyQT5 uses exec_(). Then we return whether or not the user has guessed the number correctly.

def on_click(guess:int):
    alert = QMessageBox()
    guessed = False
    if guess > num:
        alert.setText(f"{guess} is too high")
    elif guess < num:
        alert.setText(f"{guess} is too low")
    else:
        alert.setText(f"You guessed it!")
        guessed = True
    alert.exec()
    return guessed

PyQT6 Window for Input and Playing the Game

Now it’s time to play the game. First we set guessing to True. Then we fire up a QApplication() with an empty list of arguments. The list of arguments passed to the QApplication() is meant to be a list of arguments to customize our app. In this case, we’re just going to use the default app. We don’t need to customize it. Usually what is passed in is sys.argv, the command line arguments.

While guessing is True, or while we are guessing (this is one of the neat things about Python), we will show the user a window where they can input a number to guess. We will simply open up an input dialog with QInputDialog() and use that. Notice that we can’t set the variable name to input because input is a native function to Python. I just get around that by naming it _input.

Next, we need to use the getInt() function from QInputDialog() to get our guess. It’s important to know that getInt() actually returns two values, the input integer, and a boolean value corresponding to whether or not the ok button was pressed. It also takes 3 parameters, the first parameter is the QWidget() that we are getting the input from, the second parameter is the title we want to give the window, and the third is the text we want to display.

From the input, we will get our guess and then when the ok button is pressed, we will run our guess against the game logic. If the user has guessed the number, we set guessing to False. On every guess I’ve chosen to print the guess to the command line, but you don’t need to do this. At the end of the while loop, we call the show() function to show our QInputDialog().

guessing = True
app = QApplication([])
while guessing:
    _input = QInputDialog()
    guess, ok = d.getInt(_input, "High Low Guessing Game", "Enter a number")
    if ok:
        guessed = on_click(guess)
        if guessed:
            guessing = False
    print(guess)
    _input.show()

PyQT Expected Output

When we run our program we’ll see something like this:

If we guess too high:

If we guess too low:

When we win:

Learn More

To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly