【问题标题】:Real time drawing with mouse in Tkinter在 Tkinter 中使用鼠标实时绘图
【发布时间】:2022-01-22 11:34:51
【问题描述】:

我对在 Tkinter 中绘图相当满意,但只有松开鼠标按钮后才能看到形状。拖动鼠标时如何查看形状?下面的代码我已经完成了一半,但如果你运行它,你会看到它不会更新以删除运动功能制作的每张图。

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

【问题讨论】:

    标签: python tkinter canvas


    【解决方案1】:

    您只需要在locate_xy() 内创建椭圆并在update_circle() 内更新其坐标。不需要绑定&lt;ButtonRelease-1&gt;

    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)
    

    【讨论】:

    • 谢谢!这正是我想要的。
    【解决方案2】:

    您已经在通过事件&lt;B1-Motion&gt; 按下左键来跟踪鼠标移动,因此只需在此处添加绘图:

    from tkinter import *
    
    window = Tk()
    
    canvas = Canvas(bg='black')
    canvas.pack()
    
    def draw_line(event):
        x, y = event.x, event.y
        canvas.create_oval((x-2, y-2, x+2, y+2), outline='white')
    
    canvas.bind('<B1-Motion>', draw_line)
    
    window.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-29
      • 2014-07-30
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多