如何创建用户输入以更新PysimpleGUI中画布上Matplotlib图形的y轴

cl25kdpy  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(198)

我想在PysimpleGUI中创建一个字段,用户可以在其中选择Matplotlib图形的y轴值,并且程序会更新图形。我开始学习PysimpleGUI,但我对此不是很有经验。我没有通过谷歌找到答案。
我没有尝试太多,因为我不是很有经验,也没有通过谷歌找到一个解决方案。我希望得到一个想法,如何创建这样一个用户输入,更新PysimpleGUI图形的y轴

w1jd8yoj

w1jd8yoj1#

将matplotlib嵌入PySimpleGUI的示例代码。

import math, random
from pathlib import Path

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import PySimpleGUI as sg

# 1. Define the class as the interface between matplotlib and PySimpleGUI
class Canvas(FigureCanvasTkAgg):
    """
    Create a canvas for matplotlib pyplot under tkinter/PySimpleGUI canvas
    """
    def __init__(self, figure=None, master=None):
        super().__init__(figure=figure, master=master)
        self.canvas = self.get_tk_widget()
        self.canvas.pack(side='top', fill='both', expand=1)

# 2. create PySimpleGUI window, a fixed-size Frame with Canvas which expand in both x and y.
font = ("Courier New", 11)
sg.theme("DarkBlue3")
sg.set_options(font=font)
layout = [
    [sg.Input(expand_x=True, key='Path'),
     sg.FileBrowse(file_types=(("ALL CSV Files", "*.csv"), ("ALL Files", "*.*"))),
     sg.Button('Plot')],
    [sg.Frame("", [[sg.Canvas(background_color='green', expand_x=True, expand_y=True, key='Canvas')]], size=(640, 480))],
    [sg.Push(), sg.Button('Exit')]
]
window = sg.Window('Matplotlib', layout, finalize=True)

# 3. Create a matplotlib canvas under sg.Canvas or sg.Graph
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot()
canvas = Canvas(fig, window['Canvas'].Widget)

# 4. initial for figure
ax.set_title(f"Sensor Data")
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.set_xlim(0, 1079)
ax.set_ylim(-1.1, 1.1)
ax.grid()
canvas.draw()                       # do Update to GUI canvas

# 5. PySimpleGUI event loop
while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, 'Exit'):
        break
    elif event == 'Plot':
        """
        path = values['Path']
        if not Path(path).is_file():
            continue
        """
        # 6. Get data from path and plot from here
        ax.cla()                    # Clear axes first if required
        ax.set_title(f"Sensor Data")
        ax.set_xlabel("X axis")
        ax.set_ylabel("Y axis")
        ax.grid()
        theta = random.randint(0, 359)
        x = [degree for degree in range(1080)]
        y = [math.sin((degree+theta)/180*math.pi) for degree in range(1080)]
        ax.plot(x, y)
        canvas.draw()               # do Update to GUI canvas

# 7. Close window to exit
window.close()

您可以添加具有不同键的Input元素,在绘图时通过values[key]获取元素值以更新y轴。

更新-示例代码

为y轴数据添加Input元素

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import PySimpleGUI as sg

class Canvas(FigureCanvasTkAgg):
    """
    Create a canvas for matplotlib pyplot under tkinter/PySimpleGUI canvas
    """
    def __init__(self, figure=None, master=None):
        super().__init__(figure=figure, master=master)
        self.canvas = self.get_tk_widget()
        self.canvas.pack(side='top', fill='both', expand=1)

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

sg.set_options(font=("Courier New", 16))

layout = [
    [sg.Text("Income last week")],
    [sg.Canvas(size=(640, 480), background_color='green', expand_x=True, expand_y=True, key='Canvas')],
    [sg.Text(day, size=10, justification='center') for day in days],
    [sg.Input(size=10, justification='right', key=('Day', i)) for i in range(len(days))],
    [sg.Push(), sg.Button('Plot')]
]
window = sg.Window('Title', layout, finalize=True)
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot()
canvas = Canvas(fig, window['Canvas'].Widget)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break
    elif event == 'Plot':
        # x = [i for i in range(len(days))]
        y = []
        for i in range(len(days)):
            try:
                value = float(values[('Day', i)])
            except:
                value = 0
            y.append(value)
        ax.cla()
        ax.grid()
        ax.plot(days, y)
        canvas.draw()

window.close()

相关问题