变量在没有我接触的情况下变化

时间:2018-03-29 23:28:14

标签: python tkinter

我正在尝试制作记忆游戏,我有一个叫做“按钮”的课程。

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

如果你运行它并点击屏幕,你会看到按钮的位置似乎总是[300,400],无论如何。为什么会这样?除了右下角按钮之外,没有任何按钮实际消失。

1 个答案:

答案 0 :(得分:0)

问题在于:

self.canvas.bind_all("<Button-1>", self.action)

每个按钮都会尝试接管整个画布的所有Button-1事件 - 实际上,因为您正在使用bind_all,因为应用中的所有小部件都可以使用。因此,每个人都会窃取之前的绑定,最后,最后一个按钮会获得所有点击。

您要做的是让 canvas 绑定按钮,然后点击测试点击,然后手动将其传递给矩形。例如,在所有现有代码之后(但在开始主循环之前),添加:

def action(event):
    item, = canvas.find_closest(event.x, event.y)
    buttons[item-1].action(event)
canvas.bind("<Button-1>", action)

然后删除self.canvas.bind_all行。现在,画布获得自己的点击次数,找到与点击最接近的形状(按创建顺序为矩形的一个基础索引),并手动调度事件。

相关问题