Search code examples
pythontkintereventsevent-handlingattributeerror

Python tkinter: AttributeError: 'class' object has no attribute 'event'


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.


Solution

  • 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