使用 lambda 在 Python Tkinter Tic Tac Toe 中不可调用列表
List not callable in Python Tkinter Tic Tac Toe using lambda
在我的代码中,我需要使用 Lambda 来创建按钮板,但是我在尝试调用按钮时遇到错误。我已经尝试按照我在另一个论坛中看到的建议将 () 切换为 [],但是我无法使其工作。
from tkinter import *
import tkinter.font as font
root = Tk()
root.geometry("500x500")
myFont = font.Font(family = "Courier", size = 80)
who = True
turn = 0
#changing turns and choosing tiles
def update(x,y):
global who, turn
if board(x,y)["text"] == "-" and who == True:#<-----------Error
board(x,y)["text"] = "X"
who = False
turn += 1
elif board(x,y)["text"] == "-" and who == False:
board(x,y)["text"] = "0"
who = True
turn += 1
else:
print("That Box has already been chosen")
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)]
#^^^^^ The cause of my frustration
for x in range(3):
for y in range(3):
board[x][y].grid(row=x,column=y)
root.mainloop()
应该是
if board[x][y]["text"] == "-"
就像在网格循环中一样。
在我的代码中,我需要使用 Lambda 来创建按钮板,但是我在尝试调用按钮时遇到错误。我已经尝试按照我在另一个论坛中看到的建议将 () 切换为 [],但是我无法使其工作。
from tkinter import *
import tkinter.font as font
root = Tk()
root.geometry("500x500")
myFont = font.Font(family = "Courier", size = 80)
who = True
turn = 0
#changing turns and choosing tiles
def update(x,y):
global who, turn
if board(x,y)["text"] == "-" and who == True:#<-----------Error
board(x,y)["text"] = "X"
who = False
turn += 1
elif board(x,y)["text"] == "-" and who == False:
board(x,y)["text"] = "0"
who = True
turn += 1
else:
print("That Box has already been chosen")
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)]
#^^^^^ The cause of my frustration
for x in range(3):
for y in range(3):
board[x][y].grid(row=x,column=y)
root.mainloop()
应该是
if board[x][y]["text"] == "-"
就像在网格循环中一样。