""" tkinter旋转多边形示例,tkinter rotate polygon example 本程序会画一个蓝色正方形,然后按住鼠标去旋转它。 """ import math from tkinter import * canvas = Canvas(width=200, height=200) # 新建画布 canvas.pack() # 坐标点 xy = [(50,50),(150,50),(150, 150),(50,150)] item = canvas.create_polygon(xy,fill='blue') center = 100, 100 def getangle(event): dx = canvas.canvasx(event.x) - center[0] dy = canvas.canvasy(event.y) - center[1] try: return complex(dx, dy)/abs(complex(dx, dy)) except ZeroDivisionError: return 0.0 def press(event): """单击左键绑定的函数""" global start start = getangle(event) def motion(event): """计算相对于初始角的角度""" global start angle = getangle(event) / start offset = complex(center[0], center[1]) newxy = [] for x, y in xy: v = angle * (complex(x, y) - offset) + offset newxy.append(v.real) newxy.append(v.imag) canvas.coords(item, *newxy) # 重新配置坐标 canvas.bind("", press) # 绑定鼠标左键单击事件 canvas.bind(" ", motion) # 绑定鼠标左键移动事件 mainloop()
李兴球
李兴球的博客是Python创意编程原创博客