Jack Snowdon
Jack Snowdon

Reputation: 63

Python Turtle key bindings only working once

I was trying to creating a simple keyboard drawing program with turtle that saves your drawing for later, however when trying to use the key bindings to move around, I can only move once.

I am running Windows 10. I am writing this for a rendering engine I built called Ren that uses this file-format to render shapes.

Here is my code:

import turtle
from tkinter.filedialog import *

s = turtle.Screen()
s.title("Ren Poly Editor")

t = turtle.Turtle()

fileName = askopenfilename()

with open(fileName) as file:
    rendataLayer1 = file.read().split("\n")
    rendata = []
    for i in rendataLayer1:
        if not i.startswith("#") and i:
            rendata.append(str(i.split()))

t.color("black")

for i in rendata:
    i = eval(i)

    print(i[0] + " " + i[1])

    if i[0] == "cl":
        t.color(i[1])

    elif i[0] == "fd":
        t.fd(int(i[1]))

    elif i[0] == "bk":
        t.back(int(i[1]))

    elif i[0] == "lt":
        t.lt(int(i[1]))

    elif i[0] == "rt":
        t.rt(int(i[1]))

def fd():
    distance = s.textinput("Forward", "How far?")

    t.fd(int(distance))

    with open(fileName, "a") as file:
        file.write("fd " + distance + "\n")

def bk():
    distance = s.textinput("Backward", "How far?")

    t.back(int(distance))

    with open(fileName, "a") as file:
        file.write("bk " + distance + "\n")

def lt():
    distance = s.textinput("Forward", "How much?")

    t.lt(int(distance))

    with open(fileName, "a") as file:
        file.write("lt " + distance + "\n")

def rt():
    distance = s.textinput("Forward", "How much?")

    t.rt(int(distance))

    with open(fileName, "a") as file:
        file.write("rt " + distance + "\n")


s.onkeypress(fd, "Up")
s.onkeypress(bk, "Down")
s.onkeypress(lt, "Left")
s.onkeypress(rt, "Right")
s.listen()

s.mainloop()

Upvotes: 1

Views: 143

Answers (1)

cdlane
cdlane

Reputation: 41905

Whenever you call the textinput() method in Python turtle (or the similar numinput()), it undoes your listen() call as the window that pops up to take input becomes the listener. Simply add another listen() call after each call to textinput() and things should behave as you expect.

Upvotes: 2

Related Questions