首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用PySimpleGUI、MatPlotLib和tkinter在选择函数时崩溃来绘制代码

使用PySimpleGUI、MatPlotLib和tkinter在选择函数时崩溃来绘制代码
EN

Stack Overflow用户
提问于 2019-08-07 21:12:16
回答 1查看 1.9K关注 0票数 3

大家好,可爱的聪明人。我偶然发现了这段漂亮的代码,从理论上讲,它应该对我正在从事的一个项目有所帮助。但是,每次我运行它并从列表中选择一个选项时,它都会崩溃。最初的代码有900多行,可以在这里找到:https://github.com/PySimpleGUI/PySimpleGUI/blob/e59b0060b6837cfb9ec3809da51e4fe04358b6ee/DemoPrograms/Demo_Matplotlib_Browser_Paned.py

我已经将它简化到最基本的部分,看看我是否能让它工作,但没有运气。

目标是在包含相应图形的画布旁边显示一个有效的图形选项列表,并能够根据用户的选择更新图形。

提前谢谢你!

我使用的是:PyCharm2.5社区版MatPlotLib版本3.1.1 PySimpleGui版本4.1 Numpy版本1.17

关于Mac Os Mojave 10.14.6

我已经更新了我所能做的一切。我也尝试过在Windows机器上运行它,结果出现了相同的错误消息。

代码语言:javascript
运行
复制
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
import matplotlib.backends.tkagg as tkagg
import inspect
import numpy as np
import matplotlib.pyplot as plt
import tkinter as Tk


def PyplotHistogram():
    np.random.seed(0)

    n_bins = 10
    x = np.random.randn(1000, 3)

    fig, axes = plt.subplots(nrows=2, ncols=2)
    ax0, ax1, ax2, ax3 = axes.flatten()

    colors = ['red', 'tan', 'lime']
    ax0.hist(x, n_bins, density=1, histtype='bar', color=colors, label=colors)
    ax0.legend(prop={'size': 10})
    ax0.set_title('bars with legend')

    ax1.hist(x, n_bins, density=1, histtype='bar', stacked=True)
    ax1.set_title('stacked bar')

    ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
    ax2.set_title('stack step (unfilled)')

    # Make a multiple-histogram of data-sets with different length.
    x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
    ax3.hist(x_multi, n_bins, histtype='bar')
    ax3.set_title('different sample sizes')

    fig.tight_layout()
    return fig


def draw_figure(canvas, figure, loc=(0, 0)):
    """ Draw a matplotlib figure onto a Tk canvas
    loc: location of top-left corner of figure on canvas in pixels.
    Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
    """
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

    # Position: convert from top-left anchor to center anchor
    canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)

    # Unfortunately, there's no accessor for the pointer to the native renderer
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)

    # Return a handle which contains a reference to the photo object
    # which must be kept live or else the picture disappears
    return photo


fig_dict = {'Pyplot Histogram' : PyplotHistogram}


sg.ChangeLookAndFeel('LightGreen')
figure_w, figure_h = 650, 650
# define the form layout
listbox_values = [key for key in fig_dict.keys()]
col_listbox = [[sg.Listbox(values=listbox_values, change_submits=True, size=(28, len(listbox_values)), key='func')],
               [sg.T(' ' * 12), sg.Exit(size=(5, 2))]]

col_multiline = sg.Column([[sg.Multiline(size=(70, 35), key='multiline')]])
col_canvas = sg.Column([[ sg.Canvas(size=(figure_w, figure_h), key='canvas')]])

layout = [[sg.Text('Matplotlib Plot Test', font=('current 18'))],
          [sg.Column(col_listbox), sg.Pane([col_canvas, col_multiline], size=(800,600))],
          ]

# create the form and show it without the plot
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI',resizable=True, grab_anywhere=False).Layout(layout)
window.Finalize()

canvas_elem = window.FindElement('canvas')
multiline_elem= window.FindElement('multiline')

while True:
    event, values = window.Read()
    # print(event)
    # show it all again and get buttons
    if event in (None, 'Exit'):
        break

    try:
        choice = values['func'][0]
        func = fig_dict[choice]
    except:
        pass

    multiline_elem.Update(inspect.getsource(func))
    plt.clf()
    fig = func()
    fig_photo = draw_figure(canvas_elem.TKCanvas, fig)


*** ERROR MESSAGE ***

/Users/thewarpdrive/PycharmProjects/sports/venv/bin/python "/Users/thewarpdrive/PycharmProjects/sports/breakdown graph options.py"
/Users/thewarpdrive/PycharmProjects/sports/breakdown graph options.py:5: MatplotlibDeprecationWarning: 
The matplotlib.backends.tkagg module was deprecated in Matplotlib 3.0 and will be removed in 3.2.
  import matplotlib.backends.tkagg as tkagg
*** Changing look and feel is not supported on Mac platform ***
Traceback (most recent call last):
  File "/Users/thewarpdrive/PycharmProjects/sports/venv/lib/python3.7/site-packages/matplotlib/backends/tkagg.py", line 27, in blit
    dataptr, colormode, bboxptr)
_tkinter.TclError: invalid command name "PyAggImagePhoto"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/thewarpdrive/PycharmProjects/sports/breakdown graph options.py", line 103, in <module>
    fig_photo = draw_figure(canvas_elem.TKCanvas, fig)
  File "/Users/thewarpdrive/PycharmProjects/sports/breakdown graph options.py", line 56, in draw_figure
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
  File "/Users/thewarpdrive/PycharmProjects/sports/venv/lib/python3.7/site-packages/matplotlib/backends/tkagg.py", line 28, in blit
    except tk.TclError:
AttributeError: '_tkinter.tkapp' object has no attribute 'TclError'

Process finished with exit code 1
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-07 23:30:42

在PySimpleGUI GitHub上有一个关于在PySimpleGUI中使用Matplotlib 3.1.1的问题。在这些问题中进行了报道和讨论。

https://github.com/PySimpleGUI/PySimpleGUI/issues/1620 https://github.com/PySimpleGUI/PySimpleGUI/issues/1713

请尝试安装Matplotlib 3.0.3。

您可能会发现,通过搜索项目的GitHub,您可以更快地获得答案。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57395326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档