user11093202
user11093202

Reputation:

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: enter image description here

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

Upvotes: 0

Views: 529

Answers (1)

cdlane
cdlane

Reputation: 41872

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 (e.g. 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()

enter image description here

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.

Upvotes: 2

Related Questions