2013-09-25 35 views
0

我想用鼠標點擊刪除在Tkinter/Python上繪製的一條線。如何使用鼠標在Python中單擊刪除以前繪製的線?

此代碼繪製線對象,然後立即將其刪除:

#!/usr/bin/python 
from Tkinter import * 

master = Tk() 
w = Canvas(master, width=200, height=200) 
w.pack() 
i=w.create_line(0, 0, 100, 100) 
w.delete(i) 

mainloop() 

什麼會的代碼是做鼠標點擊了刪除線(左或右按鈕並不重要)?

謝謝。

回答

0
from Tkinter import * 
import math 

master = Tk() 
w = Canvas(master, width=200, height=200) 
w.pack() 
x1=0 
y1=0 
x2=100 
y2=100 
delta=10 
i=w.create_line(x1, y1, x2, y2) 

def click(event): 
# event.x is the x coordinate and event.y is the y coordinate of the mouse 
    D = math.fabs((event.y-event.x))/math.sqrt(2)  
    if D < delta and x1 - delta < event.x < x2 + delta: 
      w.delete(i)  
w.bind("<Button-1>", click) 

mainloop() 
1

這將做到這一點:

from Tkinter import * 

master = Tk() 
w = Canvas(master, width=200, height=200) 
w.pack() 
i=w.create_line(0, 0, 100, 100) 

# Bind the mouse click to the delete command 
w.bind("<Button-1>", lambda e: w.delete(i)) 

mainloop() 

編輯迴應評論

是,上述方案將在窗口中的任意註冊一個鼠標點擊。如果您希望它只在點擊接近它時刪除該行,則需要更復雜的內容。也就是說,這樣的事情:

from Tkinter import * 

master = Tk() 
w = Canvas(master, width=200, height=200) 
w.pack() 
i=w.create_line(0, 0, 100, 100) 

def click(event): 
    # event.x is the x coordinate and event.y is the y coordinate of the mouse 
    if 80 < event.x < 120 and 80 < event.y < 120: 
     w.delete(i) 

w.bind("<Button-1>", click) 

mainloop() 

只有當鼠標點擊的xy座標withing線20分這個腳本會刪除該行。

請注意,我不能完全設置此。你將不得不根據你的需要調整它。

+0

我注意到,當鼠標指針離線很遠(一英寸左右)時,這也會刪除線。當指針靠近它時,有沒有辦法刪除這一行? – Platypus

+0

@Platypus - 您可以獲取鼠標單擊的x和y座標,然後僅當它們位於該行的特定距離內時才刪除該行。看我的編輯。 – iCodez

+0

不幸的是,這隻能在靠近行尾的方形區域內工作。 20點區域並不沿線。我認爲必須有一個線性方程式編程入其中。 – Platypus

相關問題