Domanda

I want to print buttons label into excel when I press the button,the excel file created but I cant sent any information in it!Can somone help me,or I'm doing it all wrong?

import wx
from xlwt import *

w = Workbook()
ws1 = w.add_sheet('sheet 1')

class MyFrame(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Button to Excel', size = (300,300))
        panel=wx.Panel(self)

        extBtn = wx.Button(panel, label="Exit",pos=(100,150))
        extBtn.Bind(wx.EVT_BUTTON, self.onClose)

        btn = wx.Button(panel,label = "Mem 1",pos=(100,100))
        btn.Bind =(wx.EVT_BUTTON,self.onButton)

    def onClose(self, event):
        self.Close()

    def onButton(self,event):
        print self.GetLabel() in ws1

if __name__ == '__main__':
    app=wx.PySimpleApp()
    frame=MyFrame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()
    w.save('a.xls')
È stato utile?

Soluzione

You have a number of issues. First off, you bind the second button incorrectly. It should be bound the same way the first one. So change your binding code to the following:

btn.Bind(wx.EVT_BUTTON, self.onButton)

Note that there is no equals sign any more.

Next in the onButton method, you need to write data to the Excel file. Python's "in" operator does not do that. It is used to test if an item is in a collection or not. See the docs for more information.

Instead, you will want to use xlwt's write method to write the label to a cell. Here is a complete example:

import wx
from xlwt import *

w = Workbook()
ws1 = w.add_sheet('sheet 1')

class MyFrame(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Button to Excel', size = (300,300))
        panel=wx.Panel(self)

        extBtn = wx.Button(panel, label="Exit",pos=(100,150))
        extBtn.Bind(wx.EVT_BUTTON, self.onClose)

        btn = wx.Button(panel,label = "Mem 1",pos=(100,100))
        btn.Bind(wx.EVT_BUTTON, self.onButton)

    def onClose(self, event):
        w.save('a.xls')
        self.Close()

    def onButton(self,event):
        btn = event.GetEventObject()
        lbl = btn.GetLabel()
        ws1.write(0, 0, lbl)


if __name__ == '__main__':
    app=wx.PySimpleApp()
    frame=MyFrame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

Note that I have also moved the save to the onClose function as I think that's a better place for it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top