Matteo Secco
Matteo Secco

Reputation: 633

Tkinter: Draw a circle on a canvas without create_oval

I want to draw point by point a circle so without canvas.create_oval() but using the formula x^2 + y^2 = r. The circle also has to be drawn inside of a square.

This is the code:

center = (maxx - ((maxx - minx) / 2), maxy - ((maxy - miny) / 2))
radius = ((maxx - minx) / 2 + (maxy - miny) / 2) / 2

for xc in range(0, x):
    for yc in range(0, y):
        if radius - 10 <= (xc - center[0]) ** 2 + (yc - center[1]) ** 2 <= radius + 10:
            canvas.create_oval(xc + 50, yc + 50, xc + 50, yc + 50)

The problem is that the circle that came out is completely different from what I expected. (Don't care about the hand drawn circle.

x = 400, y = 300, minx = 103, maxx = 269, miny = 62, maxy = 212, center = (186.0, 137.0), radius = 79.0

photo

As you can see the circle is really smaller and the center is not where I want? What am I doing wrong??

Upvotes: 2

Views: 2201

Answers (1)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

We had a good discussion where I questioned all the inputs, but the input wasn't the problem.

Sadly, it took us this long to realize the issue was the formula.

It's not r = x^2 + y^2, it's r^2 = x^2 + y^2.

The appropriate loop would look like this:

r_squared = radius * radius
for xc in range(0, x):
    for yc in range(0, y):
       if r_squared - 10 <= (xc - center[0]) ** 2 + (yc - center[1]) ** 2 <= r_squared + 10:
           canvas.create_oval(xc, yc, xc, yc)

Upvotes: 1

Related Questions