oprav skript a cely jej zapis sem. hlasi to chybu pri vstupu Exception in Tkinter…
- User
oprav skript a cely jej zapis sem. hlasi to chybu pri vstupu
Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python312\Lib\tkinter_init_.py", line 1967, in call return self.func(*args) ^^^^^^^^^^^^^^^^ File "C:\Users\pc-home\Desktop\Nová složka\kruznice o1 4 k uprave.py", line 134, in draw_lines_from_input pairs = self.parse_pairs(input_text) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\pc-home\Desktop\Nová složka\kruznice o1 4 k uprave.py", line 126, in parse_pairs a, b = int(match[0]), int(match[1]) ^^^^^^^^^^^^^ ValueError: invalid literal for int() with base 10: '3,8'
import tkinter as tk from tkinter import messagebox, filedialog import math from PIL import Image, ImageDraw, ImageGrab import os import re
class CircleDrawer: def init(self, root): self.root = root self.root.title("Circle Drawer")
# Inicializace proměnných self.num_points = 0 self.points = {} # point_num: (x, y) self.lines = set() # set of frozensets self.intersections = {} # (x, y): intersection_num self.intersection_counter = 1 self.current_clicks = [] # Vytvoření GUI prvků self.create_widgets() def create_widgets(self): # Horní rámec pro vstupní ovládací prvky control_frame = tk.Frame(self.root) control_frame.pack(side=tk.TOP, pady=10, padx=10, fill=tk.X) # Vstup pro počet bodů tk.Label(control_frame, text="Počet Bodů (1-36):").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W) self.num_entry = tk.Entry(control_frame, width=5) self.num_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W) self.num_entry.insert(0, "12") # výchozí hodnota self.draw_circle_button = tk.Button(control_frame, text="Nakreslit Kružnici", command=self.draw_circle) self.draw_circle_button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.W) # Vstup pro páry bodů tk.Label(control_frame, text="Zadání Párů (např. (2,8),(2,9)):").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W) self.pair_entry = tk.Entry(control_frame, width=30) self.pair_entry.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=tk.W) self.draw_lines_button = tk.Button(control_frame, text="Nakreslit Čáry", command=self.draw_lines_from_input) self.draw_lines_button.grid(row=1, column=3, padx=5, pady=5, sticky=tk.W) # Hlavní rámeček pro plátno a boční informace main_frame = tk.Frame(self.root) main_frame.pack(padx=10, pady=10) # Plátno pro kreslení self.canvas_size = 400 # Upravená velikost pro lepší rozložení self.canvas = tk.Canvas(main_frame, width=self.canvas_size, height=self.canvas_size, bg="white") self.canvas.pack(side=tk.LEFT, padx=10) self.canvas.bind("<Button-1>", self.canvas_click) # Boční rámec pro seznamy a tlačítka side_frame = tk.Frame(main_frame) side_frame.pack(side=tk.RIGHT, fill=tk.Y) # Seznam čar tk.Label(side_frame, text="Čáry:").pack(anchor=tk.W) self.lines_text = tk.Text(side_frame, width=25, height=10) self.lines_text.pack(pady=5) # Seznam průsečíků tk.Label(side_frame, text="Průsečíky:").pack(anchor=tk.W, pady=(10, 0)) self.intersections_text = tk.Text(side_frame, width=25, height=10) self.intersections_text.pack(pady=5) # Tlačítka buttons_frame = tk.Frame(side_frame) buttons_frame.pack(pady=10) self.back_button = tk.Button(buttons_frame, text="Zpět", command=self.back) self.back_button.pack(fill=tk.X, pady=2) self.save_button = tk.Button(buttons_frame, text="Uložit", command=self.save_images) self.save_button.pack(fill=tk.X, pady=2) self.clear_button = tk.Button(buttons_frame, text="Vymazat", command=self.clear_all) self.clear_button.pack(fill=tk.X, pady=2) def draw_circle(self): try: n = int(self.num_entry.get()) if not 1 <= n <= 36: raise ValueError except ValueError: messagebox.showerror("Neplatný Vstup", "Prosím, zadejte celé číslo mezi 1 a 36.") return self.num_points = n self.points = {} self.lines = set() self.intersections = {} 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 # Záporný pro směrem hodinových ručiček for i in range(n): angle = -math.pi / 2 + i * angle_gap # Start ze shora, směrem hodinových ručiček x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") def parse_pairs(self, input_text): 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] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line_{a}{b}") # Kontrola průsečíků 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 # Ignorovat opakované kliknutí na stejný bod 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_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 # Směr hodinových ručiček for i in range(self.num_points): angle = -math.pi / 2 + i * angle_gap # Start ze shora x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") # Nakreslení čar 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", tags=f"line{a}{b}") # Nakreslení průsečíků for (x, y), num in self.intersections.items(): self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection{num}") self.canvas.create_text(x + 6, y, text=str(num), fill="purple", tags=f"intersection_text_{num}") 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 # Kontrola, zda průsečík není na koncích čar if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): # Kontrola, zda průsečík již není zaznamenán if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 def get_line_intersection(self, line1, line2): (x1, y1), (x2, y2) = line1 (x3, y3), (x4, y4) = line2 # Výpočet jmenovatelů s operátory násobení denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None # Paralelní nebo souběžné čáry # Výpočet průsečíku 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 # Kontrola, zda průsečík leží na obou úsecích 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): # Přepočet průsečíků 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 # Čáry sdílejí společný bod 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}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") 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("Chyba", "Nejprve nakreslete kružnici.") return # Zeptání se na složku pro uložení directory = filedialog.askdirectory() if not directory: return # Uložení prvního obrázku s popisky a průsečíky ps_file = os.path.join(directory, "kruznice_s_popisky.eps") self.canvas.postscript(file=ps_file, colormode='color') try: img1 = Image.open(ps_file) img1.save(os.path.join(directory, "kruznice_s_popisky.png"), "png") os.remove(ps_file) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání prvního obrázku: {e}") return # Uložení druhého obrázku bez popisků a průsečíků # Dočasné skrytí popisků a průsečíků all_items = self.canvas.find_all() for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='hidden') # Aktualizace plátna self.canvas.update() ps_file2 = os.path.join(directory, "kruznice_bez_popisku.eps") self.canvas.postscript(file=ps_file2, colormode='color') try: img2 = Image.open(ps_file2) img2.save(os.path.join(directory, "kruznice_bez_popisku.png"), "png") os.remove(ps_file2) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání druhého obrázku: {e}") return # Obnovení viditelnosti popisků a průsečíků for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='normal') messagebox.showinfo("Hotovo", f"Obrázky byly uloženy do složky: {directory}")if name == "main": root = tk.Tk() app = CircleDrawer(root) root.mainloop()
- Assistant
Děkuji za poskytnutí chybové zprávy a kódu. Problém, který se vyskytuje, je způsoben tím, jak regulární výraz (
regex) ve funkciparse_pairszachytává a vrací výsledky. Pojďme se na to podívat podrobněji.Problém:
Ve funkci
parse_pairspoužíváte následující regulární výraz:pattern = r'(\s*(\d+)\s*,\s*(\d+)\s*)'Když použijete
re.findalls tímto vzorem na vstup jako"3,8", výsledek bude seznam obsahující n-tice, kde každá n-tice obsahuje celkovou shodu a jednotlivé skupiny:[('3,8', '3', '8')]Váš kód pak zkouší převést
match[0]amatch[1]na celá čísla:a, b = int(match[0]), int(match[1])Ale
match[0]je'3,8', což není platné celé číslo, a proto dochází kValueError.Řešení:
Musíte změnit indexace v n-tici výsledku
re.findall. Pokud máte vzor s více skupinami,match[1]amatch[2]obsahují skutečné čísla, která chcete převést na celá čísla.Níže je opravený skript:
import tkinter as tk from tkinter import messagebox, filedialog import math from PIL import Image, ImageDraw, ImageGrab import os import re class CircleDrawer: def __init__(self, root): self.root = root self.root.title("Circle Drawer") # Inicializace proměnných self.num_points = 0 self.points = {} # point_num: (x, y) self.lines = set() # set of frozensets self.intersections = {} # (x, y): intersection_num self.intersection_counter = 1 self.current_clicks = [] # Vytvoření GUI prvků self.create_widgets() def create_widgets(self): # Horní rámec pro vstupní ovládací prvky control_frame = tk.Frame(self.root) control_frame.pack(side=tk.TOP, pady=10, padx=10, fill=tk.X) # Vstup pro počet bodů tk.Label(control_frame, text="Počet Bodů (1-36):").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W) self.num_entry = tk.Entry(control_frame, width=5) self.num_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W) self.num_entry.insert(0, "12") # výchozí hodnota self.draw_circle_button = tk.Button(control_frame, text="Nakreslit Kružnici", command=self.draw_circle) self.draw_circle_button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.W) # Vstup pro páry bodů tk.Label(control_frame, text="Zadání Párů (např. (2,8),(2,9)):").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W) self.pair_entry = tk.Entry(control_frame, width=30) self.pair_entry.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=tk.W) self.draw_lines_button = tk.Button(control_frame, text="Nakreslit Čáry", command=self.draw_lines_from_input) self.draw_lines_button.grid(row=1, column=3, padx=5, pady=5, sticky=tk.W) # Hlavní rámeček pro plátno a boční informace main_frame = tk.Frame(self.root) main_frame.pack(padx=10, pady=10) # Plátno pro kreslení self.canvas_size = 400 # Upravená velikost pro lepší rozložení self.canvas = tk.Canvas(main_frame, width=self.canvas_size, height=self.canvas_size, bg="white") self.canvas.pack(side=tk.LEFT, padx=10) self.canvas.bind("<Button-1>", self.canvas_click) # Boční rámec pro seznamy a tlačítka side_frame = tk.Frame(main_frame) side_frame.pack(side=tk.RIGHT, fill=tk.Y) # Seznam čar tk.Label(side_frame, text="Čáry:").pack(anchor=tk.W) self.lines_text = tk.Text(side_frame, width=25, height=10) self.lines_text.pack(pady=5) # Seznam průsečíků tk.Label(side_frame, text="Průsečíky:").pack(anchor=tk.W, pady=(10, 0)) self.intersections_text = tk.Text(side_frame, width=25, height=10) self.intersections_text.pack(pady=5) # Tlačítka buttons_frame = tk.Frame(side_frame) buttons_frame.pack(pady=10) self.back_button = tk.Button(buttons_frame, text="Zpět", command=self.back) self.back_button.pack(fill=tk.X, pady=2) self.save_button = tk.Button(buttons_frame, text="Uložit", command=self.save_images) self.save_button.pack(fill=tk.X, pady=2) self.clear_button = tk.Button(buttons_frame, text="Vymazat", command=self.clear_all) self.clear_button.pack(fill=tk.X, pady=2) def draw_circle(self): try: n = int(self.num_entry.get()) if not 1 <= n <= 36: raise ValueError except ValueError: messagebox.showerror("Neplatný Vstup", "Prosím, zadejte celé číslo mezi 1 a 36.") return self.num_points = n self.points = {} self.lines = set() self.intersections = {} 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 # Záporný pro směrem hodinových ručiček for i in range(n): angle = -math.pi / 2 + i * angle_gap # Start ze shora, směrem hodinových ručiček x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") def parse_pairs(self, input_text): # Upravený regex pro správné zachycení párových čísel 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] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line_{a}{b}") # Kontrola průsečíků 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 # Ignorovat opakované kliknutí na stejný bod 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_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 # Směr hodinových ručiček for i in range(self.num_points): angle = -math.pi / 2 + i * angle_gap # Start ze shora x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") # Nakreslení čar 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", tags=f"line{a}{b}") # Nakreslení průsečíků for (x, y), num in self.intersections.items(): self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection{num}") self.canvas.create_text(x + 6, y, text=str(num), fill="purple", tags=f"intersection_text_{num}") 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 # Kontrola, zda průsečík není na koncích čar if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): # Kontrola, zda průsečík již není zaznamenán if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 def get_line_intersection(self, line1, line2): (x1, y1), (x2, y2) = line1 (x3, y3), (x4, y4) = line2 # Výpočet jmenovatelů s operátory násobení denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None # Paralelní nebo souběžné čáry # Výpočet průsečíku 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 # Kontrola, zda průsečík leží na obou úsecích 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): # Přepočet průsečíků 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 # Čáry sdílejí společný bod 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}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") 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("Chyba", "Nejprve nakreslete kružnici.") return # Zeptání se na složku pro uložení directory = filedialog.askdirectory() if not directory: return # Uložení prvního obrázku s popisky a průsečíky ps_file = os.path.join(directory, "kruznice_s_popisky.eps") self.canvas.postscript(file=ps_file, colormode='color') try: img1 = Image.open(ps_file) img1.save(os.path.join(directory, "kruznice_s_popisky.png"), "png") os.remove(ps_file) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání prvního obrázku: {e}") return # Uložení druhého obrázku bez popisků a průsečíků # Dočasné skrytí popisků a průsečíků all_items = self.canvas.find_all() for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='hidden') # Aktualizace plátna self.canvas.update() ps_file2 = os.path.join(directory, "kruznice_bez_popisku.eps") self.canvas.postscript(file=ps_file2, colormode='color') try: img2 = Image.open(ps_file2) img2.save(os.path.join(directory, "kruznice_bez_popisku.png"), "png") os.remove(ps_file2) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání druhého obrázku: {e}") return # Obnovení viditelnosti popisků a průsečíků for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='normal') messagebox.showinfo("Hotovo", f"Obrázky byly uloženy do složky: {directory}") if __name__ == "__main__": root = tk.Tk() app = CircleDrawer(root) root.mainloop()Hlavní Úpravy:
-
Regulární výraz ve funkci
parse_pairsbyl opraven:- Původní vzor
r'(\s*(\d+)\s*,\s*(\d+)\s*)'vrací n-tici se třemi prvky, kdematch[0]je celý řetězec, amatch[1],match[2]jsou jednotlivá čísla. - Opravený vzor
r'\(\s*(\d+)\s*,\s*(\d+)\s*\)'správně zachycuje pouze dvojice čísel uvnitř závorek.
pattern = r'\(\s*(\d+)\s*,\s*(\d+)\s*\)' - Původní vzor
-
Přístup k zachyceným číslům byl upraven:
- V původním kódu docházelo k převodu
match[0]amatch[1], kdematch[0]obsahoval celý řetězec jako'3,8', což způsobovalo chybu. - Opravený kód nyní převádí
match[0]amatch[1], které představují jednotlivá čísla.
a, b = int(match[0]), int(match[1]) - V původním kódu docházelo k převodu
-
Zlepšení regulárního výrazu:
- Přidáním závorek
\(a\)zajistíme, že se regex zaměří pouze na páry uzavřené v závorkách, což zvyšuje přesnost.
- Přidáním závorek
-
Ostatní drobné úpravy a optimalizace:
- Ostatní části kódu byly ponechány beze změny, protože problém byl výhradně ve funkci
parse_pairs.
- Ostatní části kódu byly ponechány beze změny, protože problém byl výhradně ve funkci
Jak Testovat:
- Spusťte skript.
- Zadejte počet bodů (např.
12) a klikněte na tlačítko "Nakreslit Kružnici". - Zadejte páry bodů ve správném formátu, například
(2,8),(2,9)do vstupního pole a klikněte na "Nakreslit Čáry". - Ověřte, že čáry jsou správně nakresleny a že průsečíky jsou identifikovány, pokud existují.
Příklad Vstupu:
- Vstup pro počet bodů:
12 - Vstupní páry:
(2,8),(2,9),(3,7),(4,10)
S těmito úpravami by skript měl fungovat bez výše uvedené chyby a správně zpracovávat vstupy ve formátu párů
(a,b).Pokud se objeví další problémy nebo máte další otázky, neváhejte se zeptat!
-