Code
#!/usr/bin/python3
# ==============================================================
# draw and ellipse
# ==============================================================
import graphics as gr
import coordinate_conversion as cc
import math
import sys
# --------------------------------------------------------------
# ---- create a graphics window
# --------------------------------------------------------------
def create_a_graphics_window(width:int,
height:int,
axes:bool=False,
title:str='Ellipse') -> gr.GraphWin:
'''
create graphics window and maybe Cartesian axes
'''
# ---- create window
win = gr.GraphWin(title,width,height)
win.setBackground("white")
# ---- draw axes?
if axes:
# ---- X,Y axes origin in window coordinates
xaxis = round(width/2.0)
yaxis = round(height/2.0)
# ---- draw X axis (line)
xl = gr.Line(gr.Point(0,yaxis),gr.Point(width-1,yaxis))
xl.setWidth(1)
xl.setFill("black")
xl.draw(win)
# ---- draw Y axis (line)
yl = gr.Line(gr.Point(xaxis,0),gr.Point(xaxis,height-1))
yl.setWidth(1)
yl.setFill("black")
yl.draw(win)
return win
# --------------------------------------------------------------
# ---- create a list of points (x,y) on an Ellipse
# ---- note: an ellipse is symmetrical around the origin
# ---- you only need to calculate 1/4 of them
# --------------------------------------------------------------
def create_points(a=200,b=100) -> list:
'''
create points on an ellipse
a = semi-major axis
b = semi-minor axis
'''
points = []
for x in range(0,a+1,20):
y = round(math.sqrt(abs(b**2-(b**2)*(x**2/a**2))))
points.append((x,y))
points.append((x,-y))
points.append((-x,y))
points.append((-x,-y))
print(f'{len(points)} points created')
return points
# --------------------------------------------------------------
# ---- draw points on an Ellipse
# --------------------------------------------------------------
def draw_points(win:gr.GraphWin,pts:list) -> None:
'''
draw points on an ellipse
'''
for i,pt in enumerate(pts):
x = pt[0]
y = pt[1]
##print(f'[{i:02}] x={x:3} y={y:3}')
# ---- convert point Cartesian coords to window coords
wx1,wy1 = cc.center_to_win_coords(x,y,
win.width,win.height)
# ---- draw a point (circle)
c = gr.Circle(gr.Point(wx1,wy1),4)
c.setFill('red')
c.draw(win)
return
# --------------------------------------------------------------
# ---- main
# --------------------------------------------------------------
if __name__ == '__main__':
# ---- create points
pts = create_points()
# ---- create graphics window
win = create_a_graphics_window(801,801,axes=True,
title="Ellips")
# ---- draw points
draw_points(win,pts)
# ---- wait for a mouse click in the window, then exit
click = win.getMouse()
win.close()
sys.exit()