本程序演示了鼠标进入,鼠标指针离开,鼠标指针移动等事件。
"""
本程序演示拖动圆点并在非圆点处通过单击创建圆点
"""
from tkinter import *
class Testclass(Frame):def __init__(self, master=None):
Frame.__init__(self, master)
Pack.config(self)
self.createWidgets()def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH)
self.draw = Canvas(self, width="5i", height="5i")
self.draw.pack(side=LEFT)Widget.bind(self.draw, "<1>", self.mouseDown)
Widget.bind(self.draw, "", self.mouseMove) def mouseDown(self, event):
# 检测鼠标指针是否在一个圆点内,如果时则把它设为tk的当前tag.
if not event.widget.find_withtag(CURRENT):
fred = self.draw.create_oval(
event.x - 10, event.y -10, event.x +10, event.y + 10,
fill="green", tags=CURRENT)self.draw.tag_bind(fred, "
", self.mouseEnter)
self.draw.tag_bind(fred, "", self.mouseLeave) self.lastx = event.x
self.lasty = event.ydef mouseMove(self, event):
"""鼠标指针移动事件"""
self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x
self.lasty = event.ydef mouseEnter(self, event):
"""鼠标指针进入则设为红色"""
self.draw.itemconfig(CURRENT, fill="red")def mouseLeave(self, event):
"""鼠标指针进入则设为蓝色"""
self.draw.itemconfig(CURRENT, fill="blue")Testclass = Testclass()
Testclass.mainloop()评论已关闭。 李兴球
李兴球的博客是Python创意编程原创博客