当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python turtle.pos()用法及代码示例


Turtle模块以面向对象和面向过程的方式提供了Turtle图形基元。由于它使用Tkinter作为基础图形,因此需要安装有Tk支持的Python版本。

turtle .pos()

此方法用于查找海龟的当前位置(x,y),作为Vec2D-vector。此方法具有Aliases:pos |位置。

用法: turtle.pos() or  turtle.position()

返回:以(x,y)坐标表示海龟的当前位置

此函数不需要任何参数,并以(x,y)格式返回海龟的当前位置,其中x和y表示2D向量。默认值为(0.0,0.0)。



下面是上述方法的实现和一些示例:

范例1:

Python3

# import turtle package 
import turtle  
  
# print the default  
# position i.e; (0.0, 0.0) 
print(turtle.pos()) 
  
# forward turtle by 150 pixels 
turtle.forward(150) 
  
# print current position  
# i.e; (150.0, 0.0) 
print(turtle.pos()) 
  
# forward turtle by 150 pixels 
# after taking turn right 
# by 90 degrees 
turtle.right(90) 
turtle.forward(150) 
  
# print position (after next move) 
# i.e; (150.0, -150.0) 
print(turtle.pos())

输出:

turtle movement example

(0.0, 0.0)
(150.0, 0.0)
(150.0, -150.0)

范例2:

Python3

# import turtle package 
import turtle  
  
# print position (by default) 
# i.e; (0.0, 0.0) 
print(turtle.pos()) 
  
# turtle move forward  
# by 40 pixels 
turtle.forward(40) 
  
# print position (after move) 
# i.e; (150.0, 0.0) 
print(turtle.position()) 
  
# turtle move forward by 40 pixels 
# after taking right turn  
# by 45 degrees 
turtle.right(45) 
turtle.forward(40) 
  
# print position 
# (after next move)  
print(turtle.pos()) 
  
# turtle move forward by 80  
# pixels after taking left 
# turn by 90 degrees 
turtle.left(90) 
turtle.forward(80) 
  
# print position 
# (after next move)  
print(turtle.pos()) 
  
# turtle move forward  
# by 40 pixels after taking  
# right turn by 90 degrees 
turtle.right(90) 
turtle.forward(40) 
  
# print position (after next move)  
print(turtle.position()) 
  
# turtle move forward by  
# 40 pixels after taking  
# left turn by 45 degrees 
turtle.left(45) 
turtle.forward(40) 
  
# print position  
# (after final move)  
print(turtle.pos())

输出:

turtle movement

(0.0, 0.0)
(40.0, 0.0)
(68.2842712475, -28.2842712475)
(124.852813742, 28.2842712475)
(153.13708499, 0.0)
(193.13708499, 0.0)



相关用法


注:本文由纯净天空筛选整理自deepanshu_rustagi大神的英文原创作品 turtle.pos() method in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。