Search code examples
pythontkinter

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()

Solution

  • # 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()