canvas.create_rectangle() 只能画水平放置的矩形,旋转任意角度的矩形只能用 tCanvas.create_polygon() 来达成,如下图:
旋转方式一:以左下角为定点,逆时针旋转a角度;
旋转方式二:以中心点为定点,逆时针旋转a角度;
以正方形为例, 画好坐标轴计算好各顶点坐标;
(若要旋转矩形,边长变量从一个变成长和宽两个,坐标重新计算)
计算好坐标后就可用create_polygon()写自定义函数,源代码如下:
import tkinter as tk import pyautogui as ag import random from time import sleep as Delay from math import sqrt from math import sin from math import cos from math import pi def Window_Open(W, H): X, Y = ag.size() winSize = str(W)+"x"+str(H) winPos = winSize + "+" + str((X - W) // 2) winPos += "+" + str((Y - H) // 2) win.geometry(winPos) win.resizable(False, False) title = u'桌面分辨率:' + str(X) + "x" + str(Y) title += ' ' * 5 + u'窗体大小:' + winSize win.title(title) win.update() def Rect1(x,y,w,rad=0,c='black'): "x,y 左下角坐标,w=边长,rad=底边与水平线的夹角" a=pi*rad/180 coord = (x,y,x + w * cos(a),y - w * sin(a), x + w * (cos(a)-sin(a)), y - w * (cos(a)+sin(a)), x - w * sin(a), y - w * cos(a)) tCanvas.create_polygon(coord,fill=c) def Rect2(x,y,w,rad=45,c='black'): "x,y 中心坐标,w=半长,rad=对角线与坐标轴的夹角" a=pi*rad/180 coord = (x - w * sin(a)/sqrt(2),y - w * cos(a)/sqrt(2), x + w * cos(a)/sqrt(2),y - w * sin(a)/sqrt(2), x + w * sin(a)/sqrt(2),y + w * cos(a)/sqrt(2), x - w * cos(a)/sqrt(2),y + w * sin(a)/sqrt(2)) tCanvas.create_polygon(coord,fill=c) if __name__ == '__main__': win = tk.Tk() Window_Open(800,480) tCanvas = tk.Canvas(win, width=win.winfo_width(), height=480, bg='white') tCanvas.pack(side="top") Color = ['red','blue','green','magenta','navy','lawngreen','orange'] w=50 for r in range(0,1171,5): c = random.choice(Color) Rect1(180,240,w,r,c) tCanvas.update() w *= 1.004 Delay(0.001) Delay(1) w=280 for r in range(45,1216,5): c = random.choice(Color) Rect2(580,240,w,r,c) tCanvas.update() w *= 0.99 Delay(0.001) win.mainloop()
效果图: (单步旋转角度为逆时针5度,例一边长逐渐变长;例二边长逐渐变短)