创建图后wxpython面板缩小

时间:2019-03-21 13:17:37

标签: wxpython

我有一个非常简单的面板,您可以单击一个按钮并创建一个绘图(使用matplotlib),并将该绘图另存为.png在我的工作文件夹中。

创建绘图后,我的面板会缩小。有人知道为什么吗?

下面是代码,然后单击按钮前后的屏幕截图。

import wx
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class MyApp(wx.App):
    def __init__(self):
        super().__init__(clearSigInt=True)
        self.InitFrame()

    def InitFrame(self):
        frame = MyFrame(parent=None, title='My Frame', pos = (100,100))
        frame.Show()

class MyFrame(wx.Frame):
    def __init__(self, parent, title, pos):
        super().__init__(parent=parent, title=title, pos=pos)
        self.OnInit()

    def OnInit(self):
        panel = MyPanel(parent=self)

class MyPanel(wx.Panel):
    def __init__(self, parent):
        super().__init__(parent=parent)

        button = wx.Button(parent=self, label = "Create plot", pos = (20,80))
        button.Bind(event=wx.EVT_BUTTON, handler=self.onSubmit)

    def onSubmit(self,event):
        ActivityDF = pd.DataFrame({
            'Activity': ['A','B','C','D'],
            'Count': [10,20,30,40]
        })
        fig, ax = plt.subplots(1)
        ax.barh(ActivityDF['Activity'], ActivityDF['Count'])
        fig.savefig('Figure.png',bbox_inches='tight', facecolor="None")   



if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()

Before button clicked After button clicked

1 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出。

首先,您的代码有些复杂。不需要使用太多的类。

第二,如果您打算将matplotlib与GUI库一起使用,则需要导入后端,以便matplotlib在您要编写的应用程序中正常工作。

关于面板收缩的原因。我不太确定当matplotlib尝试在没有适当后端的情况下进行绘图时,可能会出错。

我简化了您的代码,并添加了一些注释。

import wx
import numpy as np

import matplotlib as mpl
## Import the matplotlib backend for wxPython
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

## Only one class is really needed in this case. There is no need to have 
## a class for the App, a class for the frame and a class for the panel
class MyWin(wx.Frame):
    def __init__(self, title, pos):
        super().__init__(parent=None, title=title, pos=pos)

        self.panel = wx.Panel(parent=self)
        self.button = wx.Button(parent=self.panel, label='Create plot', pos=(20, 80))

        self.button.Bind(wx.EVT_BUTTON, self.onSubmit)

    def onSubmit(self, event):
        x = np.arange(10)
        y = np.arange(10)
        ## This is to work with matplotlib inside wxPython
        ## I prefer to use the object oriented API
        self.figure  = mpl.figure.Figure(figsize=(5, 5))
        self.axes    = self.figure.add_subplot(111)
        self.canvas  = FigureCanvas(self, -1, self.figure)
        ## This is to avoid showing the plot area. When set to True
        ## clicking the button show the canvas and the canvas covers the button
        ## since the canvas is placed by default in the top left corner of the window
        self.canvas.Show(False)
        self.axes.plot(x, y)
        self.figure.savefig('Figure.png', bbox_inches='tight', facecolor='None')          

if __name__ == '__main__':
    app = wx.App()
    win = MyWin('My Frame', (100, 100))
    win.Show()
    app.MainLoop() 

希望这会有所帮助。