如何在点击事件Tkinter Python上绘制画布上的点

时间:2017-10-27 13:15:35

标签: python-3.x canvas tkinter tkinter-canvas

我有以下代码片段在画布中拍摄图像,然后每当我点击绘画功能时在它上面画一个点。

除了之外,所有内容都正常工作,因为paint函数没有按预期工作。

理想的输出

Click事件绘制一个点。无需拖动点击事件

实际输出

我必须拖动鼠标单击事件以在画布上查看图形。

我猜涂料功能可能会有轻微问题。但是,我还没知道它究竟是什么。

from tkinter import *
from PIL import Image, ImageTk


class Main(object):

    def __init__(self):
        self.canvas = None

    def main(self):
        master = Tk()

        # Right side of the screen / image holder
        right_frame = Frame(master, width=500, height=500, cursor="dot")
        right_frame.pack(side=LEFT)

        # Retrieve image
        image = Image.open("./image/demo.JPG")
        image = image.resize((800, 700), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)

        # Create canvas
        self.canvas = Canvas(right_frame, width=800, height=700)
        self.canvas.create_image(0, 0, image=photo, anchor="nw")
        self.canvas.pack()
        self.canvas.bind("<B1-Motion>", self.paint)

        mainloop()

    def paint(self, event):
        python_green = "#476042"
        x1, y1 = (event.x - 1), (event.y - 1)
        x2, y2 = (event.x + 1), (event.y + 1)
        self.canvas.create_oval(x1, y1, x2, y2, fill=python_green, outline=python_green, width=10)


if __name__ == "__main__":
    Main().main()

修正:

添加了以下两种方法:

def on_button_press(self, event):
    self.x = event.x
    self.y = event.y

def on_button_release(self, event):
    python_green = "#476042"
    x0,y0 = (self.x, self.y)
    x1,y1 = (event.x, event.y)

将画布改为:

self.canvas.bind("<ButtonPress-1>", self.on_button_press)
self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

1 个答案:

答案 0 :(得分:3)

当您只点击并且不移动鼠标时,B1-Motion不会触发。

要绑定鼠标按下(以及鼠标移动),您可以在self.canvas.bind("<ButtonPress-1>", self.paint)之前添加mainloop