not here
not here

Reputation: 43

Arrow Commands in Python Turtle

I have been trying to put turtle in tkinter using the canvas feature. I want to be able to make a turtle etcher sketcher thing so that I can control the turtle with arrow keys. I cannot seem to get it to work and don't understand the error it spits out:

NameError: name 'Screen' is not defined

Here is my code:

import tkinter as tk
import turtle

window = tk.Tk()
window.geometry("750x500")
window.resizable(0,0)

app = tk.Canvas(master = window,
                width = 500,
                height = 500,
                bg = "white")
app.pack()
Screen()
turtle = turtle.RawTurtle(app)
turtle = turtle.Screen()

def k1():
    move.forward(1)

def k2():
    move.left(1)

def k3():
    move.right(1)

def k4():
    move.back(1)

turtle.onkey(k1, "Up")
turtle.onkey(k2, "Left")
turtle.onkey(k3, "Right")
turtle.onkey(k4, "Down")

turtle.listen()
window.mainloop()

Upvotes: 0

Views: 176

Answers (2)

cdlane
cdlane

Reputation: 41872

Just as you used RawTurtle instead of Turtle, when you use turtle embedded in a tkinter window, you need to use TurtleScreen instead of Screen, if you want the methods it provides:

import tkinter as tk
from turtle import TurtleScreen, RawTurtle

window = tk.Tk()
window.geometry("750x500")
window.resizable(0, 0)

canvas = tk.Canvas(master=window, width=500, height=500)
canvas.pack()

screen = TurtleScreen(canvas)
turtle = RawTurtle(screen)

def k1():
    turtle.forward(1)

def k2():
    turtle.left(1)

def k3():
    turtle.right(1)

def k4():
    turtle.back(1)

screen.onkey(k1, "Up")
screen.onkey(k2, "Left")
screen.onkey(k3, "Right")
screen.onkey(k4, "Down")

screen.listen()
screen.mainloop()

Don't use standalone turtle's Screen in this situation, as it will potentially create a second tkinter root window, leading to subtle errors later (like images not loading.)

Upvotes: 1

furas
furas

Reputation: 142641

You have to use

turtle.Screen()

instead of

Screen()

But I see other problems with code. And I would use tkinter method bind() to execute function when key is pressed.

import tkinter as tk
import turtle

# --- functions ---

def k1(event):
    t.forward(1)

def k2(event):
    t.left(1)

def k3(event):
    t.right(1)

def k4(event):
    t.back(1)

# --- main ---

window = tk.Tk()

window.geometry("750x500")
window.resizable(False, False)

canvas = tk.Canvas(master=window, width=500, height=500, bg="white")
canvas.pack()

t = turtle.RawTurtle(canvas)

window.bind("<Up>", k1)
window.bind("<Left>", k2)
window.bind("<Right>", k3)
window.bind("<Down>", k4)

window.mainloop()

Upvotes: 1

Related Questions