How to label each circle you draw when using the method create_oval()
from module tkinter in Python?
CodePudding user response:
You have to do it manually, by creating a separate canvas text object.
Here's an example that places the text in the center of the circle:
import tkinter as tk
WIDTH, HEIGHT = 200, 200
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
x0, y0, x1, y1 = 50, 50, 100, 100
canvas.create_oval(x0, y0, x1, y1, outline='black')
center_x, center_y = (x0 x1)/2, (y0 y1)/2
canvas.create_text(center_x, center_y, text='Label')
root.mainloop()
Result:
CodePudding user response:
There is no built in way to do this, but you can use the canvas.coords
of the circle to position a label:
Here is how to do it for the top left and bottom right corners. With a little bit more manipulation of the coordinates, you could position the label at the other corners, inside the circle, above, or under it, or left & right.
import tkinter as tk
if __name__ == '__main__':
root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200, bg='cyan')
canvas.pack()
x0, y0, x1, y1 = 25, 25, 75, 75
circle_A = canvas.create_oval(x0, y0, x1, y1)
canvas.create_text(canvas.coords(circle_A)[:2], text='A')
x0, y0, x1, y1 = 125, 125, 175, 175
circle_B = canvas.create_oval(x0, y0, x1, y1)
canvas.create_text(canvas.coords(circle_B)[2:], text='B')
root.mainloop()