Python Forum
Tk .set not working in parts of code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tk .set not working in parts of code
#1
I am having an issue using tk. I have a label that dynamically changes based on conditions. There are at least 5 different conditions that can change the text. They all seem to work except 1. As far as I can tell I have it set-up just like all the others. My code is raw, I am still working on it. I am new and teaching my self so go easy on me :). I am making a tic tac toe game. The problem is in the showWinner function. I cannot get the message2 label to show the winning play. I will try to highlight the problem area. I have some print statements in there to help debug. I am sure things can be cleaned up, I'm just trying to get it working first. It is only set up to test row A, so entering 1 1 X, 1 2 X, and 1 3 X should send you to showWinner where the label should change.
from tkinter import *
from tkinter import ttk

def reset():
    pass

def makeList(*args):    
    gameSpaceValue = list(valueEntry.get())
    print(gameSpaceValue)
    gameSpaceValue.pop(1)
    gameSpaceValue.pop(2)
    print(gameSpaceValue)
    checkList(gameSpaceValue,gameBoard)

def checkList(gameSpaceValue,gameBaord):
    count = 0
    error = False
    for i in gameSpaceValue:
        count+=1
        print(count)
    if count >=4:
        error = True
        message2.set(warning1)
    if count <=2:
        error = True
        message2.set(warning2)
    if error == False:
        try:
            str1Check = int(gameSpaceValue[0])
        except:
            message2.set(warning3)
            error = True
    if error == False:
        try:
            str1Check = int(gameSpaceValue[1])
        except:
            message2.set(warning4)
            error = True
    if error == False:
        letter = gameSpaceValue[2].capitalize()
        Letter.set(letter)
        if letter == 'X' or letter == 'O':
            checkBoard(gameSpaceValue, letter, gameBoard)
        else:
            message2.set(warning6)

def checkBoard(gameSpaceValue, letter, gameBaord):
        if int(gameSpaceValue[0]) == 1:
            gameSpaceValue[0] = 0
        if int(gameSpaceValue[1]) == 1:
            gameSpaceValue[1] = 0
        if int(gameSpaceValue[0]) == 2:
            gameSpaceValue[0] = 1
        if int(gameSpaceValue[1]) == 2:
            gameSpaceValue[1] = 1
        if int(gameSpaceValue[0]) == 3:
            gameSpaceValue[0] = 2
        if int(gameSpaceValue[1]) == 3:
            gameSpaceValue[1] = 2
        gSx = gameSpaceValue[0]
        gSy = gameSpaceValue[1]
        if gameBoard[gSx][gSy] == ' ':
            gameBoard[gSx][gSy] = letter
            rowA = gameBoard[0]
            rowB = gameBoard[1]
            rowC = gameBoard[2]
            columnA = [gameBoard[0][0],gameBoard[1][0],gameBoard[2][0]]
            columnB = [gameBoard[0][1],gameBoard[1][1],gameBoard[2][1]]
            columnC = [gameBoard[0][2],gameBoard[1][2],gameBoard[2][2]]
            diagonalA = [gameBoard[0][0],gameBoard[1][1],gameBoard[2][2]]
            diagonalB = [gameBoard[0][2],gameBoard[1][1],gameBoard[2][0]]
            displayBoard(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter)
            value.delete(0,5)
            message2.set(warning7)
            
        else:
            message2.set(warning5)

def displayBoard(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter):
    #strRowA = str(rowA[0]) + ' ' +  str(rowA[1]) + ' ' + str(rowA[2])
    '''
    dispRowA.set(rowA)
    dispRowB.set(rowB)
    dispRowC.set(rowC)
    winningLine = StringVar()
    '''
    dispA10.set(rowA[0])
    dispA11.set(rowA[1])
    dispA12.set(rowA[2])
    dispB20.set(rowB[0])
    dispB21.set(rowB[1])
    dispB22.set(rowB[2])
    dispC30.set(rowC[0])
    dispC31.set(rowC[1])
    dispC32.set(rowC[2])

    findWinner(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter)

