#!/usr/bin/env python3
from tkinter import *
class Game(Frame):
def __init__(self, master=None):
# TK stuff
Frame.__init__(self, master)
self.master = master
# Function where we can setup buttons
self.initialize_window()
# Setup some game stuff
self.current_player = "X"
def initialize_window(self):
# This will be the title of the program
self.master.title('Tic Tac Toe')
self.pack(fill=BOTH, expand=1)
# Below is the code to create some buttons in a grid
# Each button has a command which is calls the button_press function with the number of the button
#Create the first row of buttons
button0 = Button(self, text="0", height=8, width=12, command=lambda: self.button_press(0))
button0.grid(row=1,column=1)
button1 = Button(self, text="1", height=8, width=12, command=lambda: self.button_press(1))
button1.grid(row=1,column=2)
button2 = Button(self, text="2", height=8, width=12, command=lambda: self.button_press(2))
button2.grid(row=1,column=3)
# Create the second row of buttons
button3 = Button(self, text="3", height=8, width=12, command=lambda: self.button_press(3))
button3.grid(row=2,column=1)
button4 = Button(self, text="4", height=8, width=12, command=lambda: self.button_press(4))
button4.grid(row=2,column=2)
button5 = Button(self, text="5", height=8, width=12, command=lambda: self.button_press(5))
button5.grid(row=2,column=3)
# Create the third row of buttons
# Store our buttons in a list so we can reference them later
# Obviously for tic tac toe you will need another row of buttons
#self.buttons = [button0, button1, button2, button3, button4, button5, button5, button6, button7, button8]
self.buttons = [button0, button1, button2, button3, button4, button5, button5]
def button_press(self, number):
# The button press passes the index of the button which we can get from our list
btn = self.buttons[number]
# We then call the config method on the button and update the buttons text
# Self.current_player is just a string that is set to "X" when the program starts
# We also disable the button so that no one tries to move in a spot that was already taken
btn.config(text = self.current_player, state=DISABLED)
# After the player has made a move we switch to the next player
# You will need to add logic to choose the next player based upon who just moved
self.current_player = "O"
self.current_player = "X"
if __name__ == '__main__':
root = Tk()
app = Game(root)
root.mainloop()