Hey folks, as we all are now aware that Python supports thousands of modules and packages to crack any logic behind the idea! And here also Python will help you play and create a very renowned and interesting game which we have all gotten our hands on since our childhood. Yes, you read it correctly game using Python and that’s Tic-Tac-Toe!, so let’s start our journey for Tic Tac Toe in Python Project with source code.
What is the Tic Tac Toe game?
Tic Tac Toe is a 2 player game where each player has a symbol (either X or O) and plays alternately to mark their symbol on a 3×3 grid.
If any player gets their(X or 0) symbol consecutively 3 times in a row, column or diagonal then that player is the winner. So, in total, we have 8 winning conditions: 3 for the rows, 3 for the columns, and 2 for the diagonals. Isn’t it interesting!
So, we will be coding it in Python using Tkinter for the interface.
‘Tkinter‘ is one of the known in-built libraries of Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. All you need to do is perform the following steps:
We first need to import the tkinter module.
Since we also have to display the results, we should use messagebox widget. As MessageBox Widget is used to display the message boxes in the python applications. Hence to use this, we have to import messagebox:
from tkinter import *
import tkinter.messagebox
Using * after import means we have imported all the methods and variables of the tkinter library.
Now, let’s create the GUI application’s main window i.e. game window.
Here, we will create a Tk widget and assign it to a variable root. And title() is used to set the title of the window.
Let’s assign two variables: click and count as well. Initialize ‘click’ to ‘True’ and ‘count’ to ‘0’. According to our logic, if click=True that means ‘X’ is clicking and if it is False that means it’s time for ‘0’ to click, while the count variable will check how many turns have been played, and after every turn, the count variable will be incremented by 1.
Coding Board for Tic Tac Toe in Python
root = Tk()
root.iconbitmap('tic tac toe.ico')
root.title('Tic-Tac-Toe')
root.resizable(False,False)
click = True
count = 0
btn1 = StringVar()
btn2 = StringVar()
btn3 = StringVar()
btn4 = StringVar()
btn5 = StringVar()
btn6 = StringVar()
btn7 = StringVar()
btn8 = StringVar()
btn9 = StringVar()
xPhoto = PhotoImage(file = 'cross.png')
oPhoto = PhotoImage(file = 'happy.png')
#grid buttons
def start():
button1 = Button(root,height=9,width=19,bd=.5,relief = 'sunken',bg = '#ccfff7',textvariable = btn1)
button1.grid(row=0,column=0)
button2 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn2)
button2.grid(row=0,column=1)
button3 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn3)
button3.grid(row=0,column=2)
button4 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn4)
button4.grid(row=1,column=0)
button5 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn5)
button5.grid(row=1,column=1)
button6 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn6)
button6.grid(row=1,column=2)
button7 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn7)
button7.grid(row=2,column=0)
button8 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn8)
button8.grid(row=2,column=1)
button9 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn9)
button9.grid(row=2,column=2)
start()
root.mainloop()
Output:
As you can see now, we have 9 buttons starting from button1 to button9 using the Button method of Tkinter in our Tic Tac Toe game board, and the window is in the grid format. As the first parameter, we have given the value root as the button to be inside the parent window.
Further, we have set the values of buttons with height=9 and width=19 and background color. And the start( ) function is used to directly start the window. You can play with those values for a better understanding.
Wasn’t that interesting?? And the rest of the code is as interesting as this!!
Now, whenever the button is clicked we are calling the ‘press function’. We have defined press() as a lambda function i.e. lambda() function is used to send specific data to the callback function. The statement for that is:
command=lambda: press()
Now, we will add this command to the button attribute:
def start():
button1 = Button(root,height=9,width=19,bd=.5,relief = 'sunken',bg = '#ccfff7',textvariable = btn1,
command=lambda: press(1,0,0))
button1.grid(row=0,column=0)
button2 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn2,
command=lambda: press(2,0,1))
button2.grid(row=0,column=1)
button3 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn3,
command=lambda: press(3,0,2))
button3.grid(row=0,column=2)
button4 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn4,
command=lambda: press(4,1,0))
button4.grid(row=1,column=0)
button5 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn5,
command=lambda: press(5,1,1))
button5.grid(row=1,column=1)
button6 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn6,
command=lambda: press(6,1,2))
button6.grid(row=1,column=2)
button7 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn7, command=lambda: press(7,2,0))
button7.grid(row=2,column=0)
button8 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn8,
command=lambda: press(8,2,1))
button8.grid(row=2,column=1)
button9 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn9,
command=lambda: press(9,2,2))
button9.grid(row=2,column=2)
Algorithm or Logic behind Tic Tac Toe
This is how it works. Whenever a player clicks on the button, we need to add symbols over it. The press() function does exactly the same. The parameters passed are num, r, and c. Let’s try to understand:
def press(num,r,c):
global click,count
if click == True:
labelPhoto = Label(root,image = xPhoto)
labelPhoto.grid(row=r,column=c)
if num == 1:
btn1.set('X')
elif num == 2:
btn2.set('X')
elif num == 3:
btn3.set('X')
elif num == 4:
btn4.set('X')
elif num == 5:
btn5.set('X')
elif num == 6:
btn6.set('X')
elif num == 7:
btn7.set('X')
elif num == 8:
btn8.set('X')
else:
btn9.set('X')
count += 1
click = False
checkWin()
else:
labelPhoto = Label(root,image = oPhoto)
labelPhoto.grid(row=r,column=c)
if num == 1:
btn1.set('O')
elif num == 2:
btn2.set('O')
elif num == 3:
btn3.set('O')
elif num == 4:
btn4.set('O')
elif num == 5:
btn5.set('O')
elif num == 6:
btn6.set('O')
elif num == 7:
btn7.set('O')
elif num == 8:
btn8.set('O')
else:
btn9.set('O')
count += 1
click = True
checkWin()
As we know, here press() function will help to check which button is pressed. If click=True that means ‘X’ is clicked and if click=False that means it’s time for ‘0’ to click and this will go back and forth.
In the above lines of code, we created a Label widget as well, which allows us to write something in the parent window. In the first parameter, we will give the value of the parent window i.e. here is its root. Further, in the second parameter, we have to set the text we have to display in the window i.e. we have passed the image as the parameter with the ‘X’ and ‘0’ images in it. To display these images we have used the Tkinter grid() method.
Now, we all are aware that tic tac toe is a two-player game. Isn’t it?
So, we will need to make two such labels as created above. Wasn’t that easy!
After this, it’s time to check who wins. For this purpose, we will check all the values for the player to win and we know there is a total of 8 winning conditions for the player to win, by checking which player makes three of their marks in a row(up, down, across, or diagonally).
def checkWin():
global count,click
if (btn1.get() == 'X' and btn2.get() == 'X' and btn3.get() == 'X' or
btn4.get() == 'X' and btn5.get() == 'X' and btn6.get() == 'X' or
btn7.get() == 'X' and btn8.get() == 'X' and btn9.get() == 'X' or
btn1.get() == 'X' and btn4.get() == 'X' and btn7.get() == 'X' or
btn2.get() == 'X' and btn5.get() == 'X' and btn8.get() == 'X' or
btn3.get() == 'X' and btn6.get() == 'X' and btn9.get() == 'X' or
btn1.get() == 'X' and btn5.get() == 'X' and btn9.get() == 'X' or
btn3.get() == 'X' and btn5.get() == 'X' and btn7.get() == 'X'):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'X Wins !')
click = True
count = 0
clear()
start()
elif (btn1.get() == 'O' and btn2.get() == 'O' and btn3.get() == 'O' or
btn4.get() == 'O' and btn5.get() == 'O' and btn6.get() == 'O' or
btn7.get() == 'O' and btn8.get() == 'O' and btn9.get() == 'O' or
btn1.get() == 'O' and btn4.get() == 'O' and btn7.get() == 'O' or
btn2.get() == 'O' and btn5.get() == 'O' and btn8.get() == 'O' or
btn3.get() == 'O' and btn6.get() == 'O' and btn9.get() == 'O' or
btn1.get() == 'O' and btn5.get() == 'O' and btn9.get() == 'O' or
btn3.get() == 'O' and btn5.get() == 'O' and btn7.get() == 'O'):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'O Wins !')
count = 0
clear()
start()
elif (count == 9):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'Tie Game!')
click = True
count = 0
clear()
start()
Finally, the check function will check the board row-wise, column-wise, and diagonal-wise for equality and displays the result of the game.
To display the result, showinfo() method in the messagebox widget is used. It shows some relevant information according to our conditions.
Output:
So, this is what our game will look like and we are almost done with it!!
After each game, this is how the winner will be displayed in another window.
Now, the game has been over so we will clear the tiles by defining a clear function i.e. clear():
def clear():
btn1.set('')
btn2.set('')
btn3.set('')
btn4.set('')
btn5.set('')
btn6.set('')
btn7.set('')
btn8.set('')
btn9.set('')
Finally, mainloop() method executes when we want to run the program and we are done!
Thus, we have developed one of the interesting game Tic Tac Toe using Tkinter in Python. Now, you know how easy it is to play this game. Let’s get hands over the complete code:
Complete Code for Tic Tac Toe in Python
#Tic Tac Toe game using tkinter
#Importing modules
from tkinter import *
import tkinter.messagebox
#Window defined
root = Tk()
root.iconbitmap('tic-tac-toe.ico')
root.title('Tic-Tac-Toe')
root.resizable(False,False)
click = True
#Count variable to check the no. of turns
count = 0
btn1 = StringVar()
btn2 = StringVar()
btn3 = StringVar()
btn4 = StringVar()
btn5 = StringVar()
btn6 = StringVar()
btn7 = StringVar()
btn8 = StringVar()
btn9 = StringVar()
xPhoto = PhotoImage(file = 'cross.png')
oPhoto = PhotoImage(file = 'happy.png')
#Grid buttons
def start():
button1 = Button(root,height=9,width=19,bd=.5,relief = 'sunken',bg = '#ccfff7',textvariable = btn1,
command=lambda: press(1,0,0))
button1.grid(row=0,column=0)
button2 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn2,
command=lambda: press(2,0,1))
button2.grid(row=0,column=1)
button3 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#ccfff7',textvariable = btn3,
command=lambda: press(3,0,2))
button3.grid(row=0,column=2)
button4 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn4,
command=lambda: press(4,1,0))
button4.grid(row=1,column=0)
button5 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn5,
command=lambda: press(5,1,1))
button5.grid(row=1,column=1)
button6 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#99ffee',textvariable = btn6,
command=lambda: press(6,1,2))
button6.grid(row=1,column=2)
button7 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn7,
command=lambda: press(7,2,0))
button7.grid(row=2,column=0)
button8 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn8,
command=lambda: press(8,2,1))
button8.grid(row=2,column=1)
button9 = Button(root,height=9,width=19,bd = .5,relief = 'sunken',bg = '#66ffe6',textvariable = btn9,
command=lambda: press(9,2,2))
button9.grid(row=2,column=2)
#Changing the value of button
def press(num,r,c):
global click,count
if click == True:
labelPhoto = Label(root,image = xPhoto)
labelPhoto.grid(row=r,column=c)
if num == 1:
btn1.set('X')
elif num == 2:
btn2.set('X')
elif num == 3:
btn3.set('X')
elif num == 4:
btn4.set('X')
elif num == 5:
btn5.set('X')
elif num == 6:
btn6.set('X')
elif num == 7:
btn7.set('X')
elif num == 8:
btn8.set('X')
else:
btn9.set('X')
count += 1
click = False
checkWin()
else:
labelPhoto = Label(root,image = oPhoto)
labelPhoto.grid(row=r,column=c)
if num == 1:
btn1.set('O')
elif num == 2:
btn2.set('O')
elif num == 3:
btn3.set('O')
elif num == 4:
btn4.set('O')
elif num == 5:
btn5.set('O')
elif num == 6:
btn6.set('O')
elif num == 7:
btn7.set('O')
elif num == 8:
btn8.set('O')
else:
btn9.set('O')
count += 1
click = True
checkWin()
#Checks the winner
def checkWin():
global count,click
if (btn1.get() == 'X' and btn2.get() == 'X' and btn3.get() == 'X' or
btn4.get() == 'X' and btn5.get() == 'X' and btn6.get() == 'X' or
btn7.get() == 'X' and btn8.get() == 'X' and btn9.get() == 'X' or
btn1.get() == 'X' and btn4.get() == 'X' and btn7.get() == 'X' or
btn2.get() == 'X' and btn5.get() == 'X' and btn8.get() == 'X' or
btn3.get() == 'X' and btn6.get() == 'X' and btn9.get() == 'X' or
btn1.get() == 'X' and btn5.get() == 'X' and btn9.get() == 'X' or
btn3.get() == 'X' and btn5.get() == 'X' and btn7.get() == 'X'):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'X Wins !')
click = True
count = 0
clear()
start()
elif (btn1.get() == 'O' and btn2.get() == 'O' and btn3.get() == 'O' or
btn4.get() == 'O' and btn5.get() == 'O' and btn6.get() == 'O' or
btn7.get() == 'O' and btn8.get() == 'O' and btn9.get() == 'O' or
btn1.get() == 'O' and btn4.get() == 'O' and btn7.get() == 'O' or
btn2.get() == 'O' and btn5.get() == 'O' and btn8.get() == 'O' or
btn3.get() == 'O' and btn6.get() == 'O' and btn9.get() == 'O' or
btn1.get() == 'O' and btn5.get() == 'O' and btn9.get() == 'O' or
btn3.get() == 'O' and btn5.get() == 'O' and btn7.get() == 'O'):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'O Wins !')
count = 0
clear()
start()
elif (count == 9):
tkinter.messagebox.showinfo("Tic-Tac-Toe", 'Tie Game!')
click = True
count = 0
clear()
start()
#Clear the tiles
def clear():
btn1.set('')
btn2.set('')
btn3.set('')
btn4.set('')
btn5.set('')
btn6.set('')
btn7.set('')
btn8.set('')
btn9.set('')
start()
root.mainloop()
Now, let’s run the code and check the output:
Output:
Here it is! See, How easy it was!
NOTE : Enter the path of the images you are using in your code.
Thanks for reading Tic Tac Toe in Python, visit our website for more, try to code, and practice the same. Happy Coding!!
Also Read:
- Create your own ChatGPT with Python
- Bakery Management System in Python | Class 12 Project
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Hostel Management System Project in Python
- Sales Management System Project in Python
- Bank Management System Project in C++
- Python Download File from URL | 4 Methods
- Python Programming Examples | Fundamental Programs in Python
- Spell Checker in Python
- Portfolio Management System in Python
- Stickman Game in Python
- Contact Book project in Python
- Loan Management System Project in Python
- Cab Booking System in Python
- Brick Breaker Game in Python
- Tank game in Python
- GUI Piano in Python
- Ludo Game in Python
- Rock Paper Scissors Game in Python
- Snake and Ladder Game in Python
- Puzzle Game in Python
- Medical Store Management System Project in Python
- Creating Dino Game in Python
- Tic Tac Toe Game in Python
- Test Typing Speed using Python App
- MoviePy: Python Video Editing Library
- Scientific Calculator in Python
- GUI To-Do List App in Python Tkinter