Логика в моем коде не абсолютна. Я пытался найти координаты центра и радиус ограничивающего круга, взяв конечные точки диаметра как 1) точку, наиболее удаленную от начала координат, и 2) точку, наиболее удаленную от (1).
Но это не дает мне фактический результат во всех случаях.
Пожалуйста, не обращайте внимания на отступы (я использую табуляции и скопировал свой код.)
from tkinter import *
class point2D:
def __init__(self, x=0, y=0):
self.__x = x
self.__y = y
def x(self):
return self.__x
def y(self):
return self.__y
def setx(self, x):
self.__x = x
def sety(self, y):
self.__y = y
def __str__(self):
return f"({self.__x}, {self.__y})"
def distance(self, other):
return ((self.__x-other.__x)**2 + (self.__y-other.__y)**2) ** 0.5
class box:
def __init__(self):
root = Tk()
root.title("Bounding Circle")
width, height = 600, 600
root.geometry(f"{width}x{height}")
self.canvas = Canvas(root, width=width, height=height, bg="white")
self.canvas.pack()
self.canvas.bind("", self.addpoint)
self.origin = point2D()
self.points = []
root.mainloop()
def addpoint(self, event):
radius = 5
self.canvas.create_oval(event.x - radius, event.y - radius,
event.x + radius, event.y + radius, fill = "black")
self.points.append(point2D(event.x, event.y))
self.getboundingcircle()
def getboundingcircle(self):
if len(self.points) == (1 or 0):
return
#Finding the point farthest from origin (0,0 in canvas)
d, start = self.points[0].distance(self.origin), 0
for i in range(1, len(self.points)):
x = self.points.distance(self.origin)
if x > d:
d = x
start = i
#Finding the point farthest from points[start]
d, end = 0, 0
for i in range(len(self.points)):
if i == start:
continue
x = self.points.distance(self.points[start])
if x > d:
d = x
end = i
center_x = (self.points[start].x() + self. points[end].x()) / 2
center_y = (self.points[start].y() + self. points[end].y()) / 2
radius = self.points[start].distance(self.points[end]) / 2
self.canvas.delete("circle")
self.canvas.create_oval(center_x - radius, center_y - radius,
center_x + radius, center_y + radius, outline = "red", tags = "circle")
box()
Подробнее здесь: https://stackoverflow.com/questions/790 ... ing-circle