将按钮文本更改为X和O时,Tkinter井字游戏“ nonetype”错误

时间:2020-08-11 01:46:45

标签: python tkinter

我试图制作一个tkinter井字游戏GUI,但我一直试图将按钮的名称从空字符串更新为X或O,具体取决于轮到谁。每次我最终收到来自代码'NoneType' object is not subscriptable的{​​{1}}错误消息时,这是我的代码

 button["text"] == ""

import tkinter as tk window = tk.Tk() window.geometry("600x600") window.title("Tic-Tac-Toe") window.resizable(0, 0) btn_click = True def on_button_click(button): global btn_click if btn_click is True and button["text"] == "": btn_click = False button["text"] = "X" elif btn_click is False and button["text"] == "": btn_click = True button["text"] = "O" btn1 = tk.Button(window, text=" ", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn1)).grid(row=1, column=1) btn2 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn2)).grid(row=1, column=2) btn3 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn3)).grid(row=1, column=3) btn4 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn4)).grid(row=2, column=1) btn5 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn5)).grid(row=2, column=2) btn6 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn6)).grid(row=2, column=3) btn7 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn7)).grid(row=3, column=1) btn8 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn8)).grid(row=3, column=2) btn9 = tk.Button(window, text="12", width=10, height=10, borderwidth=4, relief="groove", highlightcolor="red", justify="center", padx=1, pady=1, command=lambda: on_button_click(btn9)).grid(row=3, column=3) window.mainloop() 错误消息对我来说没有意义,因为我知道这只会将按钮文本更改为X或O。

button["text"] == ""似乎是一种替代方法,但是据我了解,这仅适用于标签和文本,不适用于按钮。我什至查看了许多教程和youtube视频,它们通常具有与我在上面的代码中实现的相同的方法,因此我不知道我在这里到底缺少什么。我今天刚开始学习tkinter,所以对我来说可能是一个简单的错误表示歉意。

0 个答案:

没有答案