[英]Real time drawing with mouse in Tkinter
我很喜欢在 Tkinter 中绘图,但只有松开鼠标按钮才能看到形状。 拖动鼠标时如何查看形状? 我使用下面的代码已经完成了一半,但是如果你运行它,你会看到它不会更新以删除由运动 function 制作的每个绘图。
from tkinter import *
window = Tk()
canvas = Canvas(bg='black')
canvas.pack()
def locate_xy(event):
global current_x, current_y
current_x, current_y = event.x, event.y
def draw_circle(event):
global current_x, current_y
canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
current_x, current_y = event.x, event.y
def update_circle(event):
global current_x, current_y
canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
canvas.bind('<ButtonPress-1>', locate_xy)
canvas.bind('<ButtonRelease-1>', draw_circle)
canvas.bind('<B1-Motion>', update_circle)
window.mainloop()
您只需要在locate_xy()
内创建椭圆并在update_circle()
内更新其坐标。 <ButtonRelease-1>
的绑定不是必须的:
def locate_xy(event):
global current_x, current_y, current_item
current_x, current_y = event.x, event.y
# create the oval item and save its ID
current_item = canvas.create_oval((current_x, current_y, event.x, event.y), outline='white')
def update_circle(event):
# update coords of the oval item
canvas.coords(current_item, (current_x, current_y, event.x, event.y))
canvas.bind('<ButtonPress-1>', locate_xy)
canvas.bind('<B1-Motion>', update_circle)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.