def findWinner(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter):

    print('in findwinner', rowA)
    won = all(x == letter for x in rowA)
    print(won)
    if won == True:
        winningLine.set(rowA)
        showWinner(winningLine, letter)
        #winningLine.set(RowA)
        #message2.set(winner)
    if won != True:
        won = all(x == letter for x in rowB)
        if won is True:                    
            winningLine.set(RowB)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in rowC)
        if won is True:
            winningLine.set(RowC)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnA)
        if won is True:
            winningLine.set(ColumnA)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnB)
        if won is True:
            winningLine.set(ColumnB)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnC)
        if won is True:
            winningLine.set(ColumnC)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in diagonalA)
        if won is True:
            winningLine.set(DiagonalA)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in diagonalB)
        if won is True:
            winningLine.set(DiagonalB)
            message2.set(winner)

[size=x-large]def showWinner(winningLine, letter):

        message2.set(winnerRA)[/size]
                
root = Tk()
root.title("Tic-Tac-Toe")
root.bind("<Return>", makeList)

mainFrame = ttk.Frame(root, padding="3 3 12 12")
mainFrame.grid()

#correctEntries = ['1 1 X','1 2 X','1 3 X','2 1 X','2 2 X','2 3 X','3 1 X','3 2 X','3 3 X','1 1 O','1 2 O','1 3 O',
#                '2 1 O','2 2 O','2 3 O','3 1 O','3 2 O','3 3 O'] 

gameBoard = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
valueEntry = StringVar()
dispRowA = StringVar()
dispRowB = StringVar()
dispRowC = StringVar()
message1 = StringVar()

[size=x-large]message2 = StringVar()[/size]

letter = StringVar()
Letter = StringVar()
winner = StringVar()
winningLine = StringVar()
dispA10 = StringVar()
dispA11 = StringVar()
dispA12 = StringVar()
dispB20 = StringVar()
dispB21 = StringVar()
dispB22 = StringVar()
dispC30 = StringVar()
dispC31 = StringVar()
dispC32 = StringVar()

[size=x-large]winnerRA = StringVar()[/size]

directions = ('Please enter a 1,2 or 3 for the row, a space, a 1,2 or 3 for the column, a space, and an X or O for the marker.')
warning1 = ('You entered too many characters.  Example: 1 1 X')
warning2 = ('You did not enter enough characters.  Example: 2 3 O')
warning3 = ('Please enter only a 1,2 or 3 for your row choice.')
warning4 = ('Please enter only a 1,2, or 3 for your column choice.')
warning5 = ('The space you entered is already taken, please choose a different space.')
warning6 = ('Please enter either an X or O for your marker.')
warning7 = (' ')

[size=x-large]winnerRA = ('X player, you are the winner.  You won with RowA.  Hit reset to play again.')[/size]

RowA = 'Row A'
RowB = 'Row B'
RowC = 'Row C'
ColumnA = 'Column A'
ColumnB = 'Column B'
ColumnC = 'Column C'
DiagonalA = 'Diagonal A'
DiagonalB = 'Diagonal B'
#winner = (Letter,'player, you are the winner.  You won with ',winningLine,'.  Hit reset to play again.')

message1.set(directions)
    
directionsLabel = ttk.Label(mainFrame, textvariable = message1)
directionsLabel.grid(column = 2, columnspan = 5, row = 1)

[size=x-large]messageLabel = ttk.Label(mainFrame, textvariable = message2)
messageLabel.grid(column = 2, columnspan = 5, row = 2)[/size]


value = ttk.Entry(mainFrame, width=7, textvariable=valueEntry)
value.focus_set()
value.grid(column = 2, columnspan = 5, row = 3)

enterButton = ttk.Button(mainFrame, text="Enter", command = makeList)
enterButton.grid(column = 2, columnspan = 5, row = 4)
resetButton = ttk.Button(mainFrame,text="Reset",command = reset)
resetButton.grid(column = 2, columnspan = 5, row = 5)

