PHP前端开发

Tkinter界面实时绘制函数图像:如何实现按钮控制电路的断开与闭合并从点击时刻开始绘制?

百变鹏仔 5天前 #Python
文章标签 并从

设计tkinter控制按钮,实时生成函数图像

问题:使用tkinter设计了界面,但点击按钮后,函数图像从0开始,而不是按钮点击时刻开始,无法实现电路的断开和闭合。

解决方案:

修改代码中的关键部分:

def toggle_manual_switch(self):    # 获取当前时刻的索引    current_index = int(self.current_time_index)    # 进行状态切换    self.simulator.switch_states[current_index] = not self.simulator.switch_states[current_index]    # 更新按钮文本和命令    if self.manual_switch_button["text"] == "Close Circuit":        self.manual_switch_button["text"] = "Open Circuit"    else:        self.manual_switch_button["text"] = "Close Circuit"    # 更新整个图表,传递当前时间点的索引    self.update_plot(current_index)    self.canvas.draw_idle()def calculate_circuit_response(self, current_time_index):    # 检查当前时间点是否有开关切换发生    if current_time_index > self.previous_switch_time_index:        # 检查当前时间点的开关状态是否与前一时刻不同        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_indexdef update_plot(self, frame):    self.simulator.calculate_circuit_response(frame)    time = t[frame]    # 更新时间索引    self.current_time_index = frame    V_circuit = self.simulator.VoltageOverTime[:frame + 1]    I_circuit = self.simulator.CurrentOverTime[:frame + 1]    self.V_line.set_data(t[:len(V_circuit)], V_circuit)    self.I_line.set_data(t[:len(I_circuit)], I_circuit)    self.axs[0].set_xlim(0, t_max)    self.axs[1].set_xlim(0, t_max)    self.axs[0].set_ylim(0, 20)    self.axs[1].set_ylim(0, 2)    print("Plot updated")  # 添加这行代码来确认图表是否被更新    print("Plot Voltage:", V_circuit[-1], "V")    return self.V_line, self.I_line

特点:

这些修改后,电路可以从按钮点击时刻开始绘制,并且按钮操作能够实现电路的断开和闭合。