gpt4 book ai didi

python - 如何改变 turtle 的大小?

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:42 24 4
gpt4 key购买 nike

每次按键盘上的 x 时,我都会尝试将窗口中 turtle 的大小加倍。我尝试使用 .turtlesize(2,2,2),但这是不对的。每次按下按键时我都需要加倍,因此如果 turtle 大小为 (1,1,1),它将变成 (2,2,2) 然后 (4,4,4) 等等,每次我按 x 时。

这是我到目前为止所拥有的:

import turtle
turtle.setup(500,500)
wn = turtle.Screen()
wn.title("Commands")
wn.bgcolor("black")

tess = turtle.Turtle()
tess.shape("triangle")
tess.color("red")
tess.left(90)

def increaseSize():
size = tess.turtlesize()
increase = tuple([2 * num for num in size])
tess.turtlesize(increase) #this is where the error occurs

wn.onkey(increaseSize, "x")
wn.listen()

最佳答案

Turtle 对象的默认大小为 20 像素,相当于调整 Turtle 大小时的比例 1 .

例如:

import turtle

tess = turtle.Turtle()
print(tess.shapesize())

输出:

(1.0, 1.0, 1)

元组中的前两个1.0表示Turtle的宽度和高度有多少个20像素单位,最后一个1 代表 Turtle 轮廓的宽度。如果仅将一个参数传递到 tess.color() 括号中,您将无法看到轮廓,因为默认情况下没有轮廓。

要增加 Turtle 的大小,只需将您希望 Turtle 的每个尺寸包含的 20 像素数量传递到 tess.shapesize() 中即可。或tess.turtesize() :

import turtle

tess = turtle.Turtle()
tess.shapesize(2, 3, 1) # Sets the turtle's width to 60px and height to 90px
<小时/>

另一个答案指出 turtlesize 函数不接受大批;它接受 intfloat ,因此您需要 unpack the tuple with a *当您将元组传递给函数时。

在您的 increaseSize 函数中,tuple[] 包装器不是必需的,只会浪费效率。只需使用 ():

def increaseSize():
size = tess.turtlesize()
increase = (2 * num for num in size)
tess.turtlesize(*increase)

在你的代码之上有

turtle.setup(500,500)
wn = turtle.Screen()

由于您定义了 Screen 对象 wn,因此使用 wn.setup() 而不是 turtle.setup 更简洁():

wn = turtle.Screen()
wn.setup(500,500)

一起:

import turtle

wn = turtle.Screen()
wn.setup(500,500)

tess = turtle.Turtle("triangle")
tess.color("red")
tess.left(90)

def increaseSize():
size = tess.turtlesize()
increase = (2 * num for num in size)
tess.turtlesize(*increase)

wn.onkey(increaseSize, "x")
wn.listen()

输出:

enter image description here

关于python - 如何改变 turtle 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38103158/

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