[Python] How do I use the text of a tkinter button in a while loop?

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a tic-tac-toe game using tkinter in order to learn the library. I have a 3x3 grid set up and filled with buttons and whenever you click a button it changes it to either x or o depending on the turn variable. In order to make the game stop when either x or o wins i am trying to use a while loop to determine it.

    turn = "X"

    btn = tk.Button(root, text = "", height = 4, width = 10)
    btn.grid(row = 0, column = 0)

    btn2 = tk.Button(root, text = "", height = 4, width = 10)
    btn2.grid(row = 0, column = 1)

    btn3 = tk.Button(root, text = "", height = 4, width = 10)
    btn3.grid(row = 0, column = 2)

    while btn.cget('text') != "X" and btn2.cget('text') != "X" and btn3.cget('text') != "X":
    def on_click():
    global turn
    if turn == "X":
    btn.config(text = "X")
    turn = "O"
    else:
    btn.config(text = "O")
    turn = "X"
    def on_click2():
    global turn
    if turn == "X":
    btn2.config(text = "X")
    turn = "O"
    else:
    btn2.config(text = "O")
    turn = "X"
    def on_click3():
    global turn
    if turn == "X":
    btn3.config(text = "X")
    turn = "O"
    else:
    btn3.config(text = "O")
    turn = "X"


    This is the while loop I tried because I looked it up and some website said that .cget was the proper way, but it didn't end up working. I also didn't include the contents of the while loop as I don't believe they would interrupt it in any way. Additionally, as seen above when initiated my buttons contain no text and are only filled with either X or O when they are clicked. I am using IDLE Shell 3.13.0.

    When I tried to run with this while loop it gave me this error code

    Traceback (most recent call last):
    File "C:\Users\jkoh2169\Python\Tic Tac Toe using tkinter.py", line 36, in <module>
    while btn.cget('text') != "X" and btn2.cget('text') != "X" and btn3.cget('text') != "X":
    File "C:\Program Files\Python313\Lib\tkinter\__init__.py", line 1828, in cget
    return self.tk.call(self._w, 'cget', '-' + key)
    _tkinter.TclError: invalid command name ".!button10"

    Continue reading...

Compartilhe esta Página