
问题: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通过这些修改,图表将根据模拟开关按钮的点击时间绘制电压和电流的实时响应,并且按钮将正确地实现电路的断开和闭合功能。
以上就是Tkinter模拟电路:如何让按钮点击实时更新函数图像并控制电路开关?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号