I wrote a simple python code which creates canvas and items in canvas can be moved freely using mouse only. Also, previous shapes created in canvas can be moved. However, I have some problems here:
- When moving items like 1 rect. 1 circle, somehow they overlap or one of them completely unseen in canvas.
- My delete button works but I can't do anything after using delete button. System gives error. (I think I couldn't make object_id value 0 because after reset, I add rect. and object_id doesn't start from 0, and interestingly it has no coord?? )
- When I try to drag shapes in canvas, mouse automatically picks top left corner of the shape, how can I change it? (Maybe moving shapes from the point that I try to click with mouse)
My code:
from tkinter import *
from tkinter import messagebox
def click(event):
my_label.config(text="Coordinates: x: "+ str(event.x) +" y: " +str(event.y))
if object_id is not None:
for i in range(object_id):
coord = my_canvas.coords(i+1) # +1 added because for loop starts from 0
print(coord)
print(object_id)
if ((event.x<=coord[2]+10) and (event.x>=coord[0]-10) and (event.y<=coord[3]+10) and
(event.y>=coord[1])-10):
print(coord)
width = coord[2] - coord[0]
height = coord[3] - coord[1]
my_canvas.coords(i+1, event.x, event.y, event.x+width, event.y+height)
else:
pass
else:
pass
def label_mod(event): #While not pressing button, show coords!
my_label.config(text="Coordinates: x: "+ str(event.x) +" y: " +str(event.y))
def delete():
global object_id #Delete butonunda sistem fail oluyor
msg = messagebox.askyesnocancel('Info', 'Delete my_canvas ?')
if msg == True:
my_canvas.delete(ALL)
print(object_id)
object_id=0
print(object_id)
def create_rectangle():
global object_id
object_id=my_canvas.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3)
def create_line():
global object_id
object_id=my_canvas.create_line(200, 200, 100, 100, fill='red', width=5)
def create_circle():
global object_id
object_id=my_canvas.create_oval(10, 10, 70, 70, fill='orange', outline='blue')
# Main Codes
object_id = 0
root = Tk()
root.title('Moving objects')
root.resizable(width=False, height=False)
root.geometry('1200x600+100+50')
root.configure(bg='light green')
my_label=Label(root, text="")
my_label.pack()
my_canvas = Canvas(root, bg='white', height=500, width=500)
my_canvas.pack(side=RIGHT)
my_canvas.bind("<B1-Motion>", click)
my_canvas.bind("<Motion>", label_mod)
btn_line = Button(root, text='Line', width=30, command=create_line)
btn_line.pack()
btn_rectangle = Button(root, text='Rectangle', width=30, command=create_rectangle)
btn_rectangle.pack()
btn_circle = Button(root, text='Circle', width=30, command=create_circle)
btn_circle.pack()
btn_delete = Button(root, text='Delete', width=30, command=delete)
btn_delete.pack()
root.mainloop()