To draw a line with mouse clicks in Python, you can use a graphical library such as Tkinter. Below is a simple example using Tkinter to create a window where you can draw a line by clicking and dragging the mouse:
import tkinter as tk
class LineDrawer:
def __init__(self, root):
self.root = root
self.root.title("Line Drawer")
self.canvas = tk.Canvas(root, width=800, height=600, bg="white")
self.canvas.pack()
self.start_x = None
self.start_y = None
self.canvas.bind("<Button-1>", self.on_click)
self.canvas.bind("<B1-Motion>", self.on_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_release)
def on_click(self, event):
self.start_x = event.x
self.start_y = event.y
def on_drag(self, event):
if self.start_x is not None and self.start_y is not None:
self.canvas.delete("line") # Clear previous lines
self.canvas.create_line(self.start_x, self.start_y, event.x, event.y, tags="line")
def on_release(self, event):
# You can perform actions when the mouse button is released
pass
if __name__ == "__main__":
root = tk.Tk()
app = LineDrawer(root)
root.mainloop()
In this example:
- Clicking the left mouse button sets the starting point (
start_x
,start_y
). - Dragging the mouse draws a line from the starting point to the current mouse position.
- Releasing the left mouse button can trigger additional actions (currently set to do nothing in this example).
This is a basic illustration, and you can extend it with additional features based on your requirements. For more advanced drawing and interaction capabilities, you might consider using more powerful graphical libraries such as Pygame or Pyglet.