-1

I would like to create a GUI where the user could draw on a grid (or a Cartesian axis) using the mouse and obtain the coordinates of the initial and final points of each bar or arc drawn.

I'm starting studies in python and I'm not able to create this program with my basic knowledge of Tkinter. I would be grateful if someone could help me.

1
  • 1
    Please read How to Ask to help you create a question that the community can answer. What have you tried so far? This answer might be useful for you. Dec 6, 2022 at 1:52

1 Answer 1

0

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()
3
  • FYI the OP provided no code or other details; this isn't the place to have people post requirements and others then implement those requirements. Dec 7, 2022 at 1:35
  • Understood, I'm new to this, I'll go back and look at the rules and be more careful. Dec 7, 2022 at 1:57
  • Understood too! I'll create a new question.
    – P_Python
    Dec 7, 2022 at 3:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.