简体   繁体   中英

How to make a graphic in turtle to Move?

I have made a graphic in turtle like this:

from turtle import *
from random import randint
left(20)
speed("fastest")
for i in range(36):
    left(120)
    fd(100)
    left(120)
    fd(100)
    left(120)
    fd(100)
    left(10)

it makes this: 在此处输入图片说明

now how to make the triangle-circle rotate? Like I want to drag it, and I want it to rotate.

how to make the triangle-circle rotate?

By repeatedly clearing it and redrawing it slightly rotated when no one's looking:

from turtle import *

def rotate():

    clear()

    for _ in range(36):
        for _ in range(3):
            left(120)
            fd(100)

        left(10)

    update()
    left(1)
    ontimer(rotate, 60)

left(20)
tracer(False)

rotate()

exitonclick()

This code is fragile in that several operations can cause screen updates to occur, other than update() itself, so rearranging the code or substituting other methods (eg undo() ) might not have the affect you desire.

I want to drag it

This is trickier and the result you get may depend on your architecture (Unix or Windows.) We'll make it into a cursor, which is draggable. But cursors treat their polygons as filled. So depending on the underlying Tk implementation, your results might vary. A lot.

from turtle import *

def graphic():
    penup()
    tracer(False)
    begin_poly()

    for _ in range(36):
        for _ in range(3):
            left(120)
            fd(100)

        left(10)

    end_poly()
    tracer(True)
    pendown()

    return get_poly()

def drag_handler(x, y):
    ondrag(None)
    goto(x, y)
    ondrag(drag_handler)

register_shape('graphic', graphic())

ondrag(drag_handler)

shape('graphic')
color('black', 'white')

mainloop()

在此处输入图片说明

I fear on Windows this cursor may appear as just a large, black blob.

I want to drag it, and I want it to rotate

And I want to leave that as an exercise for the reader. But here it is anyway:

from turtle import *

def rotate():
    left(1)
    ontimer(rotate, 60)

def graphic():
    penup()
    tracer(False)
    begin_poly()

    for _ in range(36):
        for _ in range(3):
            left(120)
            fd(100)

        left(10)

    end_poly()
    tracer(True)
    pendown()

    return get_poly()

def drag_handler(x, y):
    ondrag(None)
    goto(x, y)
    ondrag(drag_handler)

register_shape('graphic', graphic())

ondrag(drag_handler)

shape('graphic')
color('black', 'white')

rotate()

mainloop()

Again, depending on environment, you may be dragging a large, rotating, black blob. Now that the graphic image is a cursor, the rotation part is much simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM