當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。