如何删除在 tkinter 中绘制的尾随对象?
How do I delete trailing objects drawn in tkinter?
我的目标是允许您在屏幕上制作一个类似于在绘画中使用矩形或选择工具的矩形。我已经让它大部分工作了,但是当你通过按住左键单击并向外移动鼠标然后向内移动鼠标来制作一个矩形时,同时仍然按住按钮,它会留下之前绘制的矩形。
Alternate example when I move my mouse everywhere really fast.
import tkinter as tk
import pyautogui
def draw_rect(event, canvas, pos):
x, y = pos
rectangle = canvas.create_rectangle(
x, y, event.x, event.y, outline="yellow", width=3, fill="blue"
)
def draw_canvas(event, root, pos):
canvas = tk.Canvas(root, bg="red")
canvas.pack(fill=tk.BOTH, expand=True)
root.bind("<B1-Motion>", lambda event: draw_rect(event, canvas, pos))
与其连续绘制和删除矩形,不如绘制一个矩形,然后在拖动时修改其坐标。
这是一个简单的例子:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, bg="black", width=400, height=400)
canvas.pack(fill="both", expand=True)
def draw_drag(event):
canvas = event.widget
new_x = canvas.canvasx(event.x)
new_y = canvas.canvasy(event.y)
x0, y0, x1, y1 = canvas.coords("current_rect")
canvas.coords("current_rect", x0, y0, new_x, new_y)
def draw_stop(event):
canvas.dtag("current_rect")
def draw_start(event):
canvas = event.widget
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
canvas.create_rectangle(x, y, x, y, fill="red", tags=("current_rect",))
canvas.bind("<ButtonPress-1>", draw_start)
canvas.bind("<ButtonRelease-1>", draw_stop)
canvas.bind("<B1-Motion>", draw_drag)
root.mainloop()
我的目标是允许您在屏幕上制作一个类似于在绘画中使用矩形或选择工具的矩形。我已经让它大部分工作了,但是当你通过按住左键单击并向外移动鼠标然后向内移动鼠标来制作一个矩形时,同时仍然按住按钮,它会留下之前绘制的矩形。
Alternate example when I move my mouse everywhere really fast.
import tkinter as tk
import pyautogui
def draw_rect(event, canvas, pos):
x, y = pos
rectangle = canvas.create_rectangle(
x, y, event.x, event.y, outline="yellow", width=3, fill="blue"
)
def draw_canvas(event, root, pos):
canvas = tk.Canvas(root, bg="red")
canvas.pack(fill=tk.BOTH, expand=True)
root.bind("<B1-Motion>", lambda event: draw_rect(event, canvas, pos))
与其连续绘制和删除矩形,不如绘制一个矩形,然后在拖动时修改其坐标。
这是一个简单的例子:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, bg="black", width=400, height=400)
canvas.pack(fill="both", expand=True)
def draw_drag(event):
canvas = event.widget
new_x = canvas.canvasx(event.x)
new_y = canvas.canvasy(event.y)
x0, y0, x1, y1 = canvas.coords("current_rect")
canvas.coords("current_rect", x0, y0, new_x, new_y)
def draw_stop(event):
canvas.dtag("current_rect")
def draw_start(event):
canvas = event.widget
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
canvas.create_rectangle(x, y, x, y, fill="red", tags=("current_rect",))
canvas.bind("<ButtonPress-1>", draw_start)
canvas.bind("<ButtonRelease-1>", draw_stop)
canvas.bind("<B1-Motion>", draw_drag)
root.mainloop()