Nowakowski
Nowakowski

Reputation: 61

How to draw sinus wave with Tkinter?

How to create Sinus Wave using Tkinter?

I don't know how to "put" the y as the the rectangle. I want to make a loop with the rectangle.

from tkinter import *
import math

master = Tk()

w = Canvas(master, width=200, height=100)
w.pack()


x = 0
width = 200

for x in range(0, width):
    y = int(50 + 50*math.sin(4*((float(x)/width)*(2*math.pi) )))
    w.create_rectangle(1, 1, 1, 10, fill="yellow")
mainloop()

Upvotes: 4

Views: 6267

Answers (2)

user164489
user164489

Reputation: 1

The answer above helped me a lot! But in case the author wanted, as me, to have an animation of the line being drawn on the screen, then these modifications are necessary:

# plot a function like y = sin(x) with Tkinter canvas and line

from tkinter import *
import math
from time import sleep

root = Tk()
root.title("Simple plot using canvas and line")

width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor = 0.04
# height stretch
y_amplitude = 80

c = Canvas(width=width, height=height, bg='white')
c.pack()

str1 = "sin(x)=blue"
c.create_text(10, 20, anchor=SW, text=str1)

center_line = c.create_line(0, center, width, center, fill='green')

# create the coordinate list for the sin() curve, have to be integers
xy1 = [0,0,1,1]
sin_line = c.create_line(xy1, fill='blue')
# root.mainloop()
for x in range(400):
    # x coordinates
    xy1.append(x * x_increment)
    # y coordinates
    xy1.append(int(math.sin(x * x_factor) * y_amplitude) + center)
    sleep(0.05)
    c.coords(sin_line, xy1)
    root.update()

Upvotes: 0

django-renjith
django-renjith

Reputation: 4010

# plot a function like y = sin(x) with Tkinter canvas and line

from Tkinter import *
import math

root = Tk()
root.title("Simple plot using canvas and line")

width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor = 0.04
# height stretch
y_amplitude = 80

c = Canvas(width=width, height=height, bg='white')
c.pack()

str1 = "sin(x)=blue"
c.create_text(10, 20, anchor=SW, text=str1)

center_line = c.create_line(0, center, width, center, fill='green')

# create the coordinate list for the sin() curve, have to be integers
xy1 = []
for x in range(400):
    # x coordinates
    xy1.append(x * x_increment)
    # y coordinates
    xy1.append(int(math.sin(x * x_factor) * y_amplitude) + center)

sin_line = c.create_line(xy1, fill='blue')
root.mainloop()

Upvotes: 6

Related Questions