0

I'm trying to move a square using WASD keys, with my implementation, I'm having trouble trying to passing arguments in the function update function. I am hoping to make it listen for an event from the keyboard. Can anyone help me?

class Robot(object):
    def __init__(self):

        self.speed = [0, 0]     # iniital speed ste to 0
        self.image = window.create_rectangle(0, 0, 20, 20, fill="white")  # sample robot
        window.bind_all("<KeyPress-w>", self.update)
        window.bind_all("<KeyPress-a>", self.update)
        window.bind_all("<KeyPress-s>", self.update)
        window.bind_all("<KeyPress-d>", self.update)
        # window.bind_all("<KeyPress-x>", self.deploy)

    def move(self, object, x, y):
        window.move(self.image, x, y)

    def update(self, event):

        if event.keysym == 'D':
            self.speed[1] = 1
            self.move(self.image, self.speed[0], 0)
        if event.keysym == "A":
            self.speed[1] = -1
            self.move(self.image, self.speed[0], 0)
        if event.keysym == "W":
            self.speed[0] = -1
            self.move(self.image, 0, self.speed[1])
        if event.keysym == "S":
            self.speed[0] = 1
            self.move(self.image, 0, self.speed[1])


    def deploy(self):
        pass

Here is the run point

while True:
    pl1 = Robot()
    pl1.update() # here is the problem
    tk.update()
    time.sleep(10)
1
  • Add print(event.keysym), to see what you get. Commented Dec 6, 2018 at 13:11

1 Answer 1

1

The first issue is that you are using time.sleep which freezes tkinter's mainloop, preventing it to react to keyboard events. You don't need a while True loop, just execute your Tk instance's mainloop.

The second issue is that you are invoking the Robot.update method without passing the expected argument event. It is unnecessary to do it yourself, the keyboard bindings will trigger it each time one of the keys are pressed.

I think my answer to the question Trying to make an object move in a grid with tkinter through player inputs should help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.