📜  在Python中使用 Turtle 绘制移动对象

📅  最后修改于: 2022-05-13 01:55:39.373000             🧑  作者: Mango

在Python中使用 Turtle 绘制移动对象

先决条件: Python Turtle 基础

Turtle是Python中的一个内置模块。它使用屏幕(纸板)和海龟(笔)提供绘图。要在屏幕上绘制一些东西,我们需要移动海龟。要移动海龟,有一些函数,即 forward()、backward() 等。

1.)移动物体(球):

下面是实现:

Python3
# import turtle package
import turtle


# function for movement of an object 
def moving_object(move):
    
    # to fill the color in ball
    move.fillcolor('orange') 
    
    # start color filling
    move.begin_fill() 
    
    # draw circle
    move.circle(20)  
    
    # end color filling
    move.end_fill()             

# Driver Code
if __name__ == "__main__" :
    
    # create a screen object
    screen = turtle.Screen() 

    # set screen size
    screen.setup(600,600)    

    # screen background color
    screen.bgcolor('green')   

    # screen updaion 
    screen.tracer(0)           

    # create a turtle object object
    move = turtle.Turtle() 

    # set a turtle object color
    move.color('orange')

    # set turtle object speed
    move.speed(0) 

    # set turtle object width
    move.width(2)     

    # hide turtle object
    move.hideturtle()          

    # turtle object in air
    move.penup()               

    # set initial position
    move.goto(-250, 0) 

    # move turtle object to surface
    move.pendown()             

    # infinite loop
    while True :
        
        # clear turtle work
        move.clear()  
        
        # call function to draw ball
        moving_object(move)   
        
        # update screen
        screen.update()    
        
        # forward motion by turtle object
        move.forward(0.5)      


输出 :

海龟中的移动物体

示例 2:移动对象(框)

以下是实现:-

Python3
import turtle

screen = turtle.Screen()
screen.setup(500,500)
screen.bgcolor('Green')

# tell screen to not 
# show automatically
screen.tracer(0)            

t = turtle.Turtle()
t.speed(0)
t.width(3)

# hide donatello, we
# only want to see the drawing
t.hideturtle()            

def draw_square() :
    t.fillcolor("Orange")
    t.begin_fill()
    for side in range(4) :
        t.forward(100)
        t.left(90)
    t.end_fill()
t.penup()
t.goto(-350, 0)
t.pendown()

while True :
    t.clear()
    draw_square()
    
    # only now show the screen,
    # as one of the frames
    screen.update()         
    t.forward(0.02)
    
# This code is contributed by pulkitagarwal03pulkit