You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手开发Bounce游戏时关闭窗口触发tkinter.TclError错误求助

解决Tkinter游戏关闭窗口时的_tkinter.TclError问题

我明白你遇到的问题了——这是因为你用的while True循环和Tkinter的事件循环冲突导致的。当你关闭窗口时,Tkinter已经销毁了画布(.!canvas)等组件,但你的while循环还在继续执行,试图调用已经不存在的画布的move方法,所以触发了这个错误。而且你之前尝试加.mainloop()没生效,是因为你的while循环会一直阻塞代码执行,根本轮不到.mainloop()运行。

下面是具体的解决方案,核心是用Tkinter原生的after()方法替代while循环,这是Tkinter中实现动画的正确方式:

步骤说明

  • 移除阻塞式的while循环和time.sleep:这两个会打断Tkinter的事件循环,导致窗口无法正常处理关闭等事件。
  • 创建游戏循环函数:用after()方法定时调用这个函数,实现动画更新,同时不阻塞事件循环。
  • 启动Tkinter的事件循环:最后调用window.mainloop()让窗口正常响应所有事件。

修改后的完整代码

from tkinter import *
import random
import time

# Creating the window:
window = Tk()
window.title("Bounce")
window.geometry('600x600')
window.resizable(False, False)

# Creating the canvas containing the game:
canvas = Canvas(window, width = 450, height = 450, bg = "black")
canvas.pack(padx = 50, pady= 50)
score = canvas.create_text(10, 20, fill = "white")
window.update()

# Creating the ball:
class Ball:
    def __init__(self, canvas1, paddle1, color):
        self.canvas = canvas1
        self.paddle = paddle1
        self.id = canvas1.create_oval(10, 10, 25, 25, fill = color)
        # The starting point of the ball
        self.canvas.move(self.id, 190, 160)
        starting_direction = [-3, -2, -1, 0, 1, 2, 3]
        random.shuffle(starting_direction)
        self.x = starting_direction[0]
        self.y = -3
        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()

    # Detecting the collision between the ball and the paddle:
    def hit_paddle(self, ballcoords):
        paddle_pos = self.canvas.coords(self.paddle.id)
        if ballcoords[0] <= paddle_pos[2] and ballcoords[2] >= paddle_pos[0]:
            if paddle_pos[3] >= ballcoords[3] >= paddle_pos[1]:
                return True
        return False

    # Detecting the collision between the the ball and the canvas sides:
    def draw(self):
        self.canvas.move(self.id, self.x, self.y)
        ballcoords = self.canvas.coords(self.id)
        if ballcoords[1] <= 0:
            self.y = 3
        if ballcoords[3] >= self.canvas_height:
            self.y = 0
            self.x = 0
            self.canvas.create_text(225, 150, text = "Game Over!", font = ("Arial", 16), fill = "white")
        if ballcoords[0] <= 0:
            self.x = 3
        if ballcoords[2] >= self.canvas_width:
            self.x = -3
        if self.hit_paddle(ballcoords):
            self.y = -3

class Paddle:
    def __init__(self, canvas1, color):
        self.canvas1 = canvas
        self.id = canvas.create_rectangle(0, 0, 100, 10, fill = color)
        self.canvas1.move(self.id, 180, 350)
        self.x = 0
        self.y = 0
        self.canvas1_width = canvas1.winfo_width()
        self.canvas1.bind_all("<Left>", self.left)
        self.canvas1.bind_all("<Right>", self.right)

    def draw(self):
        self.canvas1.move(self.id, self.x, 0)
        paddlecoords = self.canvas1.coords(self.id)
        if paddlecoords[0] <= 0:
            self.x = 0
        if paddlecoords[2] >= self.canvas1_width:
            self.x = 0

    def right(self, event):
        self.x = 3

    def left(self, event):
        self.x = -3

paddle = Paddle(canvas, color = "white")
ball = Ball(canvas, paddle, color = "red")

# 定义游戏循环函数
def game_loop():
    ball.draw()
    paddle.draw()
    window.update_idletasks()
    window.update()
    # 每隔1毫秒调用一次game_loop,相当于原来的time.sleep(0.001)
    window.after(1, game_loop)

# 启动游戏循环并运行Tkinter事件循环
game_loop()
window.mainloop()

为什么这样能解决问题?

  • after()方法会告诉Tkinter在指定时间后调用目标函数,同时不会阻塞事件循环,窗口可以正常处理关闭、键盘输入等事件。
  • 当你关闭窗口时,Tkinter会正常销毁所有组件,并且停止after()的递归调用,不会出现试图操作已销毁组件的情况。

内容的提问来源于stack exchange,提问作者Mahmoud Youssry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:42:38