Python Turtle.Terminator 即使在使用 exitonclick() 之后

标签 python python-3.x function turtle-graphics

我尝试为 turtle 制作函数,使其非常容易绘制形状。代码如下所示:

import turtle as t

def square():
     tw = t.Screen()
     for i in range(4):
          t.forward(100)
          t.right(90)
     tw.exitonclick()
def triangle():
     tw = t.Screen()
     for i in range(3):
          t.forward(100)
          t.right(120)
     tw.exitonclick()
def star():
     tw = t.Screen()
     for i in range(5):
          t.forward(150)
          t.right(144)
     tw.exitonclick()

当我在 shell 中运行此代码时,会发生终结者错误:

>>> square()
>>> triangle()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    triangle()
  File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 11, in triangle
    t.forward(100)
  File "<string>", line 5, in forward
turtle.Terminator
>>> star()
>>> square()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    square()
  File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 5, in square
    t.forward(100)
  File "<string>", line 5, in forward
turtle.Terminator
>>> 

我不明白问题是什么,因为我什至使用了 exitonclick()

最佳答案

您的 turtle 程序结构不正确。你不需要这样做:

tw = t.Screen()
...
tw.exitonclick()

在每个函数中。 Screen() 只需需要调用一次; exitonclick() 应该只被调用一次。尝试这种重组:

import turtle as t

def square():
    for i in range(4):
        t.forward(100)
        t.right(90)

def triangle():
    for i in range(3):
        t.forward(100)
        t.right(120)

def star():
    for i in range(5):
        t.forward(150)
        t.right(144)

t.penup()
t.goto(150, 150)
t.pendown()
square()

t.penup()
t.goto(-150, 150)
t.pendown()
triangle()

t.penup()
t.goto(150, -150)
t.pendown()
star()

screen = t.Screen()
screen.exitonclick()

如果您想以交互方式执行代码,那也可以。只需删除函数定义后的所有内容,以交互方式将其加载到 Python 中并执行以下操作:

>>> star()

或者任何你想运行的东西。您不需要调用 Screen() 并且 exitonclick() 在交互工作时没有意义。

关于Python Turtle.Terminator 即使在使用 exitonclick() 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534458/

相关文章:

python - 使用 Gevents 异步生成函数

python - 如何使输入行低于打印行?

python - 使用点符号导入自定义包的子模块?

python - 猜猜Python中的数字。关闭游戏的选项

c++ - (c++) 将随机值从 main 保存到函数数组

python - 在 Python 中实现函数的前向声明

python - 移动图形时 matplotlib trisurf 缓慢

python - 对于给定的长度,输入的组合或排列

python - 组合字符串列表,提高性能

sql - 在 T-SQL 中创建快捷函数