0

Here is the code:

from tkinter import *

class Main:
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width="600", height="400")
        self.canvas.pack()

        self.r1 = self.canvas.create_polygon(20, 0, 20, 20, 40, 10, fill='red')
        self.loop()

    def keypress(self, event):
        x, y = 0, 0
        if self.event.char == "a":
            x = -4
        if self.event.char == "d":
            x = 4
        if self.event.char == "w":
            y = -4
        if self.event.char == "s":
            y = 4
        self.canvas.move(self.r1, x, y)

    def loop(self):
        self.root.bind_all("<Key>", self.keypress)
        self.root.mainloop()

main = Main()

This code outputs AttributeError: 'Main' object has no attribute 'event'

I have tried to add self.event = Event but it will display error AttributeError: type object 'Event' has no attribute 'char'

Please ask for more information if needed.

Ps. Sorry for bad english and i am beginner coder so please don't judge.

0

1 Answer 1

3

Change your method:

    def keypress(self, event):
        x, y = 0, 0
        if event.char == "a":
            x = -4
        if event.char == "d":
            x = 4
        if event.char == "w":
            y = -4
        if event.char == "s":
            y = 4
        self.canvas.move(self.r1, x, y)

You tried self.event. You need just event

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

2 Comments

Thank you so much, it worked like a magic!
I was glad to help! Good luck with the project

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.