使用python tkinter的Tic-tac-toe游戏无法正常运行。
Tic-tac-toe结构是正确的。我只想更改单击事件。
单击任意按钮时仅显示button9输出
每次我单击任何按钮时,都会显示以下输出

from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()发布于 2019-03-04 17:29:27
常见的错注。Button9函数使用赋值给i的最后一个值,所以每个lambda函数都会使用i=。!将lambda函数更改为:
i.config(command=lambda current_button=i: ttt(current_button))这将使lambda在创建lambda时使用i的值。
https://stackoverflow.com/questions/54979853
复制相似问题