You need to enable JavaScript to run this app. Python3.9运行Tkinter简化版Pong游戏报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9运行Tkinter简化版Pong游戏报错如何解决

Pong游戏代码报错排查结果

错误原因

  • 核心错误:Paddle类初始化方法中的键盘事件绑定拼写错误,Tkinter规定的键盘按下事件标识为KeyPress(首字母K和P都大写),你的代码中写成了小写p的Keypress,不符合事件格式要求,触发绑定失败报错。
  • 附加问题:窗口标题设置语法错误,tk.title=('Game')是错误的属性赋值写法,title是Tk对象的调用方法,正确写法为tk.title('Game'),否则无法正常设置窗口标题。

修复后的完整代码

from tkinter import*
import random
import time

class Ball:
    def __init__(self, canvas, paddle, color):
        self.canvas = canvas
        self.paddle = paddle
        self.id=canvas.create_oval(10,10,25,25,fill=color)
        self.canvas.move(self.id, 245, 100)
        starts = [-3,-2,-1, 1,2,3]
        random.shuffle(starts)
        self.x=starts[0]
        self.y=-3
        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()
        self.hit_bottom = False
    
    def hit_paddle(self,pos):
        paddle_pos = self.canvas.coords(self.paddle.id)
        if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
            if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
                return True
        return False
    

    def draw(self):
        self.canvas.move(self.id, self.x, self.y)
        pos = self.canvas.coords(self.id)
        if pos[1] <= 0:
            self.y = 3
        if pos[3] >= self.canvas_height:
            self.hit_bottom = True
        if self.hit_paddle(pos) == True:
            self.y = -3
        if pos[0] <= 0:
            self.x = 3
        if pos[2] >= self.canvas_width:
            self.x = -3

class Paddle:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
        self.canvas.move(self.id,200,300)
        self.x = 0
        self.canvas_width = self.canvas.winfo_width()
        # 修复事件拼写错误
        self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
        self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
    
    def draw(self):
        self.canvas.move(self.id, self.x, 0)
        pos = self.canvas.coords(self.id)
        if pos[0] <= 0:
            self.x = 0
        elif pos[2] >= self.canvas_width:
            self.x = 0
       
    def turn_left(self,evt):
        self.x = -2

    def turn_right(self,evt):
        self.x = 2

tk=Tk()
# 修复标题设置语法错误
tk.title('Game')
tk.resizable(0,0)
tk.wm_attributes('-topmost', 1)
canvas = Canvas(tk, width=500, height=500, bd=0, highlightthickness=0)
canvas.pack()
tk.update()

paddle = Paddle(canvas, 'blue')
ball = Ball(canvas, paddle, 'red')

while 1:
    if ball.hit_bottom == False:
        ball.draw()
        paddle.draw()
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)

修复后运行代码即可正常启动,通过左右方向键控制蓝色挡板接住红色小球,小球掉落到屏幕底部游戏结束。

内容的提问来源于stack exchange,提问作者Python coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 09:06:07