2013-10-08 11 views
0

我想將按鈕標籤打印到excel當我按下按鈕時,創建了excel文件,但我無法發送任何信息!可以幫助我嗎,或者我正在做這一切錯誤?wxpython如何將按鈕標籤顯示爲xlwt

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') 

回答

1

您有很多問題。首先,你不正確地綁定第二個按鈕。它應該像第一個一樣綁定。因此,將您的綁定代碼更改爲以下內容:

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

請注意,沒有等號了。

接下來在onButton方法中,需要將數據寫入Excel文件。 Python的「in」運算符沒有這樣做。它用於測試項目是否在集合中。有關更多信息,請參見docs

取而代之,您將需要使用xlwt的編寫方法將標籤寫入單元格。下面是一個完整的例子:

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() 

請注意,我也搬到了保存的OnClose功能我認爲這是它一個更好的地方。

+0

非常感謝,我可以問別的東西嗎?在相同的代碼中,如果我放置一個txtctrl,而不是從按鈕(Mem1)中創建另一個名稱,當我按下按鈕時,將名稱放入Excel中? – pap

+0

你是說你想從TextCtrl中獲取值並將其寫入Excel文件?如果你這樣做了,你只需要做一些事情,比如value = self.myTxtCtrl.GetValue(),然後像之前一樣寫出來給你想要的任何單元格 –

+0

再次感謝你,它現在正在工作 – pap