Search code examples
pythontkintertic-tac-toe

Python Tkinter Tic Tac Toe With lambda


I have to make a Tic Tac Toe Game using the code below. Only problem is that my class has not been taught lambda at all and no one knows what to do. My understanding of it is as a very simple function however I don't understand why we shouldn't just use regular functions and create more buttons.

from tkinter import *
import tkinter.font as font

root = Tk()
root.geometry("500x500")

myFont = font.Font(family = "Courier", size = 80)

board = [[Button(root, text = "-", font = myFont, command = (lambda x = x, y = y: update(x,y))) for y in range(3)] for x in range(3)]

for x in range(3):
    for y in range(3):
        board[x][y].grid(row=x,column=y)

def update(x,y):
    print(str(x) + str(y))

root.mainloop()

Solution

  • The only purpose of a lambda is brevity. This code:

    board = [[Button(root, text = "-", font = myFont, command = (lambda x=x, y=y: update(x,y))) for y in range(3)] for x in range(3)]
    

    is the same as this code:

    board = []
    for x in range(3):
        row = []
        for y in range(3):
            def fn(x=x, y=y):
                update(x, y)
            row.append(Button(root, text = "-", font = myFont, command = fn)
        board.append(row)
    

    Obviously the first form is briefer -- the lambda is useful because it allows you to define a function as part of a single expression, rather than having to write out a def block. fn in the second form is exactly equivalent to lambda x=x, y=y: update(x, y) in the first form.