有没有办法缩短我的代码,这样我就不必在每次使用 turtle 模块中的函数时都编写 "turtle."?

Is there a way to shorten my code so that I don't have to write "turtle." every time I use functions from the turtle module?

我正在尝试在 python 中使用 turtle 绘制正方形,每次我想命令它做某事时我都必须写 turtle.

import turtle


turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(200)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)



turtle.exitonclick()

我希望在编写代码时不必每次都写 turtle

您可以使用通配符导入:

from turtle import * 

但是最好使用带前缀的导入来保持名称空间的清洁。参见

您可以通过编写

turtle 模块导入所有内容
from turtle import *  # this is a wildcard import

然而,您应该 import turtle as t(或您想要的任何其他内容),如下所示:

import turtle as t  # you can replace t with any valid variable name

因为通配符导入往往会产生函数定义冲突

相反,您可以只从模块中导入您需要的 类(或方法)。 Turtle 是必要的导入:

from turtle import Turtle

现在,我们必须实例化它:

t = Turtle()

现在我们可以使用它了:

t.do_something()  # methods that act on the turtle, like forward and backward

然而,这不会导入 Screen 模块,因此您将无法使用 exitonclick(),除非您也导入 Screen

from turtle import Turtle, Screen
s = Screen()
s.exitonclick()

正如@cdlane 指出的那样,循环实际上可能是减少必须编写的代码量的最佳选择。此代码:

for _ in range(x):
    turtle.forward(100)
    turtle.right(90)

turtle 向前然后向右移动 x 次。

免责声明:此答案适合像我这样的懒人:)

已经有很好的答案告诉您如何解决您的问题,并警告您有关通配符导入。

如果你只是想玩 turtle 模块,你可以让你的生活变得轻松,即不要写 turtle.forward(90) 最好只写 forward(90) 但如果你只是写 f(90)

同样,它会影响代码的可读性,但很常见,值得一试

现在您的代码看起来像

编辑:按照@chepner的建议在一行中修改导入,使其变得超级懒惰

from turtle import forward as f, back as b, right as r, left as l, exitonclick

# to draw one square
f(100)
r(90)
f(100)
r(90)
f(100)
r(90)
f(100)

exitonclick()

您是否知道有多少关于 SO 的评论说 "Don't use wildcard imports" 是为了回应人们所建议的 from turtle import *?我会进一步争辩说,不要做 import turtle as t 因为它向 turtle 公开了 functional 接口。 turtle 模块是面向对象的,您只需要公开该接口即可。如果您厌倦了打这么多字,请了解循环:

from turtle import Screen, Turtle

t = Turtle()

for _ in range(4):
    t.forward(100)
    t.right(90)

for _ in range(4):
    t.backward(100)
    t.left(90)

t.backward(100)

for _ in range(3):
    t.backward(100)
    t.left(90)

s = Screen()

s.exitonclick()

诚然,我真的不介意为 short turtle & tkinter 示例以及 Zelle 图形程序导入通配符。但是 none 那 fd() 废话而不是 forward() 呢!庆祝成为一只乌龟,不要躲在你的 shell!