I need to draw text right above each arc. All 6 arcs together create a full circle. The below code works perfectly when I uncomment the line draw_circle([60,60,60,60,60,59])
, but the text position gets wrong when I run the line draw_circle([120,60,60,60,30,29])
import math
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
def draw(start_angle, new_angle, text):
x = math.cos(math.radians(start_angle new_angle/2)) * 190 200
y = math.sin(math.radians(start_angle new_angle/2)) * 190 200
canvas.create_arc((20,20,380,380), activedash=(50,10), fill='lightblue', outline="white", start=start_angle, extent=new_angle, tag="pie" str(x) "_" str(y))
txt = canvas.create_text(1, 1, text=text, fill="red")
canvas.itemconfig(txt)
canvas.coords(txt, x, y)
print(f"start_angle:{start_angle}, new_angle:{new_angle}, x:{x}, y:{y}")
return txt
def draw_circle(angle_list):
start_angle=0
for new_angle in angle_list:
draw(start_angle, new_angle,str(new_angle))
start_angle =new_angle
# draw_circle([60,60,60,60,60,59])
draw_circle([120,60,60,60,30,29])
canvas.pack()
root.mainloop()
CodePudding user response:
Your issue is math related and a full circle has 360.
x = math.cos(math.radians(start_angle new_angle/2)) * 190 200
y = math.sin(math.radians(start_angle new_angle/2)) * 190 200
should be changed to this:
x = math.cos(math.radians(-(start_angle new_angle/2))) * 190 200 #minus angle
y = math.sin(math.radians(-(start_angle new_angle/2))) * 190 200 #minus angle
.
import math
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
def draw(start_angle, new_angle, text):
x = math.cos(math.radians(-(start_angle new_angle/2))) * 190 200 #minus angle
y = math.sin(math.radians(-(start_angle new_angle/2))) * 190 200 #minus angle
canvas.create_arc((20,20,380,380), activedash=(50,10), fill='lightblue', outline="white", start=start_angle, extent=new_angle, tag="pie" str(x) "_" str(y))
txt = canvas.create_text(1, 1, text=text, fill="red")
canvas.itemconfig(txt)
canvas.coords(txt, x, y)
print(f"start_angle:{start_angle}, new_angle:{new_angle}, x:{x}, y:{y}")
return txt
def draw_circle(angle_list):
start_angle=0
for new_angle in angle_list:
draw(start_angle, new_angle,str(new_angle))
start_angle =new_angle
# draw_circle([60,60,60,60,60,59])
draw_circle([120,60,60,60,30,29])
canvas.pack()
root.mainloop()
CodePudding user response:
Since the coordinate system of a canvas has a reversed y-axis, you need to minus the calculated y distance from 200 instead:
y = 200 - math.sin(math.radians(start_angle new_angle/2)) * 190