I am fairly comfortable with drawing in Tkinter but you only see the shape once you release the mouse button. How do you see the shape as you drag the mouse? I am half way there with the below code but if you run it you will see it doesn't update to remove each drawing made by the motion function.
from tkinter import *
window = Tk()
canvas = Canvas(bg='black')
canvas.pack()
def locate_xy(event):
global current_x, current_y
current_x, current_y = event.x, event.y
def draw_circle(event):
global current_x, current_y
canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
current_x, current_y = event.x, event.y
def update_circle(event):
global current_x, current_y
canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
canvas.bind('<ButtonPress-1>', locate_xy)
canvas.bind('<ButtonRelease-1>', draw_circle)
canvas.bind('<B1-Motion>', update_circle)
window.mainloop()
CodePudding user response:
You just need to create the oval inside locate_xy() and update its coordinates inside update_circle(). The binding of <ButtonRelease-1> is not necessary:
def locate_xy(event):
global current_x, current_y, current_item
current_x, current_y = event.x, event.y
# create the oval item and save its ID
current_item = canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
def update_circle(event):
# update coords of the oval item
canvas.coords(current_item, (current_x, current_y, event.x, event.y))
canvas.bind('<ButtonPress-1>', locate_xy)
canvas.bind('<B1-Motion>', update_circle)
CodePudding user response:
You are already tracking mouse move with left button pressed by event <B1-Motion>, so just add drawing there:
from tkinter import *
window = Tk()
canvas = Canvas(bg='black')
canvas.pack()
def draw_line(event):
x, y = event.x, event.y
canvas.create_oval((x-2, y-2, x 2, y 2), outline='white')
canvas.bind('<B1-Motion>', draw_line)
window.mainloop()

