簡體   English   中英

在 Tkinter canvas 中繪制直線和拖動時出現問題

[英]Problems while drawing straight line and dragging in Tkinter canvas

所以,我試圖通過單擊“線”按鈕在 canvas 中繪制垂直線。

這些是問題和我的要求:

  1. 當我嘗試單擊繪制的線將其拖動到 position 時,它會排斥鼠標 cursor,但會朝正確的方向移動。 我該怎么做才能防止這種情況發生?
  2. 在隨后單擊“線”按鈕時,我希望繪制一條新線(每次單擊),而原始線保持在 canvas 中不動。
  3. 最新的線是唯一可以拖動的。 所有其他行應為 static。
  4. 我想要所有這些畫線的坐標。 我怎么得到這些?

這是我寫的代碼:

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()

請幫忙!!!!

使用 Python 3.11.0rc1。

我補充說:

  • geometry 所以拖動時不會調整大小。
  • Canvas 您必須將高度設置為 800
  • 我刪除了bd=5 你可以適合自己。 不要使用報價。
  • 我刪除了這個btn1.pack(side=TOP)的引號
  • 最后canvas.pack()總是在mainloop() () 旁邊

這是重新工作的代碼:

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()

結果 output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM