Skip to content Skip to sidebar Skip to footer

Draw On Python Tkinter Canvas Using Mouse And Obtain Points To A List?

I'm working on a Python application using tkinter. What I want to do is to draw on canvas coordinates, and the points will be recorded to a list so I can do calculation later. If i

Solution 1:

Start with

import tkinter as tk
root = tk.Tk()
def mmove(event):
    print(event.x, event.y)
root.bind('<Motion>', mmove)
root.mainloop()

Then elaborate as you wish. Bind motion to a canvas, draw points on the canvas, append pairs to a list, bind clicks instead or in addition, filter the stream of points, etc.

Solution 2:

Thank you Terry for providing a very useful hint. I managed to get it working. Note that this is not the optimal solution because of the redundant points recorded. That's why I have to pop it out a lot. But it works, at least.

import tkinter as tk

classExampleApp(tk.Tk):
    def__init__(self):
        tk.Tk.__init__(self)
        self.previous_x = self.previous_y = 0
        self.x = self.y = 0
        self.points_recorded = []
        self.canvas = tk.Canvas(self, width=400, height=400, bg = "black", cursor="cross")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.button_print = tk.Button(self, text = "Display points", command = self.print_points)
        self.button_print.pack(side="top", fill="both", expand=True)
        self.button_clear = tk.Button(self, text = "Clear", command = self.clear_all)
        self.button_clear.pack(side="top", fill="both", expand=True)
        self.canvas.bind("<Motion>", self.tell_me_where_you_are)
        self.canvas.bind("<B1-Motion>", self.draw_from_where_you_are)

    defclear_all(self):
        self.canvas.delete("all")

    defprint_points(self):
        if self.points_recorded:
            self.points_recorded.pop()
            self.points_recorded.pop()
        self.canvas.create_line(self.points_recorded, fill = "yellow")
        self.points_recorded[:] = []

    deftell_me_where_you_are(self, event):
        self.previous_x = event.x
        self.previous_y = event.y

    defdraw_from_where_you_are(self, event):
        if self.points_recorded:
            self.points_recorded.pop()
            self.points_recorded.pop()

        self.x = event.x
        self.y = event.y
        self.canvas.create_line(self.previous_x, self.previous_y, 
                                self.x, self.y,fill="yellow")
        self.points_recorded.append(self.previous_x)
        self.points_recorded.append(self.previous_y)
        self.points_recorded.append(self.x)     
        self.points_recorded.append(self.x)        
        self.previous_x = self.x
        self.previous_y = self.y

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

Post a Comment for "Draw On Python Tkinter Canvas Using Mouse And Obtain Points To A List?"