
Tic Tac Toe 🎮 with Python tkinter - part 1
3 May, 2022
18
18
0
Contributors
In this tutorial, we will be creating a basic Tic Tac Toe game 🎮 with Python tkinter. If you are new to tkinter, refer this crash course: https://www.showwcase.com/show/13940/getting-started-with-tkinter-crash-course
Webpage version: https://www.showwcase.com/show/14592/tic-tac-toe-with-html-css-and-js-part-1
The GUI 👀
Let's go ahead and create a GUI for the game.
Step 1: Create a tkinter window
Step 2: Add play area and a label with text "Tic Tac Toe"
Step 3: Make the GUI functional
Let's make the GUI functional by changing button text and color when clicked. For this, we need to make some changes to class "XOPoint" in code.
Detect win and draw 🤔
Let's now implement a logic to detect win/draw.
Step 4: Implement logic to detect win
We need to check after each move if X or O won the game. There are 8 possible ways in which one can win Tic Tac Toe:
Let's modify the code to detect game win.
Step 5: Detect draw
If all 9 squares were filled and still no one won the game, it's a draw! Detecting game draw is simple. Just append the following code to the function "check_win".
Enhancements
Now that everything works fine, we can improve it further.
Step 6: Status Label
Tic Tac Toe is a GUI game and displaying game result in GUI is better than printing them in console. So, let's create a tkinter Label via which we can display result. Add the following code:
Also, we need to make some changes to function "check_win":
Step 7: Display whose turn it is
The status label is not used till someone wins the game. Let's use it to display if it's X's turn or O's turn! We need to make some changes to function "set" in class "XOPoint".
Also, the text property of status label must be changed:
Step 8: Create Play again button
Once the game is over, the game needs to be disabled and a button to play the game again must be displayed. Let's add the following code to disable the game once it is over:
We need to make changes to the function "check_win" and to the for loops that create "XOPoint" objects:
Add the following code to display Play again button once the game is over:
We also need to make changes to function "disable_game" and function "reset" in class "XOPoint":
Summary
The steps done in this tutorial are:
- Create a tkinter window.
- Add play area and a label with text "Tic Tac Toe".
- Make the GUI functional.
- Implement logic to detect win.
- Detect draw.
- Status Label.
- Display whose turn it is.
- Create Play again button.
Final code:
GitHub repo link: https://github.com/Jothin-kumar/tic-tac-toe
If you find this article useful, drop a like ⭐ and follow me to get all my latest content.
Part 2 of this tutorial: https://www.showwcase.com/show/14918/tic-tac-toe-with-python-tkinter-part-2
python
tutorial
tictactoe
tkinter
beginner