Python Turtle: How to do onkeypress to a function in another file
Problem Description:
I have this issue in python turtle that when I attempt to do the onkeypress feature for a function that is in another file, nothing occurs. No error messages, no character movement. Nothing.
File 1 (Player Function and Creating Sprite):
class Player:
global player
import turtle
player = turtle.Turtle()
player.penup()
player.color("red")
player.shape("square")
player.shapesize(2, 2)
def moved(x, y):
player.forward(50)
File 2 (imports the function and when key pressed activates function):
import turtle
from Player import Player
from Player import moved
sc = turtle.Screen()
sc.title("Alpha")
sc.bgcolor("Gray")
sc.onkeypress(moved, "u")
sc.mainloop()
I tried to use the normal feature to do this, but it just didn’t work. Someone please tell me how to fix it.
Solution – 1
Just move the function in the other script or write in in only one script. Do you even need more scripts. Otherwise you didnt provide x and y for the function. To make the code nice you can also do from Player import * instead of two imports.
Solution – 2
You’re missing a call to sc.listen()
, which is required to enable key listeners.
Next, the callback to onkeypress
should accept 0 parameters, not 2. The x
and y
parameters are used for clicks. What x
and y
values would be relevant to a key press?
Furthermore, you don’t need the global
keyword here and imports should occur at the top of files. If moved
(should be named move
, a verb) is associated with the Player
, then it should be in the class. We might as well make it an instance-based class rather than a simple namespace. The convention is that files/modules are lowercase in Python.
Here’s a re-write suggestion:
player.py
:
import turtle
class Player:
def __init__(self):
self.turtle = t = turtle.Turtle()
t.penup()
t.color("red")
t.shape("square")
t.shapesize(2, 2)
def move(self):
self.turtle.forward(50)
main.py
:
import turtle
from player import Player
sc = turtle.Screen()
sc.title("Alpha")
sc.bgcolor("Gray")
player = Player()
sc.onkeypress(player.move, "u")
sc.listen()
sc.exitonclick()