You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter按钮触发绘制S参数图表问题求助

Fixing Your Tkinter-Matplotlib S-Parameter GUI

Hey there! Let's get your button-click plot functionality working smoothly. I've spotted a few key issues in your code, plus some optimizations to make it cleaner and more reliable.

First, let's break down the problems in your original code:

  • There's an extra } at the very end that's causing a syntax error
  • Matplotlib's default backend doesn't play nicely with Tkinter out of the box, which can lead to plots not showing up or your GUI freezing
  • The S12 plot has a typo in its title (it says "S22" instead of "S12")
  • Repeatedly creating new plt.figure() instances will clutter your screen with multiple windows over time

Here's the revised, working version of your code:

import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Load your data first (good practice to keep setup code at the top)
Frequency, S11_Mag, S11_Ph, S21_Mag, S21_Ph, S12_Mag, S12_Ph, S22_Mag, S22_Ph = np.loadtxt(
    '/Users/polo/Desktop/S2P_File.csv', 
    unpack=True, 
    delimiter=','
)

root = tk.Tk()
root.title('Project: S-Parameters & Stability')
frame = tk.Frame(root, relief='raised', bd=3)
frame.pack(pady=10)

# Create a single Matplotlib figure to reuse for all plots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(pady=10)

def plot_graph(param):
    # Clear previous plots to avoid overlapping
    ax1.clear()
    ax2.clear()
    
    # Select the right data based on the button clicked
    if param == 'S11':
        mag_data = S11_Mag
        ph_data = S11_Ph
        title = 'S11 Magnitude and Phase'
    elif param == 'S22':
        mag_data = S22_Mag
        ph_data = S22_Ph
        title = 'S22 Magnitude and Phase'
    elif param == 'S21':
        mag_data = S21_Mag
        ph_data = S21_Ph
        title = 'S21 Magnitude and Phase'
    elif param == 'S12':
        mag_data = S12_Mag
        ph_data = S12_Ph
        title = 'S12 Magnitude and Phase'  # Fixed the typo here!
    
    # Plot the magnitude and phase
    ax1.plot(Frequency, mag_data)
    ax1.set_ylabel('Magnitude (dB)')
    ax1.set_title(title)
    
    ax2.plot(Frequency, ph_data)
    ax2.set_xlabel('Frequency (GHz)')
    ax2.set_ylabel('Phase (Degree)')
    
    # Refresh the canvas to show the new plot
    canvas.draw()

# Create your buttons with padding for better spacing
tk.Button(frame, text="S11", command=lambda: plot_graph('S11')).pack(side=tk.LEFT, fill=tk.Y, padx=5)
tk.Button(frame, text="S22", command=lambda: plot_graph('S22')).pack(side=tk.LEFT, fill=tk.Y, padx=5)
tk.Button(frame, text="S21", command=lambda: plot_graph('S21')).pack(side=tk.LEFT, fill=tk.Y, padx=5)
tk.Button(frame, text="S12", command=lambda: plot_graph('S12')).pack(side=tk.LEFT, fill=tk.Y, padx=5)

root.mainloop()

Key changes I made:

  1. Added the Tkinter Matplotlib backend: FigureCanvasTkAgg integrates plots directly into your Tkinter window, so plots show up inside the GUI instead of separate popups, and prevents the interface from freezing.
  2. Reused a single figure/axes: Instead of creating new figures every time, we clear existing axes and redraw—keeps things tidy and avoids window clutter.
  3. Fixed the S12 title typo: Now it correctly displays the parameter name.
  4. Removed redundant code: We reuse plotting logic by assigning data/title based on the selected parameter, making the code shorter and easier to maintain.
  5. Fixed the syntax error: Removed the extra } at the end of your original code.
  6. Added padding to buttons: Makes the GUI look cleaner with space between interactive elements.

This code will let you click each button to update the plot inside the Tkinter window instantly—no more separate popups or frozen GUI!

内容的提问来源于stack exchange,提问作者Mastrepolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:45:02