python实现GUI界面控制二阶系统的阶跃响应,用滑块控制
时间: 2024-05-15 18:12:35 浏览: 104
模糊控制下二阶系统的阶跃响应
可以使用Python的GUI库Tkinter来实现这个功能。具体步骤如下:
1. 导入需要的库
```python
import tkinter as tk
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
```
2. 定义一个函数来绘制阶跃响应图形
```python
def plot_step_response(num, den, K):
sys = signal.TransferFunction(num, den)
t, y = signal.step(sys*K)
fig, ax = plt.subplots()
ax.plot(t, y)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.set_title('Step response')
plt.show()
```
3. 创建一个Tkinter窗口,并添加一个滑块和一个按钮
```python
root = tk.Tk()
root.title('Control System')
slider = tk.Scale(root, from_=0.1, to=10, resolution=0.1, orient=tk.HORIZONTAL, label='K')
slider.pack()
button = tk.Button(root, text='Plot', command=lambda: plot_step_response([1], [1, 1, 1], slider.get()))
button.pack()
root.mainloop()
```
在这里,我们定义了一个二阶系统,其传递函数为$G(s)=\frac{1}{s^2+s+1}$。滑块的取值范围为0.1到10,步长为0.1,初始值为1。当用户点击“Plot”按钮时,会调用`plot_step_response`函数来绘制阶跃响应图形。
完整代码如下:
```python
import tkinter as tk
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
def plot_step_response(num, den, K):
sys = signal.TransferFunction(num, den)
t, y = signal.step(sys*K)
fig, ax = plt.subplots()
ax.plot(t, y)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.set_title('Step response')
plt.show()
root = tk.Tk()
root.title('Control System')
slider = tk.Scale(root, from_=0.1, to=10, resolution=0.1, orient=tk.HORIZONTAL, label='K')
slider.pack()
button = tk.Button(root, text='Plot', command=lambda: plot_step_response([1], [1, 1, 1], slider.get()))
button.pack()
root.mainloop()
```
阅读全文