简体   繁体   中英

Problems while drawing straight line and dragging in Tkinter canvas

So, I'm trying to draw vertical lines in canvas on the click of the button "line".

These are the problems and my requirements:

  1. When i try click on the line drawn to drag it to a position, it repels away from the mouse cursor but moves in the correct direction. What do i do to prevent this?
  2. On subsequent clicks on the "line" button, i want a new line to be drawn (every time i click) while the original lines stays in the canvas unmoved.
  3. The latest line is the only one which can be dragged. All other lines should be static.
  4. I want coordinates of all these drawn lines. How do i get these?

This is the code i've written:

from tkinter import *   
root = Tk()             

canvas = tkinter.Canvas(root, width = 480,height = 600) 
canvas.pack()

def draw_lines():
    canvas.create_line(300, 35, 300, 200, dash=(4, 2))

def drag(event):
    event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)


canvas.bind("<B1-Motion>", drag)

btn1 = Button(root, text = 'line', bd = '5',command = draw_lines)
btn2 = Button(root, text = 'Close', bd = '5',command = root.destroy)

btn1.pack(side = 'top')   
btn2.pack(side = 'top')

canvas.mainloop()

please help!!!!

Using Python 3.11.0rc1.

I added:

  • geometry . so it will not resize when dragging.
  • Canvas . You have to play around with height set to 800
  • I removed bd=5 . You can suit yourself. Don't use quote.
  • I removed Quotes for this btn1.pack(side=TOP)
  • At last canvas.pack() always next to mainloop()

Here is the code re-worked:

from tkinter import *


root = Tk()             
root.geometry('400x650')

canvas = Canvas(root, width=480, height=600) 
 

def draw_lines():
    canvas.create_line(300, 35, 300, 200, dash=(4, 2))
    

def drag(event):
    event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)



canvas.bind("<B1-Motion>", drag)

btn1 = Button(root, text='line',  command=draw_lines)
btn2 = Button(root, text= 'Close', command=root.destroy)

btn1.pack(side=TOP)   
btn2.pack(side=TOP)


canvas.pack()
canvas.mainloop()

Result output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM