简体   繁体   English

在 Tkinter canvas 中绘制直线和拖动时出现问题

[英]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".所以,我试图通过单击“线”按钮在 canvas 中绘制垂直线。

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.当我尝试单击绘制的线将其拖动到 position 时,它会排斥鼠标 cursor,但会朝正确的方向移动。 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.在随后单击“线”按钮时,我希望绘制一条新线(每次单击),而原始线保持在 canvas 中不动。
  3. The latest line is the only one which can be dragged.最新的线是唯一可以拖动的。 All other lines should be static.所有其他行应为 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.使用 Python 3.11.0rc1。

I added:我补充说:

  • geometry . geometry so it will not resize when dragging.所以拖动时不会调整大小。
  • Canvas . Canvas You have to play around with height set to 800您必须将高度设置为 800
  • I removed bd=5 .我删除了bd=5 You can suit yourself.你可以适合自己。 Don't use quote.不要使用报价。
  • I removed Quotes for this btn1.pack(side=TOP)我删除了这个btn1.pack(side=TOP)的引号
  • At last canvas.pack() always next to mainloop()最后canvas.pack()总是在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:结果 output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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