gameFrame = ttk.Frame(mainFrame)
gameFrame.grid(column = 2, columnspan = 5, row = 6)
gameFrame10 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame10.grid(column = 0, row = 1 )
gameFrame11 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame11.grid(column = 1, row = 1)
gameFrame12 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame12.grid(column = 2, row = 1)
gameFrame20 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame20.grid(column = 0, row = 2 )
gameFrame21 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame21.grid(column = 1, row = 2)
gameFrame22 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame22.grid(column = 2, row = 2)
gameFrame30 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame30.grid(column = 0, row = 3 )
gameFrame31 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame31.grid(column = 1, row = 3)
gameFrame32 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame32.grid(column = 2, row = 3)

rowAdisp1 = ttk.Label(gameFrame10, textvariable = dispA10, width = 2)
rowAdisp1.grid()
rowAdisp2 = ttk.Label(gameFrame11, textvariable = dispA11, width = 2)
rowAdisp2.grid()
rowAdisp3 = ttk.Label(gameFrame12, textvariable = dispA12, width = 2)
rowAdisp3.grid()
rowBdisp1 = ttk.Label(gameFrame20, textvariable = dispB20, width = 2)
rowBdisp1.grid()
rowBdisp2 = ttk.Label(gameFrame21, textvariable = dispB21, width = 2)
rowBdisp2.grid()
rowBdisp3 = ttk.Label(gameFrame22, textvariable = dispB22, width = 2)
rowBdisp3.grid()
rowCdisp1 = ttk.Label(gameFrame30, textvariable = dispC30, width = 2)
rowCdisp1.grid()
rowCdisp2 = ttk.Label(gameFrame31, textvariable = dispC31, width = 2)
rowCdisp2.grid()
rowCdisp3 = ttk.Label(gameFrame32, textvariable = dispC32, width = 2)
rowCdisp3.grid()
Reply
#2
It looked like you did a global find and replace or something like that and it screwed things up. I think this is working how you wanted it now. Let me know.

from tkinter import *
from tkinter import ttk
 
def reset():
    pass
 
def makeList(*args):    
    gameSpaceValue = list(valueEntry.get())
    print(gameSpaceValue)
    gameSpaceValue.pop(1)
    gameSpaceValue.pop(2)
    print(gameSpaceValue)
    checkList(gameSpaceValue,gameBoard)
 
def checkList(gameSpaceValue,gameBaord):
    count = 0
    error = False
    for i in gameSpaceValue:
        count+=1
        print(count)
    if count >=4:
        error = True
        message2.set(warning1)
    if count <=2:
        error = True
        message2.set(warning2)
    if error == False:
        try:
            str1Check = int(gameSpaceValue[0])
        except:
            message2.set(warning3)
            error = True
    if error == False:
        try:
            str1Check = int(gameSpaceValue[1])
        except:
            message2.set(warning4)
            error = True
    if error == False:
        letter = gameSpaceValue[2].capitalize()
        Letter.set(letter)
        if letter == 'X' or letter == 'O':
            checkBoard(gameSpaceValue, letter, gameBoard)
        else:
            message2.set(warning6)
 
def checkBoard(gameSpaceValue, letter, gameBaord):
        if int(gameSpaceValue[0]) == 1:
            gameSpaceValue[0] = 0
        if int(gameSpaceValue[1]) == 1:
            gameSpaceValue[1] = 0
        if int(gameSpaceValue[0]) == 2:
            gameSpaceValue[0] = 1
        if int(gameSpaceValue[1]) == 2:
            gameSpaceValue[1] = 1
        if int(gameSpaceValue[0]) == 3:
            gameSpaceValue[0] = 2
        if int(gameSpaceValue[1]) == 3:
            gameSpaceValue[1] = 2
        gSx = gameSpaceValue[0]
        gSy = gameSpaceValue[1]
        if gameBoard[gSx][gSy] == ' ':
            gameBoard[gSx][gSy] = letter
            rowA = gameBoard[0]
            rowB = gameBoard[1]
            rowC = gameBoard[2]
            columnA = [gameBoard[0][0],gameBoard[1][0],gameBoard[2][0]]
            columnB = [gameBoard[0][1],gameBoard[1][1],gameBoard[2][1]]
            columnC = [gameBoard[0][2],gameBoard[1][2],gameBoard[2][2]]
            diagonalA = [gameBoard[0][0],gameBoard[1][1],gameBoard[2][2]]
            diagonalB = [gameBoard[0][2],gameBoard[1][1],gameBoard[2][0]]
            displayBoard(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter)
            value.delete(0,5)
            message2.set(warning7)
             
        else:
            message2.set(warning5)
 
def displayBoard(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter):
    #strRowA = str(rowA[0]) + ' ' +  str(rowA[1]) + ' ' + str(rowA[2])
    '''
    dispRowA.set(rowA)
    dispRowB.set(rowB)
    dispRowC.set(rowC)
    winningLine = StringVar()
    '''
    dispA10.set(rowA[0])
    dispA11.set(rowA[1])
    dispA12.set(rowA[2])
    dispB20.set(rowB[0])
    dispB21.set(rowB[1])
    dispB22.set(rowB[2])
    dispC30.set(rowC[0])
    dispC31.set(rowC[1])
    dispC32.set(rowC[2])
 
    findWinner(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter)
 
def findWinner(rowA,rowB,rowC,columnA,columnB,columnC,diagonalA,diagonalB,letter):
 
    print('in findwinner', rowA)
    won = all(x == letter for x in rowA)
    print(won)
    if won == True:
        winningLine.set(rowA)
        showWinner(winningLine, letter)
        #winningLine.set(RowA)
        #message2.set(winner)
    if won != True:
        won = all(x == letter for x in rowB)
        if won is True:                    
            winningLine.set(RowB)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in rowC)
        if won is True:
            winningLine.set(RowC)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnA)
        if won is True:
            winningLine.set(ColumnA)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnB)
        if won is True:
            winningLine.set(ColumnB)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in columnC)
        if won is True:
            winningLine.set(ColumnC)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in diagonalA)
        if won is True:
            winningLine.set(DiagonalA)
            message2.set(winner)
    if won != True:
        won = all(x == letter for x in diagonalB)
        if won is True:
            winningLine.set(DiagonalB)
            message2.set(winner)
 
def showWinner(winningLine, letter):
        message2.set(winnerRA)
                 
root = Tk()
root.title("Tic-Tac-Toe")
root.bind("<Return>", makeList)
 
mainFrame = ttk.Frame(root, padding="3 3 12 12")
mainFrame.grid()
 
#correctEntries = ['1 1 X','1 2 X','1 3 X','2 1 X','2 2 X','2 3 X','3 1 X','3 2 X','3 3 X','1 1 O','1 2 O','1 3 O',
#                '2 1 O','2 2 O','2 3 O','3 1 O','3 2 O','3 3 O'] 
 
gameBoard = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
valueEntry = StringVar()
dispRowA = StringVar()
dispRowB = StringVar()
dispRowC = StringVar()
message1 = StringVar()
 
message2 = StringVar()
 
letter = StringVar()
Letter = StringVar()
winner = StringVar()
winningLine = StringVar()
dispA10 = StringVar()
dispA11 = StringVar()
dispA12 = StringVar()
dispB20 = StringVar()
dispB21 = StringVar()
dispB22 = StringVar()
dispC30 = StringVar()
dispC31 = StringVar()
dispC32 = StringVar()
 
winnerRA = StringVar()
 
