from tkinter import * from tkinter.ttk import * PLAYER1 = "X" PLAYER2 = "O" class TicTacToe: '''A graphical game of Tic Tac Toe using tkinter.''' def __init__(self, window): '''Initialize the game window components.''' window.title("Tic-Tac-Toe") style = Style() style.configure('TButton', font=('Sans', '48', 'bold'), padding=30) style.configure('TLabel', font=('Sans', '24', 'bold')) self.display_text = StringVar() display = Label(window, textvariable=self.display_text) display.grid(row=0, column=0, columnspan=3) self.populate_board(window) self.turn = PLAYER1 self.display_text.set('Next player: ' + self.turn) def populate_board(self, window): '''Set up the buttons making up the game board.''' self.board = [] for row_num in range(3): board_row = [] for col_num in range(3): button_text = StringVar() button = Button( window, textvariable = button_text, command = self.button_action(row_num, col_num), width = 1 # make buttons square ) button.grid(row=row_num + 1, column=col_num) board_row.append(button_text) self.board.append(board_row) def button_action(self, row_num, col_num): '''Construct a callback function for the given (row, col).''' def button_callback(): '''Executes whenever a button is clicked to make a play.''' button_text = self.board[row_num][col_num] if self.turn == PLAYER1: button_text.set(PLAYER1) self.turn = PLAYER2 else: button_text.set(PLAYER2) self.turn = PLAYER1 self.display_text.set('Next player: ' + self.turn) return button_callback def main(): window = Tk() TicTacToe(window) window.mainloop() main()