mathtron999
mathtron999

Reputation: 129

Why is my program glitching and lagging out on me?

I'm working on a drawing app in python, and I recently added in a mousedrag function to make it so that you could drag the turtle and it would draw. It often gets a little bit laggy, and can go in other directions when I'm dragging it. Here's the code:

    import sys
import turtle
from tkinter import *


wn = turtle.Screen()
wn.title('Drawing Function!')
wn.bgcolor('blue')
ashton = turtle.Turtle()
ashton.pencolor('lime')
ashton.shape('turtle')




def turtleWrite():
    pass

def turtleForward():
    ashton.forward(30)

def turtleLeft():
    ashton.left(45)

def turtleRight():
    ashton.right(45)

def closeWindow():
    wn.bye()


def penup():
    ashton.penup()

def pendown():
    ashton.pendown()

def clear():
    ashton.clear()

def stamp():
    ashton.stamp()

def undo():
    ashton.undo()

ashton.ondrag(ashton.goto)

wn.onkey(turtleForward, 'Up')
wn.onkey(turtleLeft, 'Left')
wn.onkey(turtleRight, 'Right')
wn.onkey(closeWindow, 'q')
wn.onkey(penup, 'u')
wn.onkey(pendown, 'd')
wn.onkey(clear, 'c')
wn.onkey(stamp, 's')
wn.onkey(undo, 'BackSpace')




wn.listen()
wn.mainloop()

Does anyone have any ideas why this is happening, and if so, how I can fix them?

Thanks!

Upvotes: 0

Views: 248

Answers (1)

cdlane
cdlane

Reputation: 41872

The turtle documentation is a little oversimplified when it suggests turtle.ondrag(turtle.goto) to draw freehand. To make it work you need to define your own event handler that immediately disables drag events on entry, moves the turtle and then reenables drag events on exit:

import turtle

wn = turtle.Screen()
wn.title('Drawing Function!')
wn.bgcolor('blue')

ashton = turtle.Turtle()
ashton.pencolor('green')
ashton.shape('turtle')

def drag_handler(x, y):
    ashton.ondrag(None)  # disable event inside event handler
    ashton.goto(x, y)
    ashton.ondrag(drag_handler)  # reenable event on event handler exit

ashton.ondrag(drag_handler)

wn.onkey(lambda: ashton.forward(30), 'Up')
wn.onkey(lambda: ashton.left(45), 'Left')
wn.onkey(lambda: ashton.right(45), 'Right')
wn.onkey(lambda: wn.bye(), 'q')
wn.onkey(lambda: ashton.penup(), 'u')
wn.onkey(lambda: ashton.pendown(), 'd')
wn.onkey(lambda: ashton.clear(), 'c')
wn.onkey(lambda: ashton.stamp(), 's')
wn.onkey(lambda: ashton.undo(), 'BackSpace')

wn.listen()
wn.mainloop()

My system blew up with pen color 'lime' ("TurtleGraphicsError: bad color string: lime") so I had to substitute 'green' for this example.

enter image description here

Upvotes: 2

Related Questions