directions = ('Please enter a 1,2 or 3 for the row, a space, a 1,2 or 3 for the column, a space, and an X or O for the marker.')
warning1 = ('You entered too many characters.  Example: 1 1 X')
warning2 = ('You did not enter enough characters.  Example: 2 3 O')
warning3 = ('Please enter only a 1,2 or 3 for your row choice.')
warning4 = ('Please enter only a 1,2, or 3 for your column choice.')
warning5 = ('The space you entered is already taken, please choose a different space.')
warning6 = ('Please enter either an X or O for your marker.')
warning7 = (' ')
 
winnerRA = ('X player, you are the winner.  You won with RowA.  Hit reset to play again.')
 
RowA = 'Row A'
RowB = 'Row B'
RowC = 'Row C'
ColumnA = 'Column A'
ColumnB = 'Column B'
ColumnC = 'Column C'
DiagonalA = 'Diagonal A'
DiagonalB = 'Diagonal B'
#winner = (Letter,'player, you are the winner.  You won with ',winningLine,'.  Hit reset to play again.')
 
message1.set(directions)
     
directionsLabel = ttk.Label(mainFrame, textvariable = message1)
directionsLabel.grid(column = 2, columnspan = 5, row = 1)
 
messageLabel = ttk.Label(mainFrame, textvariable = message2)
messageLabel.grid(column = 2, columnspan = 5, row = 2)
 
 
value = ttk.Entry(mainFrame, width=7, textvariable=valueEntry)
value.focus_set()
value.grid(column = 2, columnspan = 5, row = 3)
 
enterButton = ttk.Button(mainFrame, text="Enter", command = makeList)
enterButton.grid(column = 2, columnspan = 5, row = 4)
resetButton = ttk.Button(mainFrame,text="Reset",command = reset)
resetButton.grid(column = 2, columnspan = 5, row = 5)
 
gameFrame = ttk.Frame(mainFrame)
gameFrame.grid(column = 2, columnspan = 5, row = 6)
gameFrame10 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame10.grid(column = 0, row = 1 )
gameFrame11 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame11.grid(column = 1, row = 1)
gameFrame12 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame12.grid(column = 2, row = 1)
gameFrame20 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame20.grid(column = 0, row = 2 )
gameFrame21 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame21.grid(column = 1, row = 2)
gameFrame22 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame22.grid(column = 2, row = 2)
gameFrame30 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame30.grid(column = 0, row = 3 )
gameFrame31 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame31.grid(column = 1, row = 3)
gameFrame32 = ttk.Frame(gameFrame, borderwidth=5, relief="sunken", width=20, height=20)
gameFrame32.grid(column = 2, row = 3)
 
rowAdisp1 = ttk.Label(gameFrame10, textvariable = dispA10, width = 2)
rowAdisp1.grid()
rowAdisp2 = ttk.Label(gameFrame11, textvariable = dispA11, width = 2)
rowAdisp2.grid()
rowAdisp3 = ttk.Label(gameFrame12, textvariable = dispA12, width = 2)
rowAdisp3.grid()
rowBdisp1 = ttk.Label(gameFrame20, textvariable = dispB20, width = 2)
rowBdisp1.grid()
rowBdisp2 = ttk.Label(gameFrame21, textvariable = dispB21, width = 2)
rowBdisp2.grid()
rowBdisp3 = ttk.Label(gameFrame22, textvariable = dispB22, width = 2)
rowBdisp3.grid()
rowCdisp1 = ttk.Label(gameFrame30, textvariable = dispC30, width = 2)
rowCdisp1.grid()
rowCdisp2 = ttk.Label(gameFrame31, textvariable = dispC31, width = 2)
rowCdisp2.grid()
rowCdisp3 = ttk.Label(gameFrame32, textvariable = dispC32, width = 2)
rowCdisp3.grid()


root.mainloop ()
Reply
#3
Take a peek at how the code below tests for a winner. There are only 8 ways to win the game and these are all encoded as tuples containing the winning board positions. For example, (0, 1, 2) is the top row. If all three positions have the same marker we have a winner.

I used 0..8 instead of rows and columns to represent spots on the board because it makes the code easier. The real game may be 2D, but it is much easier to write the code using flat lists. I just arrange the buttons in a grid pattern.
"""tkinter tic-tac-toe game"""

