gpt4 book ai didi

python - Turtle 在我的代码中没有显示环境变量

转载 作者:行者123 更新时间:2023-12-05 07:11:43 25 4
gpt4 key购买 nike

我刚开始使用 turtle,我在网上找到了 Sierpinski's Carpet 的代码。它应该能够毫无问题地绘制地毯,但我不知道如何添加显示变量。我只是在网上找到这段代码来帮助我。顺便说一句,这不是家庭作业。观看地毯的运行是一个有趣的小项目。这是代码

import turtle,math
def s(n, l):

if n == 0: # stop conditions

# draw filled rectangle

turtle.color('black')
turtle.begin_fill()
for _ in range (4):
turtle.forward(l)
turtle.left(90)
turtle.end_fill()

else: # recursion

# around center point create 8 smalles rectangles.
# create two rectangles on every side
# so you have to repeat it four times

for _ in range(4):
# first rectangle
s(n-1, l/3)
turtle.forward(l/3)

# second rectangle
s(n-1, l/3)
turtle.forward(l/3)

# go to next corner
turtle.forward(l/3)
turtle.left(90)

# update screen
turtle.update()

# --- main ---

# stop updating screen (to make it faster)
turtle.tracer(0)

# start
s(4, 400)

# event loop
turtle.done()

我得到一个非常奇怪的错误

Traceback (most recent call last):
File "main.py", line 40, in <module>
turtle.tracer(0)
File "<string>", line 6, in tracer
File "/usr/local/lib/python3.8/turtle.py", line 3662, in Screen
Turtle._screen = _Screen()
File "/usr/local/lib/python3.8/turtle.py", line 3678, in __init__
_Screen._root = self._root = _Root()
File "/usr/local/lib/python3.8/turtle.py", line 434, in __init__
TK.Tk.__init__(self)
File "/usr/local/lib/python3.8/tkinter/__init__.py", line 2261, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

这不是重复的,因为我问的是如何修复此代码,而不是错误是如何工作的。

最佳答案

问题是您不能导入 turtle 并立即使用像 turtle.forward 这样的命令。相反,最好分配一个等于 turtle.Turtle() 的变量,然后使用该变量来执行命令。像这样:

import turtle
import math
t = turtle.Turtle()
def s(n, l):

if n == 0: # stop conditions

# draw filled rectangle

t.color('black')
t.begin_fill()
for _ in range (4):
t.forward(l)
t.left(90)
t.end_fill()

else: # recursion

# around center point create 8 smalles rectangles.
# create two rectangles on every side
# so you have to repeat it four times

for _ in range(4):
# first rectangle
s(n-1, l/3)
t.forward(l/3)

# second rectangle
s(n-1, l/3)
t.forward(l/3)

# go to next corner
t.forward(l/3)
t.left(90)

# update screen
t.update()

# --- main ---

# stop updating screen (to make it faster)
t.tracer(0)

# start
try:
s(4, 400)
except:
print("This loop has reached it's max callback")
# event loop
t.done()

另外,根据你运行的代码,代码会运行一定的次数。有关更多信息,您可以查看此 question .综上所述,因为你有一个无限循环,你一直在函数中调用函数,所以有一个最大回调,也就是函数中最多可以调用函数的次数。 try 和 except 用于在达到最大回调后简单地打印消息。

关于python - Turtle 在我的代码中没有显示环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60670917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com