如何在按钮列表中获取特定按钮的文本?我正在使用Tkinter

时间:2017-09-20 14:53:39

标签: python tkinter

我目前正在制作一个Tic-Tac-Toe游戏,我正在努力检查是否有人连续获得了3件,所以我可以告诉他们他们已经赢了。我试图通过检查按钮的文本来做到这一点,看看我是否连续3次。但是,我不知道如何检查列表中特定按钮的文本。有没有人有任何想法,或者如果有更好的方法,你能让我知道吗?

完整代码

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()

第一部分我正在努力与

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")

我意识到在这一部分我找不到文字,但我真的不知道如何调用特定的列表项和文本。

1 个答案:

答案 0 :(得分:1)

调用包含tkinter list小部件的Button中的元素将返回小部件本身,就好像您正在调用存储在list元素中的任何其他值一样。这意味着如果您想要元素值的text属性,可以使用["text"].cget("text")

见下文:

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"])