import sys
import tkinter as tk

class TicTacToe:
    """Play tic-tac-toe.  Players take turn clicking on empty buttons
    to place their marker.  The first player to get three markers in
    a row, up/down, sideways or diagonally, wins
    """
    # All possible winning conbinations
    wins = ((0, 1, 2), (3, 4, 5), (6, 7, 8),
            (0, 3, 6), (1, 4, 7), (2, 5, 8),
            (0, 4, 8), (6, 4, 2))
    markers = ('X', 'O')       # Player markers
    colors = ('red', 'blue')   # Player colors

    def __init__(self, root):
        # Gameboard
        font = ('Comic Sans MS', 64, 'bold')
        self.buttons = []
        for i in range(9):
            button = tk.Button(root, text=' ', font=font, width=3)
            button.configure(command=lambda index=i: self.place_marker(index))
            button.grid(row=i//3, column=i%3, padx=10, pady=10)
            self.buttons.append(button)

        self.message = tk.Label(root, text=' ', width=30)
        self.message.grid(row=4, column=0, columnspan=3)

        # Start first game
        self.new_game = False
        self.player = 0
        self.reset()

    def reset(self):
        '''Reset board to empty'''
        for button in self.buttons:
            button['text'] = ' '
        self.new_game = False
        self.board = [2]*9  # 2 means empty slot
        self.message['text'] = f"{self.markers[self.player]}'s turn"
 
    def place_marker(self, index):
        """Put player marker in slot if open.  Check for win or tie"""
        if self.new_game:
            self.reset()
        elif self.board[index] != 2:
            self.message['text'] = 'That space is already taken'
        else:
            self.board[index] = self.player
            button = self.buttons[index]
            button['fg'] = self.colors[self.player]
            button['text'] = self.markers[self.player]
            self.new_game = self.game_over()
            self.player = (self.player + 1) % 2
            if not self.new_game:
                self.message['text'] = f"{self.markers[self.player]}'s turn"

    def game_over(self):
        '''Check for winner or tie'''
        # Check all winning combinations
        for win in self.wins:
            if all(self.player == self.board[slot] for slot in win):
                for slot in win:
                    button = self.buttons[slot]
                    button['fg'] = 'green'
                self.message['text'] = f'{self.markers[self.player]} wins!'
                return True

        # Check for a tie
        if not 2 in self.board:
            for button in self.buttons:
                button['fg'] = 'black'
            self.message['text'] = 'Game ends in a tie'
            return True

        return False

ROOT = tk.Tk()
ROOT.title('Tic Tac Toe')
TicTacToe(ROOT)
ROOT.mainloop()
This is the code that check for a winner:
for win in self.wins:
    if all(self.player == self.board[slot] for slot in win):
self.wins is the list of all possible winning combinations. The for loop iterates through all the winning combinations until a winner is found or the list is exhausted.

The all() is like magic to me. Something I first saw mentioned on this forum. It tests if self.player == self.board[slot] for all slots in win. In the example I gave earlier where (0, 1, 2) is the top row, player 0 would be the winner if self.board[0] == 0 and self.board[1] == 0 and self.board[2] == 0. Magic, right?

When you see yourself writing code like this:
    dispA10.set(rowA[0])
    dispA11.set(rowA[1])
    dispA12.set(rowA[2])
    dispB20.set(rowB[0])
    dispB21.set(rowB[1])
    dispB22.set(rowB[2])
    dispC30.set(rowC[0])
    dispC31.set(rowC[1])
    dispC32.set(rowC[2])
Step back and think to yourself "Can I do this with lists and a loop?"
for display, marker in zip(displays, board):
    display.set(marker)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code not working Luzaich 2 2,813 Sep-03-2018, 04:37 PM
Last Post: Gribouillis
  [Tkinter] my simple window code is not working antonmichel 8 13,063 Jan-29-2018, 06:24 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020