2013-05-21 28 views
0

我試圖使一個Python GUI寫入文件。一個簡單的測試,將看到,如果我能在文本框中得到用戶的輸入,然後讓他們點擊「創建」按鈕,並把它寫入文件。困難的Python + wxPython的

這裏是我當前的代碼:

import wx 
class gui(wx.Frame): 

def __init__(self,parent,id): 
    wx.Frame.__init__(self,parent,id,'YML Generator v1.0', size=(500,800)) 
    panel=wx.Panel(self) 
    wx.StaticText(panel, -1, "Name", (10,10)) 

    global ItemName 
    boxx = wx.TextCtrl(panel, -1, pos = (90, 10), size = (100, -1)) 
    ItemName=boxx.GetValue() 


    button=wx.Button(panel,label="Create!",pos=(100,100),size=(100,40)) 
    self.Bind(wx.EVT_BUTTON, self.writeStuff, button) 

def writeStuff(self, e): 
    yml = open("output.yml", "wb") 
    yml.write((ItemName) + " is what you entered.") 
    yml.close 
def closewindow(self,event): 
    self.Destroy() 

if __name__=='__main__': 
    app=wx.PySimpleApp()   #runs the program 
    frame=gui(parent=None,id=-1) #displays the program 
    frame.Show()     #shows the application 
    app.MainLoop()     #runs the application 

我加ITEMNAME作爲一個全球性的,因爲在此之前,我得到的錯誤有關ITEMNAME沒有被定義。

現在,我得到「是你進入了」寫入文件,但沒有用戶輸入的顯示出來。我究竟做錯了什麼?

回答

1

ItemName在textctrl創建時獲取textctrl的值,該值爲空字符串。你真正想要的是在按下按鈕時獲取值。要做到這一點,你可以保存自己的文本控件的引用,然後使用self.boxx.GetValue()來獲取你想要寫入文件的值。