This code shows an example of how to create a graphical user interface (GUI) in Python with the Tkinter library, to draw with the mouse on a cartesian axis (or grid).
The main idea of the code is to create a Tkinter window and a Tkinter canvas, and draw the cartesian axis (or grid) on the canvas. Then, a mouse event handler is established for the canvas, which is called every time the mouse is moved over the canvas while the left mouse button is pressed. The event handler gets the current mouse position, and draws a dot on the canvas at the mouse position.
import tkinter as tk
# Create a Tkinter window
window = tk.Tk()
# Create a Tkinter canvas
canvas = tk.Canvas(window, width=600, height=600, bg='white')
# Draw the cartesian axis (or grid) on the canvas
canvas.create_line(0, 300, 600, 300, width=2) # x-axis
canvas.create_line(300, 0, 300, 600, width=2) # y-axis
# Bind a mouse event to the canvas to draw with the mouse
def draw(event):
# Get the current mouse position
x, y = event.x, event.y
# Draw a dot on the canvas at the current mouse position
canvas.create_oval(x-3, y-3, x+3, y+3, fill='black')
# Bind the '<B1-Motion>' event to the canvas to call the 'draw()' function
canvas.bind('<B1-Motion>', draw)
# Pack the canvas and start the main loop
canvas.pack()
window.mainloop()