Build a Rock‑Paper‑Scissors Game with PyQt5: Step‑by‑Step Guide
This tutorial walks you through creating a fully functional Rock‑Paper‑Scissors desktop game using PyQt5, covering window setup, grid layout, widget placement, signal‑slot connections, random image selection, score tracking, and graceful exit handling, all illustrated with screenshots.
1. Introduction
Recently I started learning PyQt5, a rich GUI library that is more powerful and visually appealing than Tkinter. I decided to create a visual Rock‑Paper‑Scissors game to demonstrate its capabilities.
2. Implementation
Step 1: Create the main window
In PyQt5, create an application object with app = QApplication(sys.argv) and start the event loop using sys.exit(app.exec_()). Define a GameWindow class with a size of 900×400, then set the window title and icon.
The window displays as shown in the following screenshot.
Step 2: Arrange widgets with a grid layout
PyQt5 offers five layout types; this tutorial uses the grid layout. The 3×3 grid hosts the player labels, round indicator, and score displays. Widgets are added with addWidget(widget, row, column).
Images for the three choices are placed in the second row, while the middle cell of that row contains a nested grid showing red score, "VS", and blue score.
Step 3: Bind signals to slots
Use QPushButton to create "Start Game" and "Restart" buttons, connecting them to gamestart and restart functions respectively, and place them in the third row.
The basic framework is now complete.
Step 4: Game logic
The gamestart function randomly selects one of the three images (rock, paper, scissors) and displays it. It then calls judge to determine the winner, updating red score, blue score, and draw count via setText.
A close‑event handler prompts the user before exiting.
3. Conclusion
The PyQt5 Rock‑Paper‑Scissors game demonstrates window creation, grid layout, widget interaction, signal‑slot binding, random selection, and score tracking. The source code is available on GitHub; reply with the keyword “剪刀石头布” to receive the repository link.
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.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
