hi,

Please could you help me with displaying the png image file I am saving. I want it to display just after it is saved so within the same function onPLOT

import wx
import cx_Oracle
import datetime
import wx.grid
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker 
import cStringIO

class MainWindow(wx.Panel):
    def __init__(self,parent,id):
        wx.Panel.__init__(self,parent,id)

        self.background = wx.Panel(self)
          
        lblHeader = wx.StaticText(self,-1,label='PERF CALCULATION',pos=(100,10),style=wx.ALIGN_CENTER)
        font = wx.Font(15,wx.BOLD,wx.NORMAL,wx.ITALIC)
        lblHeader.SetFont(font)
               
        lblComboBox = wx.StaticText(self,-1,label='Fund_id:',pos=(5,65))
        self.Fund_id = wx.ComboBox(self, -1, pos=(120,60), size=(100,25), choices=['gip'], style=wx.CB_DROPDOWN)

        lblStartDate = wx.StaticText(self, -1, label='Start_date:', pos=(5,105))
        self.StartDate = wx.TextCtrl(self, -1, pos=(120,100), size=(100,25))

        lblEndDate = wx.StaticText(self,-1,label='End_date:',pos=(5,145))
        self.EndDate=wx.TextCtrl(self,-1,pos=(120,140),size=(100,25))

        self.myButton = wx.Button(self, label='Execute', pos=(50,200), size=(100,35))
        self.Bind(wx.EVT_BUTTON,self.OnExecute,id= self.myButton.GetId())
        
        self.myButton = wx.Button(self, label='Display', pos=(200,200), size=(100,35))
        self.Bind(wx.EVT_BUTTON,self.OnDisplay,id= self.myButton.GetId())
    
        self.Exit = wx.Button(self, label='Exit', pos=(350,200), size=(100,35))
        self.Bind(wx.EVT_BUTTON, self.OnExit, id=self.Exit.GetId())

        self.Clear = wx.Button(self,label='Clear',pos=(500,200),size=(100,35))
        self.Bind(wx.EVT_BUTTON,self.OnClear,id=self.Clear.GetId())

        self.Export = wx.Button(self,label='CSV Export',pos=(650,200),size=(100,35))
        self.Bind(wx.EVT_BUTTON,self.OnExport,id=self.Export.GetId())

        self.Plot = wx.Button(self,label='Plot Return',pos=(800,200),size=(100,35))
        self.Bind(wx.EVT_BUTTON,self.OnPlot,id=self.Plot.GetId())

        font1 = wx.Font(8,wx.MODERN,wx.NORMAL, wx.NORMAL, False)


        self.transferArea = wx.TextCtrl(self, pos=(20,250),size= (1200,600),style = wx.TE_READONLY |wx.TE_LEFT | wx.TE_MULTILINE)
        self.transferArea.SetFont(font1)
    
        self.dbresult = ''
    
    def OnExecute(self,event):
       # try:
        if self.dbresult != '':
           return self.result
        else:
        #   All the rest below
            connection = cx_Oracle.connect('/DB)
            cursor = connection.cursor()
            fund_id = self.Fund_id.GetValue()
            print fund_id
            start_date = self.StartDate.GetValue()
            print start_date
            end_date = self.EndDate.GetValue()
            print end_date
            sql ="""MY SQL"""% (str(start_date),str(end_date),str(fund_id))
            
            cursor.execute(sql) 
            
            result = []
            for line in cursor:
                line = [str(entry) for entry in line]
                result.append(line)
                
                
            self.result = result


    def OnDisplay(self,event):
        
        myheaderformat = "%-20s %-22s %-22s %-15s %-20s %13s %15s %12s"
        myreportformat = "%-20s %-22s %-22s %-15s %-20s %13s %15s %12s"
        
        header = myheaderformat % ('DATE','FUND_ID','STRATEGY','INSTRUMENT','SECTOR','PNL$M','NAV','PERFPCT')
        self.transferArea.WriteText(str(header+"\n"))
        
        for i in range(len(self.result)):
            myline = myreportformat % (self.result[i][0][0:-9],self.result[i][1],self.result[i][2],self.result[i][3],self.result[i][4],self.result[i][5],self.result[i][6],self.result[i][7])

            
            self.transferArea.WriteText(myline+"\n")


    def OnExit(self,event):
        self.Destroy()  # Close the frame.

    def OnClear(self,event):
        self.transferArea.Clear()

    def OnExport(self,event):
        filepath = 'gui.csv'
        csv_writer=csv.writer(open(filepath,"w"))
        title = ['DATE','FUND_ID','STRATEGY','INSTRUMENT','SECTOR','PNL$M','NAV','PERFPCT']
        csv_writer.writerow(title)
        for line in self.result:
            line = [str(entry)for entry in line]
            csv_writer.writerow(line)\


    def OnPlot(self,event):
        r = []

        d={}

        for line in self.result:
            line=tuple(line)
            r.append(line)
        r.sort()

        for line in r:
            key=line[0]
            d[key]=line[8]

        plot_list = [(i,d[i]) for i in d.keys()]
        
        plot_list.sort()

        x=[]
            
        for line in plot_list:
            dates = datetime.datetime.strptime(line[0], '%Y-%m-%d %H:%M:%S')
            x.append(dates) # append the dates to the x axis
                
        date = np.asarray(x)
                
        count=0
                
        y=[]
                
        for line in plot_list:
            count+=float(line[1])
            y.append(count) # append the results to y axis
        
        for line in x:
            print line
        
        for line in y:
            print line
            
        perf = np.asarray(y)
                    
        fig = plt.figure()
    
        ax = fig.add_subplot(111)
                    
                    #add some labels
        ax.set_ylabel('PERF IN %')
        ax.set_xlabel('Date')
        ax.set_title('Percentage Performance')
                    
        ax.plot(x,y,'s-')    # plot x y 
        fig.autofmt_xdate()
        
        #plt.show()
        plt.savefig("test.png")

        perf_plot = 'test.png'
             

app = wx.App()
frame = wx.Frame(None,-1,"TITLE")
MainWindow(frame,-1)
frame.Show(1)
app.MainLoop()

Recommended Answers

All 5 Replies

Try something like this ...

#plt.show()
        plt.savefig("test.png")

        # create an internal image
        image = wx.Bitmap("test.png")
        # show the image as static bitmap
        wx.StaticBitmap(self, wx.ID_ANY, image)

        perf_plot = 'test.png'

Also correct the error in line 63, needs a closing '

Try something like this ...

#plt.show()
        plt.savefig("test.png")

        # create an internal image
        image = wx.Bitmap("test.png")
        # show the image as static bitmap
        wx.StaticBitmap(self, wx.ID_ANY, image)

        perf_plot = 'test.png'

Thanks for ur response..Using this method seems to create half the image in the main panel and not in a new window hence my buttons being over the image etc.

Thanks for ur response..Using this method seems to create half the image in the main panel and not in a new window hence my buttons being over the image etc.

In this case you have to create a new parent frame (size it for the image) for wx.StaticBitmap(frame, wx.ID_ANY, image)

Would be nice if I could test it out, but I simply don't have all the required modules and data files.

In this case you have to create a new parent frame (size it for the image) for wx.StaticBitmap(frame, wx.ID_ANY, image)

Would be nice if I could test it out, but I simply don't have all the required modules and data files.

No joy still unfortunately. Seems like it is doing something but no new frame pops up and displays the image.

Thanks for ur response..Using this method seems to create half the image in the main panel and not in a new window hence my buttons being over the image etc.

Got it to work now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.