Home > OS >  Python Turtle: How to do onkeypress to a function in another file
Python Turtle: How to do onkeypress to a function in another file

Time:12-05

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.

CodePudding user response:

You need the moved function defined within the Player class. In your code the moved function is defined outside of the Player class. So it is not a method of the Player class. So, when you try to use the onkeypress method to call the moved function, it does not have access to the player object that is defined within the Player class.

CodePudding user response:

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. Hope this helps!

  • Related