在第 17 行(下面的代码)上,我尝试使用 event.x event.y 获取鼠标光标的 x 和 y 坐标,但是如果单击窗口,则会出现错误:'hi' object has no attribute 'x' :
from tkinter import *
import time
tk=Tk()
tk.wm_attributes('-topmost',1)
tk.resizable(0,0)
canvas=Canvas(tk,width=700,height=525,bd=0,highlightthickness=0)
canvas.pack()
tk.title('GAME')
tk.update()
class hi():
def __init__(self,canvas):
self.canvas=canvas
self.id=self.canvas.create_polygon(15,0, 0,15, 10,30, 10,40, 0,50, 10,45, 0,70, 15,50, 30,70, 20,45, 30,50, 20,40, 20,30, 30,15, fill='green')
self.canvas.bind_all('<Button-1>',self.hit)
def hit(event,self):
if event.x>pos[0] and event.x<pos[2] and event.y>pos[1] and event.x<pos[3]:#ТУТ
self.canvas.itemconfig(self.id,fill='red')
tk.update()
time.sleep(0.1)
self.canvas.itemconfig(self.id,fill='green')
tk.update()
obj=hi(canvas)
更改
def hit(event,self):
为def hit(self, event):
。特殊词“self”必须始终作为第一个参数出现。