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

turtle对象不可调用错误求助:报错行与代码行数不符

问题排查:turtle object not callable错误

问题描述

运行Python代码时触发TypeError: 'Turtle' object is not callable错误,报错堆栈指向turtle库内部第1921行,但自身代码仅43行,无法定位问题。

错误提示内容:

TypeError: 'Turtle' object is not callable

用户原代码:

import turtle
import tkinter as tk
def importantmoving():
    win = turtle.Screen()
    win.title("moving")
    win.bgcolor("black")
    win.setup(width=800, height=800)
    win.tracer(0)
    #moving
    a = turtle.Turtle()
    a.speed(0)
    a.shape("square")
    a.color("white")
    a.shapesize(stretch_wid=5,stretch_len=5)
    a.penup()
    a.goto(0,0)
    #functions
    def a_up():
        y = a.ycor()
        y += 20
        a.sety(y)
    def a_down():
        y = a.ycor()
        y -= 20
        a.sety(y)
    def a_right():
        x = a.xcor()
        x += 20
        a.setx(x)
    def a_left():
        x = a.xcor()
        x -= 20
        a.setx(x)
    #keyboard binding
    win.listen()
    win.onkeypress(a,"Up")
    win.onkeypress(a,"Right")
    win.onkeypress(a,"Down")
    win.onkeypress(a,"Left")
    while True:
        win.update()

importantmoving()

错误原因

  • 核心问题在键盘绑定逻辑:win.onkeypress(a, "Up")这类语句中,你将turtle实例对象a传给了onkeypress的第一个参数,但该参数要求传入可调用的函数(即你定义的a_up、a_right等移动函数)。当turtle库尝试调用传入的对象时,发现它不是函数类型,因此触发类型错误。
  • 报错指向库内部行号是因为错误发生在库的执行流程中,堆栈信息显示的是库代码的位置,而非你的代码行。

修正后的代码

import turtle
import tkinter as tk
def importantmoving():
    win = turtle.Screen()
    win.title("moving")
    win.bgcolor("black")
    win.setup(width=800, height=800)
    win.tracer(0)
    #moving
    a = turtle.Turtle()
    a.speed(0)
    a.shape("square")
    a.color("white")
    a.shapesize(stretch_wid=5,stretch_len=5)
    a.penup()
    a.goto(0,0)
    #functions
    def a_up():
        y = a.ycor()
        y += 20
        a.sety(y)
    def a_down():
        y = a.ycor()
        y -= 20
        a.sety(y)
    def a_right():
        x = a.xcor()
        x += 20
        a.setx(x)
    def a_left():
        x = a.xcor()
        x -= 20
        a.setx(x)
    #keyboard binding
    win.listen()
    win.onkeypress(a_up,"Up")
    win.onkeypress(a_right,"Right")
    win.onkeypress(a_down,"Down")
    win.onkeypress(a_left,"Left")
    while True:
        win.update()

importantmoving()

内容的提问来源于stack exchange,提问作者mr.nokia ringtone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:15:38