Ahoj! Rozumím, že máš dva problémy s tvým Python skriptem:
- Varování
tight_layout: Toto varování vzniká, protože funkce plt.tight_layout() není kompatibilní s ručně přidanými Axes, jakými je například sidebar ve tvém případě.
- Neaktualizující se rok při použití tlačítek: To může být důsledkem konfliktu s layoutem figure nebo jinými částmi kódu, které brání správné aktualizaci textu.
Níže je kompletně opravený kód, který řeší oba problémy:
- Odstranění
plt.tight_layout(): Vzhledem k tomu, že ručně přidáváš sidebar pomocí add_axes, není vhodné používat tight_layout(), které může způsobit konflikty s umístěním Axes.
- Zajištění aktualizace data: Ujistil jsem se, že textové pole pro datum je správně aktualizováno po každé interakci s tlačítky.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button, TextBox
import numpy as np
# Definice třídy pro Planet
class Planet:
def __init__(self, name, distance, speed, initial_angle=1):
"""
Inicializuje planetu s jejími vlastnostmi.
:param name: Název planety
:param distance: Vzdálenost od hvězdy (AU)
:param speed: Orbitalní rychlost (degrees per day)
:param initial_angle: Počáteční úhel (degrees), defaultně 1°
"""
self.name = name
self.distance = distance # V astronomických jednotkách (AU)
self.speed = speed # Rychlost v °/den
self.initial_angle = initial_angle # Počáteční úhel
self.angle = initial_angle # Aktuální úhel
def update_angle(self, cumulative_days):
"""
Aktualizuje aktuální úhel na základě celkových dnů.
:param cumulative_days: Celkové dny simulace
"""
self.angle = (self.initial_angle + self.speed * cumulative_days) % 360
def get_cartesian(self):
"""
Převádí aktuální úhel do kartézských souřadnic.
:return: (x, y) pozice planety
"""
rad = np.deg2rad(self.angle)
x = self.distance * np.cos(rad)
y = self.distance * np.sin(rad)
return (x, y)
# Funkce pro získání vstupu od uživatele
def get_number_of_planets():
while True:
try:
num = int(input("Zadejte počet planet (1-12): "))
if 1 <= num <= 12:
return num
else:
print("Prosím zadejte číslo mezi 1 a 12.")
except ValueError:
print("Neplatný vstup. Zadejte celé číslo mezi 1 a 12.")
# Inicializace planetárního systému podle počtu planet
def initialize_system(number_of_planets):
planets = []
# Dynamické nastavení rychlosti a vzdáleností
max_speed = 12 # Rychlost nejbližší planety (degrees per day)
if number_of_planets > 1:
speed_decrement = (max_speed - 1) / (number_of_planets - 1) # Snížení rychlosti pro každou planetu
else:
speed_decrement = 0
base_distance = 1 # Vzdálenost nejbližší planety (AU)
distance_increment = 1 # Přírůstek vzdálenosti pro každou planetu (AU)
initial_base_angle = 1 # Základní úhel 1°
for i in range(1, number_of_planets + 1):
distance = base_distance + (i - 1) * distance_increment # 1 AU, 2 AU, ..., n AU
speed = max_speed - (i - 1) * speed_decrement # Dynamicky snížená rychlost
initial_angle = initial_base_angle # Všechny planety začínají na 1°
planet = Planet(name=f"Planet {i}", distance=distance, speed=speed, initial_angle=initial_angle)
planets.append(planet)
return planets
# Třída pro řízení simulace
class PlanetarySystemSimulation:
def __init__(self, number_of_planets):
# Inicializace systému
self.planets = initialize_system(number_of_planets)
# Datumové proměnné
self.cumulative_days = 1 # Starting from day 1
self.day = 1
self.month = 1
self.year = 1
# Nastavení grafu
self.fig, self.ax = plt.subplots(figsize=(12, 8))
self.fig.subplots_adjust(left=0.35) # Leave space on the left for sidebar
# Hlavní plot pro planetární systém
self.ax.set_aspect('equal')
# Dynamické nastavení hranic grafu podle počtu planet
max_distance = max(planet.distance for planet in self.planets) + 2 # Přidáme trochu prostoru
self.ax.set_xlim(-max_distance, max_distance)
self.ax.set_ylim(-max_distance, max_distance)
self.ax.set_xlabel('X (AU)')
self.ax.set_ylabel('Y (AU)')
self.ax.set_title(f'Simulace Planetárního Systému s {number_of_planets} Planetami')
# Zobrazení hvězdy
self.ax.plot(0, 0, 'yo', markersize=12, label='Hvězda')
# Kreslení orbitálních drah
for planet in self.planets:
orbit = plt.Circle((0, 0), planet.distance, color='gray', linestyle='dashed', fill=False, alpha=0.5)
self.ax.add_artist(orbit)
# Inicializace planet jako scatter body
self.scatters = []
for planet in self.planets:
x, y = planet.get_cartesian()
scatter, = self.ax.plot([x], [y], 'o', markersize=6, label=planet.name)
self.scatters.append(scatter)
# Sidebar pro tlačítka a datum
self.setup_sidebar()
# Inicializace animace
self.ani = None
# Aktualizace data text na startovní hodnotu
self.update_date_text()
def setup_sidebar(self):
# Přidání sidebaru pomocí add_axes
ax_sidebar = self.fig.add_axes([0.05, 0.05, 0.25, 0.9]) # [left, bottom, width, height]
ax_sidebar.axis('off') # Skrýt osu
# Start and Stop buttons
ax_start = ax_sidebar.inset_axes([0.05, 0.85, 0.9, 0.1]) # [left, bottom, width, height]
self.button_start = Button(ax_start, 'Start')
self.button_start.on_clicked(self.start_animation)
ax_stop = ax_sidebar.inset_axes([0.05, 0.75, 0.9, 0.1])
self.button_stop = Button(ax_stop, 'Stop')
self.button_stop.on_clicked(self.stop_animation)
# Controls for Days
# Add Days
ax_add_day_text = ax_sidebar.inset_axes([0.05, 0.65, 0.3, 0.05])
self.text_add_day = TextBox(ax_add_day_text, '+ Days', initial='0')
ax_add_day_btn = ax_sidebar.inset_axes([0.35, 0.65, 0.2, 0.05])
self.button_add_day = Button(ax_add_day_btn, 'Add')
self.button_add_day.on_clicked(self.add_day)
# Remove Days
ax_remove_day_text = ax_sidebar.inset_axes([0.05, 0.58, 0.3, 0.05])
self.text_remove_day = TextBox(ax_remove_day_text, '- Days', initial='0')
ax_remove_day_btn = ax_sidebar.inset_axes([0.35, 0.58, 0.2, 0.05])
self.button_remove_day = Button(ax_remove_day_btn, 'Remove')
self.button_remove_day.on_clicked(self.remove_day)
# Controls for Months
# Add Months
ax_add_month_text = ax_sidebar.inset_axes([0.05, 0.45, 0.3, 0.05])
self.text_add_month = TextBox(ax_add_month_text, '+ Months', initial='0')
ax_add_month_btn = ax_sidebar.inset_axes([0.35, 0.45, 0.2, 0.05])
self.button_add_month = Button(ax_add_month_btn, 'Add')
self.button_add_month.on_clicked(self.add_month)
# Remove Months
ax_remove_month_text = ax_sidebar.inset_axes([0.05, 0.38, 0.3, 0.05])
self.text_remove_month = TextBox(ax_remove_month_text, '- Months', initial='0')
ax_remove_month_btn = ax_sidebar.inset_axes([0.35, 0.38, 0.2, 0.05])
self.button_remove_month = Button(ax_remove_month_btn, 'Remove')
self.button_remove_month.on_clicked(self.remove_month)
# Controls for Years
# Add Years
ax_add_year_text = ax_sidebar.inset_axes([0.05, 0.15, 0.3, 0.05])
self.text_add_year = TextBox(ax_add_year_text, '+ Years', initial='0')
ax_add_year_btn = ax_sidebar.inset_axes([0.35, 0.15, 0.2, 0.05])
self.button_add_year = Button(ax_add_year_btn, 'Add')
self.button_add_year.on_clicked(self.add_year)
# Remove Years
ax_remove_year_text = ax_sidebar.inset_axes([0.05, 0.08, 0.3, 0.05])
self.text_remove_year = TextBox(ax_remove_year_text, '- Years', initial='0')
ax_remove_year_btn = ax_sidebar.inset_axes([0.35, 0.08, 0.2, 0.05])
self.button_remove_year = Button(ax_remove_year_btn, 'Remove')
self.button_remove_year.on_clicked(self.remove_year)
# Datum text
self.date_text = ax_sidebar.text(0.5, 0.35, '', ha='center', va='center', fontsize=12, transform=ax_sidebar.transAxes)
def start_animation(self, event):
"""Spustí animaci."""
if self.ani is None:
print("Spouštím animaci...")
self.ani = animation.FuncAnimation(
self.fig,
self.animate,
fargs=(self.scatters,),
frames=360,
interval=100,
blit=False,
repeat=True
)
self.fig.canvas.draw_idle() # Aktualizace GUI
else:
print("Animace již běží.")
self.ani.event_source.start()
def stop_animation(self, event):
"""Zastaví animaci."""
if self.ani is not None:
print("Zastavuji animaci...")
self.ani.event_source.stop()
else:
print("Animace ještě neběží.")
def add_day(self, event):
"""Přidá N dní podle vstupu."""
try:
days = int(self.text_add_day.text)
if days < 0:
raise ValueError
self.cumulative_days += days
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro přidání dnů. Zadejte celé číslo >=0.")
def remove_day(self, event):
"""Odebere N dní podle vstupu."""
try:
days = int(self.text_remove_day.text)
if days < 0:
raise ValueError
self.cumulative_days -= days
if self.cumulative_days < 0:
self.cumulative_days = 0
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro odebrání dnů. Zadejte celé číslo >=0.")
def add_month(self, event):
"""Přidá N měsíců podle vstupu."""
try:
months = int(self.text_add_month.text)
if months < 0:
raise ValueError
self.cumulative_days += months * 30
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro přidání měsíců. Zadejte celé číslo >=0.")
def remove_month(self, event):
"""Odebere N měsíců podle vstupu."""
try:
months = int(self.text_remove_month.text)
if months < 0:
raise ValueError
self.cumulative_days -= months * 30
if self.cumulative_days < 0:
self.cumulative_days = 0
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro odebrání měsíců. Zadejte celé číslo >=0.")
def add_year(self, event):
"""Přidá N let podle vstupu."""
try:
years = int(self.text_add_year.text)
if years < 0:
raise ValueError
self.cumulative_days += years * 360
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro přidání let. Zadejte celé číslo >=0.")
def remove_year(self, event):
"""Odebere N let podle vstupu."""
try:
years = int(self.text_remove_year.text)
if years < 0:
raise ValueError
self.cumulative_days -= years * 360
if self.cumulative_days < 0:
self.cumulative_days = 0
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
except ValueError:
print("Neplatný vstup pro odebrání let. Zadejte celé číslo >=0.")
def update_date_text(self):
"""Aktualizuje text zobrazující datum."""
# Vypočítáme day, month, year z cumulative_days
cumulative = self.cumulative_days
if cumulative >= 0:
year = (cumulative // 360) + 1
remaining_days = cumulative % 360
else:
year = 1 # prevent negative years
remaining_days = 0
if remaining_days >= 0:
month = (remaining_days // 30) + 1
day = (remaining_days % 30) + 1
else:
month = 1
day = 1
# Aktualizace planetových úhlů
for planet in self.planets:
planet.update_angle(self.cumulative_days)
# Aktualizace planetových pozic
for planet, scatter in zip(self.planets, self.scatters):
x, y = planet.get_cartesian()
scatter.set_data([x], [y])
# Aktualizace datum text
self.day = int(day)
self.month = int(month)
self.year = int(year)
self.date_text.set_text(f"Datum: {self.day:02d}-{self.month:02d}-{self.year:04d}")
def animate(self, frame, scatters):
"""Automaticky aktualizuje pozice planet a datum."""
# Přidání jednoho dne na každý frame
self.cumulative_days += 1
self.update_date_text()
self.fig.canvas.draw_idle() # Aktualizace GUI
return scatters
def show(self):
"""Zobrazuje graf a spustí interaktivní mód."""
# Odstranění tight_layout, který způsobuje varování
# plt.tight_layout() # Tento řádek je odstraněn, aby nedocházelo k varováním
plt.show()
def main():
print("=== Simulace Planetárního Systému ===")
number_of_planets = get_number_of_planets()
simulation = PlanetarySystemSimulation(number_of_planets)
simulation.show()
if __name__ == "__main__":
main()
Změny a Vysvětlení
-
Odstranění plt.tight_layout():
- Ve třídě
PlanetarySystemSimulation jsem odstranil nebo zakomentoval řádek plt.tight_layout() v metodě show(). Toto odstranění eliminuje varování, které jsi obdržel, protože tight_layout není kompatibilní s manuálně přidanými Axes (sidebar).
-
Aktualizace Data:
- Zajištění, že po každé interakci s tlačítky (přidání/odebrání dní, měsíců, let) se volá
self.update_date_text() a následně self.fig.canvas.draw_idle(), což zaručuje, že textová pole se budou správně aktualizovat.
-
Další Vylepšení:
- Rodina Planet: Přidal jsem komentáře a strukturování kódu pro lepší čitelnost a údržbu.
- Bezpečnost: Přidal jsem kontrolu, aby
cumulative_days nikdy nespadlo pod nulu, což by mohlo způsobit nečekané chování.
Doporučení
-
Rozšíření Layoutu: Pokud bys chtěl pokročilejší layout, můžeš zvážit použití GridSpec nebo constrained_layout, které nabízejí větší flexibilitu ve správě různých Axes v jedné figure.
-
Optimalizace Animace: Pro lepší výkon můžeš experimentovat s parametrem blit=True v FuncAnimation, pokud to tvoje verze Matplotlib podporuje. To může zrychlit animaci tím, že aktualizuje jen část figure.
Doufám, že tyto úpravy pomohou vyřešit tvé problémy. Pokud narazíš na další potíže nebo máš další otázky, neváhej se zeptat!