python中tkinter鼠标事件_在Tkinter中使用鼠标事件绘制矩形

该示例展示了如何在Python的Tkinter中使用鼠标事件实现实时绘制矩形。当鼠标按下时开始绘制,随着鼠标移动矩形会随之扩展,松开鼠标后矩形固定。代码中包含了一个简单的应用程序,用户可以在图片上拖动鼠标来绘制黑色矩形。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is with respect to Draw rectangle on mouse click [Python]. I tried out the first solution and it works perfectly. Can someone please tell me, what to do if I want to see the rectangle being drawn and the rectangle gets fixed once the mouse button is released as I can only see the drawn rectangle once the button is released.

Any kind of help will be appreciated.

解决方案

I amended the code from the referenced question. Now it shows the rectangle when mouse is being dragged on the canvas. The canvas displays Lena image.

import tkinter as tk # this is in python 3.4. For python 2.x import Tkinter

from PIL import Image, ImageTk

class ExampleApp(tk.Tk):

def __init__(self):

tk.Tk.__init__(self)

self.x = self.y = 0

self.canvas = tk.Canvas(self, width=512, height=512, cursor="cross")

self.canvas.pack(side="top", fill="both", expand=True)

self.canvas.bind("", self.on_button_press)

self.canvas.bind("", self.on_move_press)

self.canvas.bind("", self.on_button_release)

self.rect = None

self.start_x = None

self.start_y = None

self._draw_image()

def _draw_image(self):

self.im = Image.open('./resource/lena.jpg')

self.tk_im = ImageTk.PhotoImage(self.im)

self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)

def on_button_press(self, event):

# save mouse drag start position

self.start_x = event.x

self.start_y = event.y

# create rectangle if not yet exist

#if not self.rect:

self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, fill="black")

def on_move_press(self, event):

curX, curY = (event.x, event.y)

# expand rectangle as you drag the mouse

self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)

def on_button_release(self, event):

pass

if __name__ == "__main__":

app = ExampleApp()

app.mainloop()

The black square is drawn on top of the image. Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值