【问题标题】:Python tkinter: AttributeError: 'class' object has no attribute 'event'Python tkinter:AttributeError:'class'对象没有属性'event'
【发布时间】:2021-01-13 19:59:46
【问题描述】:

代码如下:

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()

此代码输出AttributeError: 'Main' object has no attribute 'event'

我尝试添加self.event = Event,但会显示错误AttributeError: type object 'Event' has no attribute 'char'

如果需要,请询问更多信息。

附言。抱歉英语不好,我是初学者,所以请不要评判。

【问题讨论】:

    标签: python tkinter events event-handling attributeerror


    【解决方案1】:

    改变你的方法:

        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)
    

    你试过self.event。你只需要event

    【讨论】:

    • 非常感谢,它就像魔术一样!
    • 我很乐意提供帮助!祝项目顺利
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2021-12-29
    • 2020-08-08
    • 2016-11-18
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多