stew3254
stew3254

Reputation: 35

How can I get the text of a specific button in a list of buttons? I'm using Tkinter

I am currently making a Tic-Tac-Toe game, and I am working on trying to check if someone gets 3 of their pieces in a row, so I can tell them they've won. I'm trying to do that by checking the text of the buttons, to see if I've gotten 3 in a row. However, I don't know how to check the text of a specific button in a list. Does anyone have any ideas, or if there is a better way, can you let me know?

Full Code

import tkinter as tk


class TicTacToe(tk.Tk):
    def __init__(self):
        super().__init__()
        # Vars
        self.rounds_played = 0
        self.wins = 0
        self.losses = 0
        self.player = 0
        self.turn = 0
        self.clicked_buttons = []

        # Attributes
        self.resizable(False, False)
        self.attributes("-toolwindow", True)

        # Start
        self.game_title = tk.Label(text="Stew's Tic Tac Toe")
        self.name_label = tk.Label(text="Choose a name\n(Press the \'Enter\' key to submit)")
        self.name_entry = tk.Entry()
        self.symbol_label = tk.Label(text="Choose your symbol")
        self.symbol_buttons = [tk.Button(text="[X]", command=lambda: self.symbol_select(0)),
                               tk.Button(text="[O]", command=lambda: self.symbol_select(1))]
        self.next = tk.Button(text="Next", command=self.next_button)
        self.ready = tk.Button(text="Start", command=self.start_game_button)
        self.game_title.grid(row=0)
        self.name_label.grid(row=1)
        self.name_entry.grid(row=2)
        self.name_entry.bind("<Return>", lambda x: self.set_player_name(self.player))

    def set_player_name(self, num):
        if num == 0:
            self.names = [self.name_entry.get()]
            if self.names[0] ==  " ":
                self.names = ["Player 1"]
            print(self.names[0])
            self.symbol_label.grid(row=3,)
            self.symbol_buttons[0].grid(row=4, sticky=tk.W, padx=57.5)
            self.symbol_buttons[1].grid(row=4, sticky=tk.E, padx=57.5)
        elif num == 1:
            self.names.append(self.name_entry.get())
            if self.names[1] == "" or " ":
                self.names.append("Player 2")
            self.ready.grid(row=4)

    def symbol_select(self, num):
        if num == 0:
            self.symbol = ["[X]",
                           "[O]"]
        else:
            self.symbol = ["[X]",
                           "[O]"]
        self.next.grid(row=5)

    def next_button(self):
        self.player = 1
        self.next.grid_forget()
        self.name_entry.delete(0, tk.END)
        self.symbol_label.grid_forget()
        for x in self.symbol_buttons:
            x.grid_forget()

    def start_game_button(self):
        self.game_title.grid_configure(row=0, column=1, columnspan=3)
        self.whos_turn = tk.Label(text="{}\'s turn".format(self.names[0]))
        self.whos_turn.grid(row=1, column=1, columnspan=3)
        self.ready.grid_forget()
        self.name_label.grid_forget()
        self.name_entry.grid_forget()
        self.game_buttons = [tk.Button(text="[ ]", command=lambda: self.move_update(0)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(1)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(2)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(3)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(4)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(5)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(6)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(7)),
                             tk.Button(text="[ ]", command=lambda: self.move_update(8))]
        num = 0
        for r in range(0,3):
            for c in range(0,3):
                self.game_buttons[num].grid(row=(r%3 + 2), column=(c%3 + 1))
                num = num + 1
        self.rounds = tk.Label(text="Rounds Played: {}".format(self.rounds_played))
        self.rounds.grid(row=5, column=1, columnspan=3)

    def move_update(self, num):
        if num not in self.clicked_buttons:
            self.clicked_buttons.append(num)
            self.turn = self.turn + 1
            if self.turn%2 == 1:
                self.game_buttons[num].config(text=self.symbol[0])
            elif self.turn%2 == 0:
                self.game_buttons[num].config(text=self.symbol[1])
        # Here is where I am struggling
        for x in range(0,8):
            if self.game_buttons[x] == "[X]" and self.game_buttons[(x+3)%9]:
                if self.game_buttons[(x+6)%9] == "[X]":
                    print("Winner")
        # Here is where it ends
        if self.turn == 9:
            self.rounds_played = self.rounds_played + 1
            self.rounds.configure(text="Rounds Played: {}".format(self.rounds_played))
            self.play_again = tk.Button(text="Play Again?", command=self.new_game)
            self.play_again.grid(row=6, column=1, columnspan=3)

    def new_game(self):
        self.turn = 0



game = TicTacToe()
game.mainloop()

Part I am struggling with

for x in range(0,8):
            if self.game_buttons[x] == "[X]" and self.game_buttons[(x+3)%9]:
                if self.game_buttons[(x+6)%9] == "[X]":
                    print("Winner")

I realize in this part I'm not finding the text, but I really don't know how to call upon both the specific list item and text.

Upvotes: 0

Views: 3125

Answers (1)

Ethan Field
Ethan Field

Reputation: 4730

Calling the element in a list which contains a tkinter Button widget will return the widget itself as if you were calling any other value stored in an element of a list. Meaning that if you wanted the text attribute of the value of the element you could use ["text"] or .cget("text").

See below:

from tkinter import *

root = Tk()

array = [Button(root, text="1"), Button(root, text="2"), Button(root, text="3")]

for i in array:
    print(type(i))
    print(i.cget("text"))
    print(i["text"])

Upvotes: 1

Related Questions