Introduction
Drawing applications allow users to create illustrations interactively. This program demonstrates how to create a basic drawing app using Python’s Tkinter library, enabling users to draw freely on a canvas using the mouse.
Objective
The objective of this program is to create an interactive drawing application with basic functionality, including drawing lines on a canvas with the mouse.
Python Code
import tkinter as tk class DrawingApp: def __init__(self, root): self.root = root self.root.title("Basic Drawing App") self.canvas = tk.Canvas(root, width=800, height=600, bg="white") self.canvas.pack() self.canvas.bind("", self.draw) self.last_x, self.last_y = None, None def draw(self, event): if self.last_x and self.last_y: self.canvas.create_line(self.last_x, self.last_y, event.x, event.y, fill="black", width=2) self.last_x, self.last_y = event.x, event.y def reset_position(self, event): self.last_x, self.last_y = None, None if __name__ == "__main__": root = tk.Tk() app = DrawingApp(root) root.mainloop()
Program Explanation
This Python program uses the Tkinter library to create a basic drawing application. Here’s a breakdown of the program structure:
DrawingApp
: The main application class that initializes the drawing canvas and binds mouse events.draw
: Handles the drawing logic by creating lines on the canvas based on mouse movement.reset_position
: Resets the last mouse position when the mouse button is released.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
drawing_app.py
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python drawing_app.py
. - Use your mouse to draw on the canvas.