import tkinter as tkimport mathmy_w = tk.Tk()width,height=410,210 # set the variables c_width,c_height=width-10,height-10 # canvas width heightd=str(width)+"x"+str(height)my_w.geometry(d)
c1 = tk.Canvas(my_w, width=c_width, height=c_height,bg='lightgreen')c1.grid(row=0,column=0,padx=5,pady=5,columnspan=3)
speed=10 # in milliseconds, delay timmer, drawing speed
x1,y1=5,int(c_height/2)h=y1-10 # gap from curve top to canvas edge in_degree=0 # starting angle
def my_draw(): global in_degree,x1,y1 in_degree=in_degree+1 in_redian = math.radians(in_degree) y2=y1-h*math.sin(in_redian) #y2=(h+10)-h*math.cos(in_redian) l1=c1.create_line(x1, y1, x1,y2,fill='red',width=1) if (x1<width-10): # check the right edge x1=x1+1 c1.after(speed,my_draw) else: return
my_draw()
my_w.mainloop()
Drawing along the curve
We can draw the curve by shifting the x1,y1 value to x2,y2 value.
import tkinter as tkimport mathmy_w = tk.Tk()width,height=410,210 # set the variables c_width,c_height=width-10,height-10 # canvas width heightd=str(width)+"x"+str(height)my_w.geometry(d) c1 = tk.Canvas(my_w, width=c_width, height=c_height,bg='lightgreen')c1.grid(row=0,column=0,padx=5,pady=5,columnspan=3)speed=10 # in milliseconds, delay timmer x1,y1=5,int(c_height/2)h=y1-10 # gap between canvas top edge and curve top c1.create_line(x1,y1,c_width-5,y1,arrow='last') # x Axis c1.create_line(x1,y1,x1,10,arrow='last') # Y Axis
in_degree=0 # starting angle def my_draw(): global in_degree,x1,y1 in_degree=in_degree+1 in_redian = math.radians(in_degree) y2=(h+10)-h*math.sin(in_redian) # sin curve #y2=(h+10)-h*math.cos(in_redian) # cos curve x2=x1+0.5 # increasing x value l1=c1.create_line(x1, y1, x2,y2,fill='red',width=2) if (x2<c_width-5): # check the right edge x1,y1=x2,y2 c1.after(speed,my_draw) else: return my_draw()my_w.mainloop()
By changing this line we can get sin curve
y2=(h+10)-h*math.sin(in_redian) # sin curve #y2=(h+10)-h*math.cos(in_redian) # cos curve
Both sin and cos curves in same canvas
import tkinter as tk
import math
my_w = tk.Tk()
width,height=410,210 # set the variables c_width,c_height=width-10,height-10 # canvas width heightd=str(width)+"x"+str(height)my_w.geometry(d)
c1 = tk.Canvas(my_w, width=c_width, height=c_height,bg='lightgreen')c1.grid(row=0,column=0,padx=5,pady=5,columnspan=3)
speed=10 # in milliseconds, delay timmer x1,z1,y1=5,5,int(c_height/2)h=y1-10 # gap from curve top to canvas edge
c1.create_line(x1,y1,c_width-5,y1,arrow='last') # x Axis
c1.create_line(x1,y1,x1,5,arrow='last') # Y Axis in_degree=0def my_draw(): global in_degree,x1,y1,z1 in_degree=in_degree+1 in_redian = math.radians(in_degree) y2=(h+10)-h*math.cos(in_redian) # cos curve z2=(h+10)-h*math.sin(in_redian) # sin curve x2=x1+0.5 # X axis steps l1=c1.create_line(x1, y1, x2,y2,fill='red',width=1) l2=c1.create_line(x1, z1, x2,z2,fill='blue',width=1) if (x2<c_width-10): # check the right edge x1=x2 y1=y2 z1=z2 c1.after(speed,my_draw) else: return my_draw()
my_w.mainloop()