Djanken
Djanken

Reputation: 13

Moving an object (square) using tkinter in python

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)

Upvotes: 0

Views: 742

Answers (1)

j_4321
j_4321

Reputation: 16169

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.

Upvotes: 1

Related Questions