Creating a comprehensive program as described involves several steps, including GUI design, drawing graphics, handling user interactions, and managing data structures for lines and intersection points. Below is a complete Python program using the Tkinter library that fulfills your requirements. Additionally, it uses the Pillow library to handle image saving.
Prerequisites
Before running the program, ensure you have the following Python libraries installed:
pip install pillow
Complete Python Program
import tkinter as tk
from tkinter import messagebox, filedialog
import math
from PIL import Image, ImageDraw, ImageGrab
import os
class CircleDrawer:
def __init__(self, root):
self.root = root
self.root.title("Circle Drawer")
# Initialize variables
self.num_points = 0
self.points = {} # point_num: (x, y)
self.lines = set() # set of frozensets
self.intersections = {} # (x, y): intersection_num
self.intersection_list = []
self.current_clicks = []
self.intersection_counter = 1
# Create UI elements
self.create_widgets()
def create_widgets(self):
control_frame = tk.Frame(self.root)
control_frame.pack(side=tk.TOP, pady=10)
# Input for number of points
tk.Label(control_frame, text="Number of Points (1-36):").grid(row=0, column=0, padx=5)
self.num_entry = tk.Entry(control_frame, width=5)
self.num_entry.grid(row=0, column=1, padx=5)
self.num_entry.insert(0, "12") # default value
self.draw_circle_button = tk.Button(control_frame, text="Draw Circle", command=self.draw_circle)
self.draw_circle_button.grid(row=0, column=2, padx=5)
# Input for lines
tk.Label(control_frame, text="Enter Pairs (e.g., (2,8),(2,9)):").grid(row=1, column=0, padx=5)
self.pair_entry = tk.Entry(control_frame, width=30)
self.pair_entry.grid(row=1, column=1, columnspan=2, padx=5)
self.draw_lines_button = tk.Button(control_frame, text="Draw Lines", command=self.draw_lines_from_input)
self.draw_lines_button.grid(row=1, column=3, padx=5)
# Canvas for drawing
self.canvas_size = 600
self.canvas = tk.Canvas(self.root, width=self.canvas_size, height=self.canvas_size, bg="white")
self.canvas.pack(pady=10)
self.canvas.bind("<Button-1>", self.canvas_click)
# Lists for lines and intersections
lists_frame = tk.Frame(self.root)
lists_frame.pack(side=tk.LEFT, padx=10, pady=10)
tk.Label(lists_frame, text="Lines:").pack()
self.lines_text = tk.Text(lists_frame, width=30, height=10)
self.lines_text.pack()
tk.Label(lists_frame, text="Intersections:").pack(pady=(10,0))
self.intersections_text = tk.Text(lists_frame, width=30, height=10)
self.intersections_text.pack()
# Control buttons
buttons_frame = tk.Frame(self.root)
buttons_frame.pack(side=tk.RIGHT, padx=10, pady=10)
self.back_button = tk.Button(buttons_frame, text="Back", command=self.back)
self.back_button.pack(fill=tk.X, pady=5)
self.save_button = tk.Button(buttons_frame, text="Save", command=self.save_images)
self.save_button.pack(fill=tk.X, pady=5)
self.clear_button = tk.Button(buttons_frame, text="Clear", command=self.clear_all)
self.clear_button.pack(fill=tk.X, pady=5)
def draw_circle(self):
try:
n = int(self.num_entry.get())
if not 1 <= n <= 36:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter an integer between 1 and 36.")
return
self.num_points = n
self.points = {}
self.lines = set()
self.intersections = {}
self.intersection_list = []
self.intersection_counter = 1
self.current_clicks = []
self.lines_text.delete(1.0, tk.END)
self.intersections_text.delete(1.0, tk.END)
self.canvas.delete("all")
center = self.canvas_size / 2
radius = self.canvas_size * 0.4
angle_gap = 2 * math.pi / n
for i in range(n):
angle = -math.pi / 2 + i * angle_gap # Start from top
x = center + radius * math.cos(angle)
y = center + radius * math.sin(angle)
point_num = i + 1
self.points[point_num] = (x, y)
# Draw point
r = 5
self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}")
# Draw label
self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}")
# Draw the main circle
self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black")
def parse_pairs(self, input_text):
import re
pattern = r'\(\s*(\d+)\s*,\s*(\d+)\s*\)'
matches = re.findall(pattern, input_text)
pairs = []
for match in matches:
a, b = int(match[0]), int(match[1])
if a != b and a in self.points and b in self.points:
pair = frozenset([a, b])
pairs.append(pair)
return pairs
def draw_lines_from_input(self):
input_text = self.pair_entry.get()
pairs = self.parse_pairs(input_text)
for pair in pairs:
if pair not in self.lines:
self.lines.add(pair)
self.draw_line(pair)
self.update_lines_text()
def draw_line(self, pair):
a, b = sorted(pair)
x1, y1 = self.points[a]
x2, y2 = self.points[b]
line = self.canvas.create_line(x1, y1, x2, y2, fill="red")
# Check for intersections
self.check_intersections(a, b)
def update_lines_text(self):
self.lines_text.delete(1.0, tk.END)
for pair in sorted(self.lines, key=lambda x: sorted(x)):
a, b = sorted(pair)
self.lines_text.insert(tk.END, f"({a}, {b})\n")
def canvas_click(self, event):
if self.num_points == 0:
return
clicked_point = self.get_clicked_point(event.x, event.y)
if clicked_point is None:
return
if clicked_point in self.current_clicks:
return # Ignore multiple clicks on the same point
self.current_clicks.append(clicked_point)
self.highlight_point(clicked_point)
if len(self.current_clicks) == 2:
pair = frozenset(self.current_clicks)
if pair not in self.lines:
self.lines.add(pair)
self.draw_line(pair)
self.update_lines_text()
self.unhighlight_points()
self.current_clicks = []
def get_clicked_point(self, x, y):
for point_num, (px, py) in self.points.items():
if math.hypot(px - x, py - y) <= 10:
return point_num
return None
def highlight_point(self, point_num):
x, y = self.points[point_num]
r = 8
self.canvas.create_oval(x - r, y - r, x + r, y + r, outline="green", width=2, tags="highlight")
def unhighlight_points(self):
self.canvas.delete("highlight")
def back(self):
if not self.lines:
return
last_line = sorted(self.lines)[-1]
self.lines.remove(frozenset(last_line))
self.redraw_canvas()
self.update_lines_text()
self.update_intersections()
def clear_all(self):
self.lines.clear()
self.intersections.clear()
self.intersection_list.clear()
self.intersection_counter = 1
self.current_clicks = []
self.lines_text.delete(1.0, tk.END)
self.intersections_text.delete(1.0, tk.END)
self.redraw_canvas()
def redraw_canvas(self):
self.canvas.delete("all")
center = self.canvas_size / 2
radius = self.canvas_size * 0.4
angle_gap = 2 * math.pi / self.num_points
for i in range(self.num_points):
angle = -math.pi / 2 + i * angle_gap # Start from top
x = center + radius * math.cos(angle)
y = center + radius * math.sin(angle)
point_num = i + 1
self.points[point_num] = (x, y)
# Draw point
r = 5
self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}")
# Draw label
self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}")
# Draw the main circle
self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black")
# Redraw lines
for pair in self.lines:
a, b = sorted(pair)
x1, y1 = self.points[a]
x2, y2 = self.points[b]
self.canvas.create_line(x1, y1, x2, y2, fill="red")
# Redraw intersections
for (x, y), num in self.intersections.items():
self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple")
self.canvas.create_text(x + 6, y, text=str(num), fill="purple")
def check_intersections(self, a, b):
new_line = (self.points[a], self.points[b])
for existing_pair in self.lines:
if existing_pair == frozenset([a, b]):
continue
c, d = sorted(existing_pair)
existing_line = (self.points[c], self.points[d])
intersect_point = self.get_line_intersection(new_line, existing_line)
if intersect_point:
x, y = intersect_point
# Check if intersection is at endpoints
if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]):
if (x, y) not in self.intersections:
self.intersections[(x, y)] = self.intersection_counter
self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Lines ({a},{b}) & ({c},{d})\n")
self.intersection_counter += 1
# Draw intersection
self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple")
self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple")
def get_line_intersection(self, line1, line2):
(x1, y1), (x2, y2) = line1
(x3, y3), (x4, y4) = line2
# Calculate denominators
denom = (x1 - x2)*(y3 - y4) - (y1 - y2)*(x3 - x4)
if denom == 0:
return None # Parallel or coincident
# Calculate intersection point
Px = ((x1*y2 - y1*x2)*(x3 - x4) - (x1 - x2)*(x3*y4 - y3*x4)) / denom
Py = ((x1*y2 - y1*x2)*(y3 - y4) - (y1 - y2)*(x3*y4 - y3*x4)) / denom
# Check if the intersection point is within both line segments
if self.point_on_segment(Px, Py, line1) and self.point_on_segment(Px, Py, line2):
return (Px, Py)
else:
return None
def point_on_segment(self, x, y, segment):
(x1, y1), (x2, y2) = segment
return (min(x1, x2) - 1e-6 <= x <= max(x1, x2) + 1e-6) and (min(y1, y2) - 1e-6 <= y <= max(y1, y2) + 1e-6)
def update_intersections(self):
# Recompute intersections
self.intersections.clear()
self.intersections_text.delete(1.0, tk.END)
self.intersection_counter = 1
lines = list(self.lines)
for i in range(len(lines)):
for j in range(i+1, len(lines)):
pair1 = lines[i]
pair2 = lines[j]
a, b = sorted(pair1)
c, d = sorted(pair2)
if len(pair1.intersection(pair2)) > 0:
continue # Lines share a common point
intersect_point = self.get_line_intersection((self.points[a], self.points[b]), (self.points[c], self.points[d]))
if intersect_point:
x, y = intersect_point
if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]):
if (x, y) not in self.intersections:
self.intersections[(x, y)] = self.intersection_counter
self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Lines ({a},{b}) & ({c},{d})\n")
self.intersection_counter += 1
self.redraw_canvas()
def is_at_endpoint(self, x, y, points):
for px, py in points:
if math.isclose(px, x, abs_tol=1e-6) and math.isclose(py, y, abs_tol=1e-6):
return True
return False
def save_images(self):
if self.num_points == 0:
messagebox.showerror("Error", "Please draw a circle first.")
return
# Ask for save directory
directory = filedialog.askdirectory()
if not directory:
return
# Save first image with labels and intersections
ps_file = os.path.join(directory, "circle_with_labels.ps")
self.canvas.postscript(file=ps_file, colormode='color')
img1 = Image.open(ps_file)
img1.save(os.path.join(directory, "circle_with_labels.png"), "png")
os.remove(ps_file)
# Save second image without labels and intersections
temp_canvas = tk.Canvas(self.root, width=self.canvas_size, height=self.canvas_size, bg="white")
temp_canvas.pack_forget()
# Draw only the circle and lines
center = self.canvas_size / 2
radius = self.canvas_size * 0.4
temp_canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black")
for pair in self.lines:
a, b = sorted(pair)
x1, y1 = self.points[a]
x2, y2 = self.points[b]
temp_canvas.create_line(x1, y1, x2, y2, fill="red")
# Save the second image
ps_file2 = os.path.join(directory, "circle_without_labels.ps")
temp_canvas.update()
temp_canvas.postscript(file=ps_file2, colormode='color')
img2 = Image.open(ps_file2)
img2.save(os.path.join(directory, "circle_without_labels.png"), "png")
os.remove(ps_file2)
messagebox.showinfo("Saved", f"Images saved to {directory}")
if __name__ == "__main__":
root = tk.Tk()
app = CircleDrawer(root)
root.mainloop()
Explanation of the Program
-
Imports and Setup:
- Tkinter: Used for creating the GUI.
- math: For calculating positions on the circle.
- PIL (Pillow): For handling image saving.
- os: For file operations.
-
Class CircleDrawer:
- Initialization: Sets up the main window, initializes variables, and calls
create_widgets to build the UI.
-
UI Components (create_widgets):
- Control Frame: Contains inputs for the number of points and line pairs, along with buttons to draw the circle and lines.
- Canvas: The drawing area where the circle and lines are rendered. It also handles mouse clicks for drawing lines.
- Lists Frame: Displays the list of drawn lines and intersections.
- Buttons Frame: Contains the "Back", "Save", and "Clear" buttons.
-
Drawing the Circle (draw_circle):
- Validates the number of points entered by the user.
- Calculates the positions of each point evenly spaced around the circle.
- Draws each point and labels them.
- Draws the main circle.
-
Handling Line Inputs (draw_lines_from_input):
- Parses the input string for point pairs using regular expressions.
- Ensures each line is only drawn once by using a
set of frozensets.
- Draws the lines and updates the list of lines.
-
Mouse Click Handling (canvas_click):
- Detects clicks on points.
- Highlights the selected points.
- Draws a line between two distinct clicked points if it hasn't been drawn before.
- Checks for intersections with existing lines.
-
Intersection Detection (check_intersections):
- For every new line drawn, checks if it intersects with existing lines.
- If an intersection is found that's not at the endpoints, it's recorded and displayed.
-
Back, Clear, and Save Functionalities:
Running the Program
-
Start the Program: Run the Python script. A window will appear with input fields and a canvas.
-
Draw the Circle:
- Enter the number of points (1-36) and click "Draw Circle".
- The circle with labeled points will appear on the canvas.
-
Draw Lines via Input:
- Enter point pairs in the format
(2,8),(2,9) in the designated input field.
- Click "Draw Lines" to draw the specified lines on the circle.
-
Draw Lines via Mouse:
- Click on two distinct points on the circle. A line will be drawn between them.
- The line will be added to the list of lines, and any new intersections will be recorded.
-
Manage Lines:
- Back: Removes the last drawn line.
- Clear: Removes all lines and intersections.
-
Save Images:
- Click "Save" to export two images. You'll be prompted to choose a directory.
- The images will be saved as
circle_with_labels.png and circle_without_labels.png.
Notes
- Intersection Detection: The program detects intersections that occur strictly within the circle, excluding intersections at the labeled points.
- Data Validation: Ensures that only valid and distinct point pairs are processed.
- Graphical Representation: Uses colors to differentiate points (blue), lines (red), and intersections (purple).
This program provides a robust solution to your requirements, enabling both manual input and interactive line drawing with real-time intersection detection and management.