如何将鼠标单击位置添加到tkinter中的列表?

时间:2015-02-19 20:06:48

标签: python events tkinter click

我正在尝试使用python中的tkinter创建鼠标点击列表。以下是我到目前为止的情况:

def main():

    master = Tk()
    w = Canvas(master, width=400, height=400)
    w.pack()
    w.create_line(0, 200, 400, 200)
    w.create_line(200, 0, 200, 400)
    circle = w.create_oval(190, 190, 210, 210,
                               fill='blue', width=1)

    w.bind('<Button-1>', lambda event: left_mouse_click(event))


    mainloop()

def left_mouse_click(event, robot, speed):

    # Should create and return a list
    canvas = event.widget
    canvas.create_oval(event.x - 10, event.y - 10,
                       event.x + 10, event.y + 10,
                       fill='red', width=1)

如何将每个event.x和event.y保存到单独的列表中?

非常感谢!

1 个答案:

答案 0 :(得分:0)

您需要发送要添加的列表。我称之为clicks

所以main看起来像这样:

def main():

    master = Tk()
    w = Canvas(master, width=400, height=400)
    w.pack()
    w.create_line(0, 200, 400, 200)
    w.create_line(200, 0, 200, 400)
    circle = w.create_oval(190, 190, 210, 210,
                               fill='blue', width=1)

    # create list of clicks
    clicks = []
    # create function to track clicks into 'clicks'
    tracking_function = track_to_list(clicks)
    # use clicks tracker generated as click handler
    w.bind('<Button-1>', lambda event: tracking_function(event))


    mainloop()

生成点击跟踪功能(闭包)的功能:

def track_to_list(lst):
    def left_mouse_click(event, robot, speed):

        # Should create and return a list
        canvas = event.widget
        canvas.create_oval(event.x - 10, event.y - 10,
                           event.x + 10, event.y + 10,
                           fill='red', width=1)
        # add tuple (x, y) to existing list
        lst.append((event.x, event.y,))
    return left_mouse_clicks

这将返回一个具有lst访问权限的函数,并生成一个事件处理程序(就像你所拥有的那样),并添加了一行附加到lst的行。