Reputation: 4592
I'm using the library turtle. It has the onkey command, as specified:
turtle.onkeypress(fun, key=None)
Parameters:
fun – a function with no arguments or None
key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)
However, I need to pass an argument. Was there any way to do this?
My code:
menuInitial.py
class MenuInitial(menu.Menu):
[...]
def itemInput(self):
turtle.Screen().onkey(menu.Menu.itemUp(self), "Up")
turtle.Screen().listen()
menu.py
class Menu(drawingGeometric.rectangle):
[...]
def itemUp(self):
self.turtle.left(90)
position.position.forwardWithoutPen(self, 16)
self.turtle.right(90)
As can be seen, the "MenuInitial" class is heir to the "Menu". I'm learning object orientation.
Upvotes: 0
Views: 2259
Reputation: 94951
It looks like you should just do this:
class MenuInitial(menu.Menu):
[...]
def itemInput(self):
turtle.Screen().onkey(self.itemUp, "Up")
turtle.Screen().listen()
Because you're passing itemUp
as a bound instance method (self.itemUp
) to onkey
instead of as an unbound method (menu.Menu.itemUp
), self
will automatically be passed as the first argument. You can do this because MenuInitial
is a child of Menu
, so they share the same internal state.
If for some reason you did need to pass another argument to itemUp
, you could use functools.partial
:
from functools import partial
[...]
def itemInput(self):
func = partial(self.itemUp, "some_argument")
turtle.Screen().onkey(func, "Up")
turtle.Screen().listen()
Then you could have this:
class Menu(drawingGeometric.rectangle):
[...]
def itemUp(self, argument):
print(argument) # This will print "some_argument"
self.turtle.left(90)
position.position.forwardWithoutPen(self, 16)
self.turtle.right(90)
Upvotes: 2