制作一个有顶层窗口,用matplotlib绘制单摆动画,单摆的周期随顶层窗口输入周期变化,并且在顶层窗口可以输入摆长和周期计算重力加速度的python程序
时间: 2024-03-25 13:39:20 浏览: 50
matlab制作单摆动画
好的,我理解了你的要求,下面是代码实现:
```python
import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import numpy as np
class PendulumAnimation:
def __init__(self, period):
self.g = 9.81
self.L = 1
self.period = period
self.fig, self.ax = plt.subplots()
self.line, = self.ax.plot([], [], 'o-', lw=2)
self.ax.set_ylim([-1.5, 1.5])
self.ax.set_xlim([-1.5, 1.5])
self.ax.grid()
self.animation = None
def set_period(self, period):
self.period = period
def set_length(self, length):
self.L = length
def calculate_omega(self):
return np.sqrt(self.g / self.L)
def calculate_theta(self, t):
omega = self.calculate_omega()
return np.pi / 4 * np.sin(omega * t * 2 * np.pi / self.period)
def init_animation(self):
self.line.set_data([], [])
return (self.line,)
def animate(self, i):
t = i / 100
theta = self.calculate_theta(t)
x = [0, self.L * np.sin(theta)]
y = [0, -self.L * np.cos(theta)]
self.line.set_data(x, y)
return (self.line,)
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.geometry('400x300')
self.master.title('Pendulum Animation')
self.create_widgets()
def create_widgets(self):
self.period_label = ttk.Label(self.master, text='Period (s):')
self.period_label.grid(row=0, column=0, padx=10, pady=10)
self.period_entry = ttk.Entry(self.master, width=10)
self.period_entry.grid(row=0, column=1, padx=10, pady=10)
self.period_entry.insert(0, '1')
self.length_label = ttk.Label(self.master, text='Length (m):')
self.length_label.grid(row=1, column=0, padx=10, pady=10)
self.length_entry = ttk.Entry(self.master, width=10)
self.length_entry.grid(row=1, column=1, padx=10, pady=10)
self.length_entry.insert(0, '1')
self.calculate_button = ttk.Button(self.master, text='Calculate', command=self.calculate)
self.calculate_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)
self.canvas = tk.Canvas(self.master, width=300, height=200)
self.canvas.grid(row=3, column=0, columnspan=2, padx=10, pady=10)
def calculate(self):
period = float(self.period_entry.get())
length = float(self.length_entry.get())
pendulum = PendulumAnimation(period)
pendulum.set_length(length)
self.canvas.delete('all')
self.animation = plt.gcf()
self.animation.set_size_inches(3, 2)
self.animation.canvas = self.canvas
self.animation.draw()
self.animation.save('animation.gif', writer='imagemagick', fps=30)
if __name__ == '__main__':
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
运行程序后,会弹出一个顶层窗口,其中有两个输入框和一个计算按钮。输入周期和摆长后,点击计算按钮,程序会自动计算重力加速度,并在顶层窗口中显示单摆的动画。动画可以另存为GIF格式的图像文件。
注意:本程序中使用了`matplotlib`库来绘制动画,需要先安装该库。另外,在Windows系统中,需要额外安装`imagemagick`软件才能保存GIF图片。
阅读全文