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

Python Turtle代码无法运行,提示未定义语法错误求助

Python Turtle代码语法错误修复方案

你的代码出现“未定义”错误的核心原因是:函数内直接调用了penup()、setposition()等方法,但这些方法属于turtle模块,必须通过模块前缀或者画笔对象来调用,解释器才能找到它们。

修复方案1:使用模块前缀调用方法

直接在每个方法前加上turtle.前缀,同时添加turtle.done()保持窗口不自动关闭:

import turtle

turtle.speed(10)

def blue_circle():
    turtle.penup()
    turtle.setposition(100,50)
    turtle.color("blue")
    turtle.begin_fill()
    turtle.circle(60)
    turtle.end_fill()

def red_circle():
    turtle.penup()
    turtle.setposition(-100,50)
    turtle.color("red")
    turtle.begin_fill()
    turtle.circle(60,360,4)
    turtle.end_fill()

def yellow_half_circle():
    turtle.penup()
    turtle.setposition(-115,-150)
    turtle.color("yellow")
    turtle.begin_fill()
    turtle.circle(60,180)
    turtle.end_fill()

def green_pentagon():
    turtle.penup()
    turtle.setposition(100,-150)
    turtle.left(180)
    turtle.color("green")
    turtle.begin_fill()
    turtle.circle(60,360,5)
    turtle.end_fill()

blue_circle()
red_circle()
yellow_half_circle()
green_pentagon()

turtle.done()  # 防止窗口自动关闭

修复方案2:创建画笔对象(推荐)

更符合面向对象编程的写法,创建独立的画笔对象来调用方法,避免全局模块调用的潜在问题:

import turtle

# 初始化画笔对象
pen = turtle.Turtle()
pen.speed(10)

def blue_circle():
    pen.penup()
    pen.setposition(100,50)
    pen.color("blue")
    pen.begin_fill()
    pen.circle(60)
    pen.end_fill()

def red_circle():
    pen.penup()
    pen.setposition(-100,50)
    pen.color("red")
    pen.begin_fill()
    pen.circle(60,360,4)
    pen.end_fill()

def yellow_half_circle():
    pen.penup()
    pen.setposition(-115,-150)
    pen.color("yellow")
    pen.begin_fill()
    pen.circle(60,180)
    pen.end_fill()

def green_pentagon():
    pen.penup()
    pen.setposition(100,-150)
    pen.left(180)
    pen.color("green")
    pen.begin_fill()
    pen.circle(60,360,5)
    pen.end_fill()

blue_circle()
red_circle()
yellow_half_circle()
green_pentagon()

turtle.done()  # 保持绘图窗口显示

内容的提问来源于stack exchange,提问作者Andrew Morris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:45:32