现在代码执行会在computer_move函数*下执行以下“if语句”。我希望它等待玩家点击另一个按钮。现在,代码在玩家点击按钮放置“o”之前放置x。
import tkinter as tk
board = tk.Tk()
def player_move(widget):
if widget["o"] not in ("o", "x"):
widget["text"] = "o"
widget["state"] = "disabled"
computer_move()
def computer_move():
if i["text"] == "Open Space":
i["text"] = "x"
i["state"] = "disabled"
else:
c["text"] = "x"
c["state"] = "disabled"
if a["text"] and c["text"] == "x" or "o": # *
b["text"] = "x"
b["state"] = "disabled"
board.geometry("400x500")
board.title("Board")
buttons = []
a = tk.Button(board, text="x", state = "disabled")
a["command"] = lambda x=a:player_move(x)
a.grid(row=0, column = 0)
buttons.append(a)
board.mainloop()
答案 0 :(得分:1)
代码没有设置x
,但您可以在线
a = tk.Button(board, text="x", state= "disabled")
删除text="x", state="disabled"
顺便说一句:
widget["o"]
不正确 - 按钮没有名称为"o"
的媒体资源。
它有属性"text"
- widget["text"]
- 可能有值"o"
或"x"
if a["text"] and c["text"] == "x" or "o":
相当不正确。特别是
c["text"] == "x" or "o"
必须是
c["text"] == "x" or c["text"] == "o"
或
c["text"] in ("x", "o")
我想你试着做
if a["text"] in ("x", "o") and c["text"] in ("x", "o"):
最好将按钮保留在列表中 - 您可以使用for
循环检查computer_move
import tkinter as tk
# --- functions ---
def player_move(btn):
# if button is empty
if btn["text"] not in ("o", "x"):
# then set `o` and disable button
btn["text"] = "o"
btn["state"] = "disabled"
# and make comuter move
computer_move()
def computer_move():
# check all buttons
for btn in buttons:
# if button is empty
if btn["text"] not in ("o", "x"):
# then set `x` and disable button
btn["text"] = "x"
btn["state"] = "disabled"
# and skip checking other buttons
break
# --- main ---
board = tk.Tk()
board.geometry("400x500")
board.title("Board")
buttons = []
for row in range(3):
for col in range(3):
btn = tk.Button(board, width=1)
btn["command"] = lambda x=btn:player_move(x)
btn.grid(row=row, column=col)
buttons.append(btn)
board.mainloop()