如何从锚点旋转画布对象?

2024-04-19 04:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你看我的问题

所以我想知道你是否可以从一个锚定点旋转一个画布对象。例如,一个正方形位于0100,而锚点位于0,0,则该正方形从锚点旋转。如果你有办法做到这一点,请解释它是如何工作的,为什么,我将不胜感激


Tags: 对象画布锚定办法正方形锚点
1条回答
网友
1楼 · 发布于 2024-04-19 04:20:30

我强烈推荐马提诺的答案here

import tkinter as tk
import math
from itertools import islice

def draw_square(x,y,w,h):
    lu = (x,y)#left upper corner
    ru = (x+w,y)#right upper corner
    rb = (x+w,y+h)#right bottom corner
    lb = (x,y+h)#left bottom corner
    square = cnvs.create_polygon(lu,ru,rb,lb)
#using polygon for simple fill and getting the dots
    return square #return square_id

def pair_it(itr):#function to chunk list into x,y pairs
    itr = iter(itr)
    return iter(lambda:tuple(islice(itr,2)),())

def rotate_polygon(_id,angle):
    pns = cnvs.coords(_id)
    xy = list(pair_it(pns))
    mid_x=sum([p[0] for p in xy])/len(xy)#sumerize x and divide through len
    mid_y=sum([p[1] for p in xy])/len(xy)#sumerize y and divide through len
    # I was stealen it from martineau, since my bbox method failed
##    bbox = cnvs.bbox(square_id)
##    r1 = (bbox[2]-bbox[0])/2
##    r2 = (bbox[3]-bbox[1])/2
##    mid_x,mid_y=bbox[0]+r1,bbox[1]+r2
##    worked for an amount of rotations but messed up till it got stable again
    radians=angle*math.pi/180
    new_coords = []
    for edge in xy:
        edx,edy = edge[0]-mid_x,edge[1]-mid_y#here it "translates the surface" to mid point
        x = edx*math.cos(radians)-edy*math.sin(radians)+mid_x#here we translate back
        y = edx*math.sin(radians)+edy*math.cos(radians)+mid_y#here we translate back
        new_coords.extend((x,y))
    cnvs.coords(_id,new_coords)
    root.after(1,rotate_polygon,_id,angle)

root = tk.Tk()
cnvs = tk.Canvas(root)
square_I = draw_square(150,50, 100,200)
cnvs.itemconfig(square_I, fill='red')
root.bind('<Button-1>',lambda e:rotate_polygon(square_I,20))
cnvs.pack()

root.mainloop()

相关问题 更多 >