gpt4 book ai didi

python - turtle.setworldcoordinates 函数有什么作用?

转载 作者:行者123 更新时间:2023-12-01 03:57:40 24 4
gpt4 key购买 nike

初学者的 Python 书籍往往会变得更加陡峭,几乎没有解释任何内容。因此,在对我无法通过阅读文档来做到这一点感到失望之后,我很难弄清楚turtle.setworldcoordinates函数的作用,这是非常没有帮助的,并且无法根据文档的一些想法凭经验推断出任何内容。谁能指出这个函数在 turtle 图形中的作用吗?

最佳答案

由于turtle.py 随Python 一起提供,并且是用Python 编写的,因此您可以查看源代码以了解该函数的功能(我发现我经常使用turtle.py 执行此操作),请参见下文。

我相信 setworldcooperatives() 允许您选择更适合您的问题的坐标系。例如,假设您不希望 (0,0) 位于屏幕中央。您可以使用 setworldcoordinates() 将其移动到角落(如果这样更适合您),而不是合并偏移量。您还可以设置在水平与垂直方向上具有不同缩放因子的坐标系。

例如参见 my answer to this question我在其中定义了一个例程,它使用 setworldcoordinates() 来缩放您绘制的任何内容,而无需将任何缩放因子合并到您自己的绘图代码中。

或者您可以设置一个角点为 (0,0)、(1,0)、(0,1) 和 (1,1) 的坐标系,以完全在单位正方形内工作。

棘手的一点是它将您的坐标系映射到现有的窗口形状上 - 因此您要么必须调整窗口的坐标,要么重新调整窗口的形状以匹配您的坐标系。否则,您可能会发现自己的纵横比不理想。

def setworldcoordinates(self, llx, lly, urx, ury):
"""Set up a user defined coordinate-system.

Arguments:
llx -- a number, x-coordinate of lower left corner of canvas
lly -- a number, y-coordinate of lower left corner of canvas
urx -- a number, x-coordinate of upper right corner of canvas
ury -- a number, y-coordinate of upper right corner of canvas

Set up user coodinat-system and switch to mode 'world' if necessary.
This performs a screen.reset. If mode 'world' is already active,
all drawings are redrawn according to the new coordinates.

But ATTENTION: in user-defined coordinatesystems angles may appear
distorted. (see Screen.mode())

Example (for a TurtleScreen instance named screen):
>>> screen.setworldcoordinates(-10,-0.5,50,1.5)
>>> for _ in range(36):
... left(10)
... forward(0.5)
"""
if self.mode() != "world":
self.mode("world")
xspan = float(urx - llx)
yspan = float(ury - lly)
wx, wy = self._window_size()
self.screensize(wx-20, wy-20)
oldxscale, oldyscale = self.xscale, self.yscale
self.xscale = self.canvwidth / xspan
self.yscale = self.canvheight / yspan
srx1 = llx * self.xscale
sry1 = -ury * self.yscale
srx2 = self.canvwidth + srx1
sry2 = self.canvheight + sry1
self._setscrollregion(srx1, sry1, srx2, sry2)
self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
self.update()

my book gives a weird example like this: setworldcoordinates(-10, 0.5, 1, 2), could you tell me what this operation exactly does?

这些奇怪的 setworldcoordinates() 示例比比皆是,但解释甚少,例如,请参阅 @TessellatedHeckler 的幻灯片。它们只是表明你可以用坐标做极端的事情。但为了回答您的后续问题,如果我们有一个 100 x 100 的窗口,则该特定调用将对我们的坐标系执行以下操作:

enter image description here

关于python - turtle.setworldcoordinates 函数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37154189/

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