Tkinter模拟电路:如何让按钮点击实时更新函数图像并控制电路开关?

ID:21566 / 打印

tkinter模拟电路:如何让按钮点击实时更新函数图像并控制电路开关?

问题:tkinter 控制按钮实时生成函数图像出现问题?

问题详情:

当点击模拟开关按钮时,电压和电流的图表从 0时刻开始绘制,而不是按钮点击的时刻。此外,按钮无法实现电路的断开和闭合。

回答:

此问题可以通过修改几个关键函数来解决:

修改 1:circuitsimulator 类的 calculate_circuit_response

# 如果当前时刻开关状态与上一时刻不同 if self.switch_states[current_time_index] != self.switch_states[current_time_index - 1]:     # 更新上一个开关状态     self.previous_switch_state = not self.previous_switch_state      # 找到下一个开关状态变化的时间点     next_switch_index = current_time_index + np.argmax(         self.switch_states[current_time_index:] != self.switch_states[current_time_index])      # 根据当前开关状态更新电压和电流数组     if not self.previous_switch_state:         # 开关断开         self.voltageovertime[current_time_index:] = 0         self.currentovertime[current_time_index:] = 0     else:         # 开关闭合         self.voltageovertime[current_time_index:] = v_battery * np.ones_like(             self.voltageovertime[current_time_index:])         self.currentovertime[current_time_index:] = v_battery / r_load * np.ones_like(             self.currentovertime[current_time_index:])      # 更新上一次开关切换的时间索引     self.previous_switch_time_index = next_switch_index

修改 2:circuitsimulationgui 类的 toggle_manual_switch

def toggle_manual_switch(self):     # 获取当前时刻的索引     current_time_index = int(self.current_time_index)      # 切换开关状态     self.simulator.toggle_switch_at_time(current_time_index)     self.simulator.calculate_circuit_response(current_time_index)      # 更新按钮文本和命令     # ... 省略 ...      # 更新图表,传递当前时刻的索引     self.update_plot(current_time_index)     self.canvas.draw_idle()

修改 3:circuitsimulationgui 类的 update_plot

def update_plot(self, frame):     # 计算电路响应     self.simulator.calculate_circuit_response(frame)      # 获取当前时间和电压、电流数据     time = t[frame]     V_circuit = self.simulator.VoltageOverTime     I_circuit = self.simulator.CurrentOverTime      # 更新图表数据     self.V_line.set_data(t, V_circuit)     self.I_line.set_data(t, I_circuit)      # 设置坐标轴范围     # ... 省略 ...      # 打印提示信息     print("Plot updated")     print("Plot Voltage:", V_circuit[-1], "V")      return self.V_line, self.I_line

通过这些修改,图表将根据模拟开关按钮的点击时间绘制电压和电流的实时响应,并且按钮将正确地实现电路的断开和闭合功能。

上一篇: PyInstaller打包Tkinter程序时,如何正确加载WAV资源?
下一篇: Flask小程序真机测试无响应或报错怎么办?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。