create_line() 需要两个点的坐标,若线段的一个端点作定点,另一个端点作某种运动,写两个点的坐标比较麻烦。如下图自定义一个画直线函数,以角度和长度为变量来作图相对要方便一些:
代码如下: 同样的时间间隔,看上去 Line1()会比Line2() “转得”快2倍,角速度前者是后者的2倍。
import tkinter as tk import pyautogui as ag import random from time import sleep as Delay 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 Line1(x,y,d,rad=0,c='black'): "x,y 起始点坐标,d=长度,rad=与水平线夹角" coord = x,y,x + d * cos(pi*rad/180),y - d * sin(pi*rad/180) tCanvas.create_line(coord,fill=c) def Line2(x,y,r,rad=0,c='black'): "x,y 线段中点坐标,r=半长,rad=与水平线夹角" coord = (x + r * cos(pi*rad/180),y - r * sin(pi*rad/180), x - r * cos(pi*rad/180),y + r * sin(pi*rad/180)) tCanvas.create_line(coord,fill=c) if __name__ == '__main__': win = tk.Tk() Window_Open(480,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'] for i in range(20): for r in range(0,360): c = random.choice(Color) Line1(240,240,200,r,c) tCanvas.update() Delay(0.05) Delay(2) for i in range(20): for r in range(0,180): c = random.choice(Color) Line2(240,240,200,r,c) tCanvas.update() Delay(0.05) win.mainloop()
效果图: