user3118523
user3118523

Reputation: 11

Bind keys so I can press them simultaneously

N.B. This is not all the code. What I really want to do is bind player 1 keys (wasd) and player 2 keys (up,down,right,left) so I can press them at the same time and therefore control both players separately but simultaneously(Player 2 is not in the code)) So here is my current code:

    def p1_move_N(self):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, (p1_y-line_length), width=line_width, fill=p1_colour)
    p1_y = p1_y - line_length

def p1_move_S(self):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, p1_y+line_length, width=line_width, fill=p1_colour)
    p1_y = p1_y + line_length

def p1_move_E(self):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x + line_length, p1_y, width=line_width, fill=p1_colour)
    p1_x = p1_x + line_length

def p1_move_W(self):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x - line_length, p1_y, width=line_width, fill=p1_colour)
    p1_x = p1_x - line_length

p1_press = None # which key is the player holding down?

def change_press(key, up_down):
    if up_down == "up":
        p1_press=None
    else:
        p1_press=key.keysym


while(True):
    print(p1_press)

window.bind("<KeyPress-w>", change_press('down'))
window.bind("<KeyPress-s>", change_press('down'))
window.bind("<KeyPress-a>", change_press('down'))
window.bind("<KeyPress-d>", change_press('down'))
window.bind("<KeyRelease-w>", change_press('up'))
window.bind("<KeyRelease-s>", change_press('up'))
window.bind("<KeyRelease-a>", change_press('up'))
window.bind("<KeyRelease-d>", change_press('up'))

I have started to to do it but I can't seem to debug the fact that all my code throws back is this:(when 'w' key pressed)

    None
    Nonew
    wNone
    None
    Nonew

This is from the loop

It should return:

None
w
None
None
w
None

Any help is much appreciated!!

Upvotes: 0

Views: 205

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

When you do this: window.bind("<KeyPress-w>", change_press('down')), tkinter will call the function change_press('down'), and whatever that returns is what is associated with the binding. In other words you are calling the function at initialization, not each time the key is pressed.

A simple modification is to change your bindings to look like this:

window.bind("<KeyPress-w>", lambda event: change_press('down'))

lambda will create a new, anonymous function which takes an event as an argument (supplied by Tkinter when it calls the bound function). This new function will be associated with the binding. It will then call the change_press function when the binding fires.

Also, this collection of statements will run forever, preventing your GUI from ever showing up:

while(True):
    print(p1_press)

You need to remove that code.

Upvotes: 1

Related Questions