matplotlib 关闭绘图窗口后,plot.show仍在运行

t9eec4r0  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(164)
import os
import sys
from typing import List
from scipy import signal
from scipy import interpolate
from scipy.interpolate import interp1d
import numpy as np
import csv
import itertools
from string import ascii_uppercase
import time
import matplotlib.pyplot as plt
import scipy.io as sio
import wvfreader
import math
from scipy.fft import fft, ifft, fftfreq
import xlsxwriter
import datetime
import PySimpleGUI as sg

字符串
这些是我的程序的输入。我先用plt.show()绘图,然后显示图形,但在关闭图形窗口(按右上角的“x”)后,程序仍保留在plt.show()命令中,不会进一步执行。plt.show()是否会陷入某种循环?
我尝试了不同的方法,但都不起作用。该程序在没有plt.show()的情况下完美地工作。即使当我保存情节而不是显示程序的作品。因此,主要问题似乎是plt.show()。是否有其他方法可以代替plt.show()来显示图?

4c8rllxm

4c8rllxm1#

因为我不确定你的代码是什么,或者你想做什么,这是你第二次问这个问题(在一个新的账户上),也许需要一个新的方法。在这里,我展示了一个如何为图形创建GUI的示例,以及每次单击图形按钮时图形如何更改。也许这种技术会更好地服务于你想要实现的目标。我强烈建议您阅读PySimpleGUI documentation

import PySimpleGUI as sg
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

# Random data for the graph
data1 = [1,2,3,4,5]
data2 = [5,4,3,2,1]

# Graphing function
def graph(data):
    fig, ax1 = plt.subplots(1)
    plt.plot(data)
    draw_figure(window['Graph_Canvas'].TKCanvas, fig)
    
# This definition is used to create a Matplotlib figure inside the main window
def draw_figure(canvas, fig):
    if canvas.children:
        plt.close()                           # close any open figures (too many open pyplot figures eat up RAM)
        for child in canvas.winfo_children(): # close any already created canvas figures
            child.destroy()            
    figure_canvas_agg = FigureCanvasTkAgg(fig, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

# Layout of the GUI
layout = [
    [sg.Push(), sg.B('Graph'), sg.Push()],
    [sg.Canvas(key = 'Graph_Canvas')],
]

window = sg.Window(title='Test', layout = layout, resizable=True).Finalize()
window.BringToFront()

# Some place holder variables to be used later
version, data = 0, []
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
        
    elif event == 'Graph':
        
        # If data1 was graphed then graph data2 and vice versa
        if version == 0: 
            data = data1
            version = 1
        else:
            data = data2
            version = 0
        # Call the graph function
        graph(data)
        
window.close()

字符串

相关问题