Tic tac toe python tkinter code
Playing computer games is a great way to unwind or challenge yourself. Some people even do it professionally. It’s also fun and educational to build your own computer games. In this tutorial, you’ll build a classic tic-tac-toe game using Python and Tkinter. Show
With this project, you’ll go through the thought processes required for creating your own game. You’ll also learn how to integrate your diverse programming skills and knowledge to develop a functional and fun computer game. In this tutorial, you’ll learn how to:
As mentioned, you’ll be using the Tkinter GUI framework from the Python standard library to create your game’s interface. You’ll also use the model-view-controller pattern and an object-oriented approach to organize your code. For more on these concepts, check out the links in the prerequisites. To download the entire source code for this project, click the link in the box below: Demo: A Tic-Tac-Toe Game in PythonIn this step-by-step project, you’ll build a tic-tac-toe game in Python. You’ll use the Tkinter tool kit from the Python standard library to create the game’s GUI. In the following demo video, you’ll get a sense of how your game will work once you’ve completed this tutorial:
Your tic-tac-toe game will have an interface that reproduces the classic three-by-three game board. The players will take turns making their moves on a shared device. The game display at the top of the window will show the name of the player who gets to go next. If a player wins, then the game display will show a winning message with the player’s name or mark (X or O). At the same time, the winning combination of cells will be highlighted on the board. Finally, the game’s File menu will have options to reset the game if you want to play again or to exit the game when you’re done playing. If this sounds like a fun project to you, then read on to get started! Project OverviewYour goal with this project is to create a tic-tac-toe game in Python. For the game interface, you’ll use the Tkinter GUI tool kit, which comes in the standard Python installation as an included battery. The tic-tac-toe game is for two players. One player plays X and the other plays O. The players take turns placing their marks on a grid of three-by-three cells. If a given player gets three marks in a row horizontally, vertically, or diagonally, then that player wins the game. The game will be tied if no one gets three in a row by the time all the cells are marked. With these rules in mind, you’ll need to put together the following game components:
The game board will work as a mix between view and controller in a model-view-controller design. To build the board, you’ll use a Tkinter window, which you can create by instantiating the
You’ll create the game display using a For the grid of cells, you’ll use a series of
Now that you have a general idea of how to build your tic-tac-toe game, you should check out a few knowledge prerequisites that’ll allow you to get the most out of this tutorial. PrerequisitesTo complete this tic-tac-toe game project, you should be comfortable or at least familiar with the concepts and topics covered in the following resources:
If you don’t have all of the suggested knowledge before starting this tutorial, that’s okay. You’ll learn by doing, so go ahead and give it a whirl! You can always stop and review the resources linked here if you get stuck. Step 1: Set Up the Tic-Tac-Toe Game Board With TkinterTo kick things off, you’ll start by creating the game board. Before doing this, you need to decide how to organize the code for your tic-tac-toe game. Because this project will be fairly small,
you can initially keep all the code in a single Go ahead and fire up your favorite code editor or IDE. Then create a
Throughout this tutorial, you’ll be incrementally adding code to this file, so keep it open and near. If you want to get the entire code for this tic-tac-toe game project, then you can click the following collapsible section and copy the code from it:
Having the entire source code beforehand will allow you to check your progress while going through the tutorial. Alternatively, you can also download the game source code from GitHub by clicking the link in the box below: Now that you know what the game’s final code will look like, it’s time to make sure you have the right Tkinter version for this project. Then, you’ll go ahead and create your game board. Ensure the Right Tkinter VersionTo complete this project, you’ll use a standard Python installation. There’s no need to create a virtual environment because no external dependency is required. The only package that you’ll need is Tkinter, which comes with the Python standard library. However, you need to make sure that you have the right Tkinter version installed. You should have Tkinter greater than or equal to 8.6. Otherwise, your game won’t work. You can check your current Tkinter version by starting a Python interactive session and running the following code: >>>
If this code doesn’t show a version greater than or equal to 8.6 for your Tkinter installation, then you’ll need to fix that. On Ubuntu Linux, you may need to install the Once you have Tkinter properly installed, then you need to check its current version. If the Tkinter version is lower than 8.6, then you’ll have to install a more recent version of Python either by downloading it from the official download page or by using a tool like pyenv or Docker. On macOS and Windows, a straightforward option is to install a Python version greater than or equal to 3.9.8 from the download page. Once you’re sure you have the right Tkinter version, you can get back to your code editor and start writing code. You’ll begin with the Python class that’ll represent the tic-tac-toe game board. Create a Class to Represent the Game BoardTo build the board of your tic-tac-toe game,
you’ll use the Go ahead and import the required objects and define the board class:
In this code snippet, you first import Then you import the The The The To continue with the game board, you now need to create a display where you can provide information about the
game’s state and result. For this display, you’ll use a Now go ahead and add the following method to your
Here’s a breakdown of what this method does line by line:
Cool! You already have the game display. Now you can create the grid of cells. A classic tic-tac-toe game has a three-by-three grid of cells. Here’s a method that creates the grid of cells using
Wow! This method does a lot! Here’s an explanation of what each line does:
Now that you’ve implemented
These two lines put together the game board by adding the display and grid of cells. Isn’t that cool? With
these updates, you can almost run your app and see how your tic-tac-toe game will look. You just need to write a few more lines of boilerplate code. You need to instantiate Go ahead and add the following piece of code to the end of your
This code snippet defines a The That’s it! You’re now ready to run your game for the first time. Of course, the game isn’t playable yet, but the board is ready. To run the game, go ahead and execute the following command on your command line: Once you’ve run this command, then you’ll get the following window on your screen: Cool! Your tic-tac-toe game is starting to look like the real thing. Now you need to make this window respond to the players’ actions on the board. Step 2: Set Up the Tic-Tac-Toe Game Logic in PythonUp to this point, you’ve put together a suitable tic-tac-toe game board using Tkinter. Now you need to think of how to deal with the game’s logic. This logic will consist of code that processes a player’s move and determines if this player has won the game or not. Several ideas are key when it comes to implementing the logic of a tic-tac-toe game. First, you need a valid representation of the players and their moves. You also need a higher-level class to represent the game itself. In this section, you’ll define classes for these three logic concepts. You can download the source code for this step by clicking the link below and navigating to the Define Classes for the Players and Their MovesIn the first round, you’ll define classes to represent players and their moves on the game board. These classes will be pretty bare-bones. All they need is a few attributes each. They don’t even need to have any methods. You can use a few tools to build classes that fulfill these requirements. For example, you can use either a data class or a named tuple. In this tutorial, you’ll use a named tuple for both classes because this kind of class provides all you need. Instead of using the classic Go back to your code editor and add the following code at the beginning of your
Here’s a breakdown of this code snippet:
With these two classes in place, now you can define the class that you’ll use to represent the game logic. Create a Class to Represent the Game LogicIn this section, you’ll define a class to manage the game’s logic. This class will take care of processing the moves, finding a winner, toggling players, and performing a few other tasks. Get back to your
Here, you first import
The Inside
The Regarding the last line in Now go ahead and define the following constants right below the
As you already learned, On the other hand, Set Up the Abstract Game BoardManaging the game’s state in every moment is a fundamental step in the game’s logic. You need to keep track of every move on the board. To do this, you’ll use the You also need to determine which cell combinations on the board determine a win. You’ll store these combinations in the Here’s the
In The last line of this method calls Figure Out the Winning CombinationsOn a classic tic-tac-toe board, you’ll have eight possible winning combinations. They’re essentially the rows, columns, and diagonals of the board. The following illustration shows these winning combinations: How would you get the coordinates of all these combinations using Python code? There are several ways to do it. In the code below, you’ll use four list comprehensions to get all the possible winning combinations:
The main input for this method is the The first comprehension iterates over the rows on the grid, getting the coordinates of every cell and building a sublist of coordinates. Each sublist of coordinates represents a winning combination. The second comprehension creates sublists containing the coordinates of each cell in the grid columns. The third and fourth comprehensions use a similar approach to get the coordinates of every cell in the board diagonals. Finally, the method returns a list of lists containing all possible winning combinations on the tic-tac-toe board. With this initial setup for your game board, you’re ready to start thinking about processing the players’ moves. Step 3: Process the Players’ Moves on the Game’s LogicIn this tic-tac-toe game, you’ll mostly handle one type of event: players’ moves. Translated to Tkinter terms, a player’s move is just a click on the selected cell, which is represented by a button widget. Every player’s move will trigger a bunch of operations on the
In the following sections, you’ll write the code to handle all these operations in your To download the source code for this step from GitHub, click the link below and navigate to the Validate Players’ MovesYou need to validate the move every time a player clicks a given cell on the tic-tac-toe board. The question is: What defines a valid move? Well, at least two conditions make a move valid. Players can only play if:
Go ahead and add the following method to the
end of
The
This method returns a Boolean value that results from checking if the game has no winner and the current move hasn’t been played yet. Process Players’ Moves to Find a WinnerNow it’s time for you to determine if a player has won the game after their last move. This may be your chief concern as the game designer. Of course, you’ll have many different ways to find out if a given player has won the game. In this project, you’ll use the following ideas to determine the winner:
To find out if the last player has won the game, you’ll check if the player’s label is present in all the possible moves contained in a given winning combination. Go ahead and add the following method to your
Here’s a breakdown of what this new method does line by line:
On lines 12 to 16, a few points and ideas need clarification. To better understand lines 12 to 15, say that all the labels in the moves associated with the cells of the current winning combination hold an X. In that case, the generator expression will yield three X labels. When you feed the built-in So, if the set in To wrap up the topic of finding the winner of your tic-tac-toe game, go ahead and add the following method at the end of your
This method returns the Boolean value stored in Check for Tied GamesIn the tic-tac-toe game, if the players play on all the cells and there’s no winner, then the game is tied. So, you have two conditions to check before declaring the game as tied:
Go ahead and add the following method at the end of
Inside Toggle Players Between TurnsEvery time a player makes a valid move, you need to toggle the current player so that the other player can make the next move. To provide this functionality, go ahead and add the following method to your
Because Step 4: Process Players’ Moves on the Game BoardAt this point, you’re able to handle the players’ moves on the game logic. Now you have to connect this logic to the game board itself. You also need to write the code to make the board respond to players’ moves. First, go ahead and inject the game logic into the game board. To do this, update the
In this code snippet, you first add a The second update is to use With
these updates, you’re ready to dive into handling the players’ moves on the As usual, you can download the source code for this step by clicking the link below and navigating to the Handle a Player’s Move EventThe When a player in your tic-tac-toe game clicks a cell, a click event occurs inside the game’s event loop. You can process this event by providing an appropriate handler method
on your
This method is fundamental in your tic-tac-toe game because it puts together almost all the game logic and GUI behavior. Here’s a summary of what this method does:
You’re almost there! With a few more updates and additions, your tic-tac-toe game will be ready for its first-ever match. The next step is to connect every button on the game board to the
The highlighted line
binds the click event of every button on the game board with the Update the Game Board to Reflect the Game StateTo complete the code for processing the players’ moves on the game board, you need to write three helper methods. These methods will complete the following actions:
To kick things off, go ahead and add
In this code snippet, The next helper method to add is
In this method, instead of using Finally, you need a helper method to highlight the winning cells once a given player makes a winning move:
The loop inside With this last helper method in place, your tic-tac-toe game is ready for the first match! Run Your Tic-Tac-Toe Game for the First TimeTo finish putting together the logic and the user interface of your tic-tac-toe game, you need to update the
game’s Get back to
In this code, the first highlighted line creates an instance of With these updates in place, you can now run your game. To do this, fire up a terminal window and navigate to the directory containing your Once this command has run, then your game’s main window will appear on your screen. Go ahead and give it a try! It’ll behave something like this:
Wow! Your game project looks amazing so far! It allows two players to share their mouse and play a classic tic-tac-toe match. The game GUI looks nice and, in general, the game works as expected. In the following section, you’ll write code to allow the players to restart the game and play again. You’ll also provide the option of exiting the game. Step 5: Provide Options to Play Again and Exit the GameIn this section, you’ll provide your tic-tac-toe game with a main menu. This menu will have an option to restart the game so that the players can start another match. It’ll also have an option to exit the game once the players have finished playing. Main menus are often an essential component of many GUI applications. So, learning how to create them in Tkinter is a good exercise to improve your GUI-related skills beyond the game development itself. This is an example of how building your own games is a powerful learning experience because it allows you to integrate knowledge and skills that you can later use in other non-game projects. The complete source code for this step is available for download. Just click the link below and navigate to the Build the Game’s Main MenuTo add a main menu to a Tkinter application, you can use the Here’s the code that creates and adds a main menu to your tic-tac-toe game:
Here’s what this code does line by line:
To actually add the main menu to your game’s
main window, you need to call
With this final update, your game’s main menu is almost ready for use. However, before using it, you must implement the Implement the Play Again OptionTo reset the game board and allow the players to play again, you need to add code to both classes, In the game logic class, you need to reset the Get back to
The After updating the current moves, the methods sets Note that Once you’ve provided the required new functionality in the game logic, then you’re ready to update the game board functionality. Go ahead and add the
following method to the end of
This
That’s it! With this last feature, your tic-tac-toe game project is complete. Go ahead and give it a try! ConclusionThroughout this step-by-step project, you’ve created a classic tic-tac-toe computer game using Python and Tkinter. This GUI framework is available in the Python standard library. It runs on Windows, Linux, and macOS, so your game will work great on all three platforms. That’s pretty cool! In this tutorial, you learned how to:
This knowledge provides you with the foundation for creating new and more complex games and GUI projects, which will help you take your Python skills to the next level. Next StepsThe tic-tac-toe game that you implemented in this tutorial is fairly bare-bones. However, you can expand it in several different and fun ways. Some ideas to take this game project to the next level include allowing your users to:
What other ideas can you come up with to extend this project? Be creative and have fun! Now that you’ve completed this project, here are some additional great projects to continue building your own games with Python:
How do you make a tic tac toe in tkinter Python?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.. Can you make a game using tkinter?TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games.
How do I use tkinter in Python?Python Tkinter Tutorial. import the Tkinter module.. Create the main application window.. Add the widgets like labels, buttons, frames, etc. to the window.. Call the main event loop so that the actions can take place on the user's computer screen.. |