Python tkinter: AttributeError: 'class' object has no attribute 'event'
Python tkinter: AttributeError: 'class' object has no attribute 'event'
代码如下:
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'
如果需要,请询问更多信息。
Ps。抱歉英语不好,我是初学者所以请不要判断。
改变你的方法:
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
代码如下:
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'
如果需要,请询问更多信息。
Ps。抱歉英语不好,我是初学者所以请不要判断。
改变你的方法:
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