如何使用Tkinter清除标签?

时间:2017-09-24 02:39:05

标签: python python-3.x tkinter

我使用标签来显示我在Tic Tac Toe游戏中获胜的人。但是,当标签被不同的文本覆盖时,其下的旧文本不会被清除,只会被覆盖。因此,一些旧文本有时会通过。有没有办法清除标签来实现这一点,而不只是制作同一地点的不同标签?如果我尝试在标签上使用.destroy()方法,则会出现错误的窗口路径错误。

这是我的代码:

import tkinter as tk


class TicTacToe(tk.Tk):
    def __init__(self):
        super().__init__()
        # Vars
        self.players = Players()
        self.rounds_played = 0
        self.turn = 0
        self.hz = [0,3,6]
        self.clicked_buttons = []

        # Attributes
        self.resizable(False, False)

        # Start
        self.game_title = tk.Label(text="Stew's Tic Tac Toe")
        self.name_label = tk.Label(text="Make a name\n(Press the \'Enter\' key to submit)")
        self.name_entry = tk.Entry()
        self.symbol_label = tk.Label(text="Pick 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.start_game = tk.Button(text="Start", command=self.start)
        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.players.player))

    def set_player_name(self, num):
        if num == 0:
            self.players.name = [self.name_entry.get().strip(" ")]
            if len(self.players.name[0].strip(" ")) == 0:
                self.players.name = ["Player 1"]
            if self.players.name[0] == "":
                self.players.name = ["Player 1"]
            if self.players.name[0] ==  " ":
                self.players.name = ["Player 1"]
            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.players.name.append(self.name_entry.get().strip(" "))
            if len(self.players.name) >= 3:
                self.players.name[1] = self.players.name[2]
                self.players.name.pop(2)

            if len(self.players.name[0].strip(" ")) == 0:
                self.players.name = ["Player 1"]
            if self.players.name[1] == "":
                self.players.name.pop(1)
                self.players.name.append("Player 2")
            if self.players.name[1] == " ":
                self.players.name.pop(1)
                self.players.name.append("Player 2")
            if self.players.name[1] == self.players.name[0]:
                self.players.name[0] = f"{self.players.name[0]}1"
                self.players.name[1] = f"{self.players.name[1]}2"
            self.start_game.grid(row=4)

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

    def next_button(self):
        self.players.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(self):
        self.game_title.grid_forget()
        self.whos_turn = tk.Label(text=f"{self.players.name[0]}\'s Turn")
        self.whos_turn.grid(row=0, column=1, columnspan=3)
        self.start_game.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 + 1), column=(c%3 + 1))
                num = num + 1
        self.rounds = tk.Label(text=f"Rounds Played: {self.rounds_played}")
        self.stats_title = tk.Label(text="Player\'s Stats")
        self.player_stats = [tk.Label(text=f"{self.players.name[0]}\'s Wins: {self.players.wins[0]}"),
                             tk.Label(text=f"{self.players.name[1]}\'s Wins: {self.players.wins[1]}")]
        self.rounds.grid(row=5, column=1, columnspan=3)
        self.stats_title.grid(row=0, column=0)
        self.player_stats[0].grid(row=1, column=0)
        self.player_stats[1].grid(row=2, column=0)

    def move_update(self, num):
        if num not in self.clicked_buttons:
            self.clicked_buttons.append(num)
            self.players.turn = self.players.turn + 1
            if self.players.turn%2 == 1:
                self.game_buttons[num].config(text=self.players.symbol[0], relief=tk.SUNKEN)
                self.whos_turn.config(text=f"{self.players.name[1]}\'s Turn")
            elif self.players.turn%2 == 0:
                self.game_buttons[num].config(text=self.players.symbol[1], relief=tk.SUNKEN)
                self.whos_turn.config(text=f"{self.players.name[0]}\'s Turn")
        if self.players.turn != 9:
            self.check_for_winner()
        if self.players.turn == 9:
            if self.check_for_winner() != 1:
                self.round_end(0)

    def check_for_winner(self):
        # Check Which Symbol Won
        for n in range(0, 2):
            # Check if Winner (Vertical)
            for x in range(0, 3):
                if self.game_buttons[x]["text"] == self.players.symbol[n] and self.game_buttons[x + 3]["text"] == self.players.symbol[
                    n]:
                    if self.game_buttons[x + 6]["text"] == self.players.symbol[n]:
                        self.round_end(n + 1)
                        return 1
            # Check if Winner (Horizontal)
            for x in range(0, 9):
                if x in self.hz and self.game_buttons[x]["text"] == self.players.symbol[n]:
                    if self.game_buttons[x + 1]["text"] == self.players.symbol[n] and self.game_buttons[x + 2]["text"] == self.players.symbol[n]:
                        self.round_end(n + 1)
                        return 1
            # Check if Winner (Left Diagonal)
            if self.game_buttons[0]["text"] == self.players.symbol[n] and self.game_buttons[4]["text"] == self.players.symbol[n]:
                if self.game_buttons[8]["text"] == self.players.symbol[n]:
                    self.round_end(n + 1)
                    return 1
            # Check if Winner (Right Diagonal)
            if self.game_buttons[2]["text"] == self.players.symbol[n] and self.game_buttons[4]["text"] == self.players.symbol[n]:
                if self.game_buttons[6]["text"] == self.players.symbol[n]:
                    self.round_end(n + 1)
                    return 1

    def round_end(self ,num):
        for x in self.game_buttons:
            x.config(relief=tk.SUNKEN, state=tk.DISABLED)
        self.rounds_played = self.rounds_played + 1
        self.rounds.configure(text=f"Rounds Played: {self.rounds_played}")
        self.round_winner = tk.Label()
        self.play_again = tk.Button(text="Play Again?", command=self.new_game)
        self.play_again.grid(row=6, column=1, columnspan=3)
        if num == 0:
            self.round_winner.grid(row=4, column=1, columnspan=3)
            self.round_winner.destroy()
            self.round_winner.grid(row=4, column=1, columnspan=3)
            self.round_winner.config(text="It was a Tie!")
        elif num == 1:
            self.round_winner.grid(row=4, column=1, columnspan=3)
            self.round_winner.config(text=f"{self.players.name[0]} Wins!")
            self.players.wins = [self.players.wins[0] + 1, self.players.wins[1]]
            self.player_stats[0].config(text=f"{self.players.name[0]}\'s Wins: {self.players.wins[0]}")
        elif num == 2:
            self.round_winner.grid(row=4, column=1, columnspan=3)
            self.round_winner.destroy()
            self.round_winner.grid(row=4, column=1, columnspan=3)
            self.round_winner.config(text=f"{self.players.name[1]} Wins!")
            self.players.wins = [self.players.wins[0], self.players.wins[1] + 1]
            self.player_stats[1].config(text=f"{self.players.name[1]}\'s Wins: {self.players.wins[1]}")

    def new_game(self):
        self.players.turn = 0
        for x in self.game_buttons:
            x.config(state=tk.ACTIVE, text="[ ]", relief=tk.RAISED)
        self.clicked_buttons = []


class Players:
    def __init__(self):
        super().__init__()
        self.name = []
        self.symbol = []
        self.wins = [0, 0]
        self.player = 0
        self.turn = 0



game = TicTacToe()
game.mainloop()

相关部分是这(196的第161-164行)

self.round_winner.grid(row=4, column=1, columnspan=3)
self.round_winner.destroy()
self.round_winner.grid(row=4, column=1, columnspan=3)
self.round_winner.config(text="It was a Tie!")

1 个答案:

答案 0 :(得分:1)

您只需要更新标签中的文字;没有必要为每个游戏重新创建和重新标记标签 分数也需要更新。
login: function () { axios.post( this.BASE_URL + "/api/login", { // you must have this here username: this.username, password: this.password, }).then(function(data){ console.log(data); }); }, 可能有点过分;你可以用self.update()替换它,或者完全删除它。

self.update_idletasks()