![](/img/trans.png)
[英]Python & CV2: How do i draw a line on an image with mouse then return line coordinates?
[英]How to draw a line following your mouse coordinates with tkinter?
我嘗試使用以下代碼繪制在tkinter中創建一行的點:
import tkinter as tk
from time import sleep
def myfunction(event):
x, y = event.x, event.y
x1 = (x+1)
y1 = (y+1)
canvas.create_line(x, y, x1, y1)
sleep(0.5)
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
root.bind('d', myfunction)
root.mainloop()
可以理解的是,當我按下“d”時,該程序只能說明一點。 我試過在myfunction
函數中使用循環,如下所示:
def myfunction(event):
x, y = event.x, event.y
x1 = (x+1)
y1 = (y+1)
for x in range(0,5):
canvas.create_line(x, y, x1, y1)
sleep(0.1)
但這不起作用。 我嘗試了很多其他解決方案,但似乎都沒有。
有這個問題的解決方案嗎?
首先,您必須綁定到"<Motion>"
事件,每次鼠標移動時都會觸發該事件。
然后,您需要保存以前的鼠標坐標,以便有一個從中繪制線的位置。
像這樣:
import tkinter as tk
def myfunction(event):
x, y = event.x, event.y
if canvas.old_coords:
x1, y1 = canvas.old_coords
canvas.create_line(x, y, x1, y1)
canvas.old_coords = x, y
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.old_coords = None
root.bind('<Motion>', myfunction)
root.mainloop()
基於Novel的答案,您可以進一步定義僅在按下鼠標左鍵時工作的功能,並進一步定義繪制線的功能:
import tkinter as tk
def draw(event):
x, y = event.x, event.y
if canvas.old_coords:
x1, y1 = canvas.old_coords
canvas.create_line(x, y, x1, y1)
canvas.old_coords = x, y
def draw_line(event):
if str(event.type) == 'ButtonPress':
canvas.old_coords = event.x, event.y
elif str(event.type) == 'ButtonRelease':
x, y = event.x, event.y
x1, y1 = canvas.old_coords
canvas.create_line(x, y, x1, y1)
def reset_coords(event):
canvas.old_coords = None
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.old_coords = None
root.bind('<ButtonPress-1>', draw_line)
root.bind('<ButtonRelease-1>', draw_line)
#root.bind('<B1-Motion>', draw)
#root.bind('<ButtonRelease-1>', reset_coords)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.