我想做一个记忆游戏,我有一个叫做“按钮”的类。你知道吗
tk = Tk()
tk.title('Memory Game')
tk.wm_attributes('-topmost', 1)
tk.resizable(0, 0)
canvas = Canvas(tk, width=400, height=600, bg='white', bd=0,
highlightthickness=0)
canvas.pack()
tk.update()
class Button:
def __init__(self, pos):
self.pos = pos
self.open = False
self.canvas = canvas
self.id = canvas.create_rectangle(pos[0], pos[1], pos[0]+100, pos[1]+100, fill='blue')
self.canvas.bind_all("<Button-1>", self.action)
print(self.pos)
#The positions are what they're supposed to be as of now.
def action(self, event):
print(self.pos)
#If you click on the screen, then the console prints out [300, 400] no matter what the actual position is.
print(event.x, event.y) #Prints out coords of where the mouse clicked
if event.x >= self.pos[0] and event.x <= self.pos[0] + 100:
if event.y >= self.pos[1] and event.y <= self.pos[1]+100:
self.canvas.coords(self.id, 1000, 1000, 1100, 1100)
#Makes Button Disappear from Tkinter Window
button_pos = [[0, 100], [0, 200], [0, 300], [0, 400], [100, 100], [100, 200], [100, 300], [100, 400], [200, 100], [200, 200], [200, 300], [200, 400], [300, 100], [300, 200], [300, 300], [300, 400]]
//coordinates for the buttons
buttons = []
for x in range(16):
buttons.append(Button(button_pos[x]))
如果运行此命令并单击屏幕,您将看到按钮的位置似乎总是[300400],无论发生什么。为什么会这样?除了右下角的按钮外,其他按钮都没有消失。你知道吗
问题在于:
实际上,每个按钮都试图接管整个画布的所有
Button-1
事件,因为应用程序中任何地方的所有小部件都使用bind_all
。所以,每一个都从前面的一个窃取绑定,最后,最后一个按钮得到所有的点击。你知道吗您要做的是让画布绑定按钮,然后点击测试点击,然后手动将其传递给矩形。例如,在所有现有代码之后(但在启动主循环之前),添加以下内容:
然后删除
self.canvas.bind_all
行。现在,canvas获得自己的点击,找到最接近点击的形状(这将是按创建顺序对矩形的基于一的索引),并手动分派事件。你知道吗相关问题 更多 >
编程相关推荐