Reputation: 1
I am a beginner programmer, sorry if the answer is obvious. Any help is appreciated.
I am currently using WIN.onkeypress()
to call functions but my scroll_draw_col
function requires the argument curr_draw_col
. I know WIN.onkeypress()
can't pass arguments to their function. How do I call the scroll_draw_col
function with curr_draw_col
as an argument on keypress ("f")?
def scroll_draw_col(curr_draw_col):
curr_draw_col += 1
WIN.listen()
WIN.onkeypress(tri_fwd, 'Up') # Unrelated
WIN.onkeypress(tri_bkw, 'Down') # Unrelated
WIN.onkeypress(tri_left, 'Left') # Unrelated
WIN.onkeypress(tri_right, 'Right') # Unrelated
WIN.onkeypress(scroll_draw_col, 'f') # <-----
while True:
WIN.update()
dra.goto(tri.xcor(), tri.ycor()) # Unrelated
print(curr_draw_col) # To see if curr_draw_col is being incremented by 1
Upvotes: 0
Views: 56
Reputation: 1014
I'm sure Lecdi's answer is sufficient but I thought I might add a couple more methods. It looks like what you are trying to do with this function call is change some state, increment a variable. For this, there are two techniques I'd suggest. For your particular use case, I would suggest a class.
class DrawColTrack:
def __init__(self):
self.col = 0
def increment(self):
self.col+=1
draw_col_tracker = DrawColTrack()
WIN.listen()
WIN.onkeypress(tri_fwd, 'Up') # Unrelated
WIN.onkeypress(tri_bkw, 'Down') # Unrelated
WIN.onkeypress(tri_left, 'Left') # Unrelated
WIN.onkeypress(tri_right, 'Right') # Unrelated
WIN.onkeypress(draw_col_tracker.increment, 'f') # <-----
while True:
WIN.update()
dra.goto(tri.xcor(), tri.ycor()) # Unrelated
print(draw_col_tracker.col) # To see if curr_draw_col is being incremented by 1
The other way which I think is worth mentioning on the topic of lambdas etc is to create a closure.
def gen_col_incrementer(starting_value):
def _():
starting_value+=1
return starting_value
return _
increment = gen_col_incrementer(0)
assert 1 == increment()
Upvotes: 1
Reputation: 2241
Simply use global
and remove the argument altogether. However, for future reference, you can pass an argument to a function without running it by using lambda
:
# What you should do
def scroll_draw_col():
global curr_draw_col
curr_draw_col += 1
WIN.listen()
WIN.onkeypress(tri_fwd, 'Up') # Unrelated
WIN.onkeypress(tri_bkw, 'Down') # Unrelated
WIN.onkeypress(tri_left, 'Left') # Unrelated
WIN.onkeypress(tri_right, 'Right') # Unrelated
WIN.onkeypress(scroll_draw_col, 'f') # <-----
while True:
WIN.update()
dra.goto(tri.xcor(), tri.ycor()) # Unrelated
print(curr_draw_col) # To see if curr_draw_col is being incremented by 1
# If you wanted to pass an argument on a key press
WIN.onkeypress(lambda: function_name(argument), 'f')
Upvotes: 1