问题描述:

I'm trying to make a Python GUI. A simple test that will see if I can get a user's input in a text box, then have them click a "Create" button and have it write to a file.

Here is my current code:

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

I added ItemName as a global because before that I was getting errors about ItemName not being defined.

Now, I get " is what you entered" written to the file, but no user input shows up. What am I doing wrong?

网友答案:

ItemName is getting the value of the textctrl at the time that the textctrl is created, which is an empty string. What you really want is to get the value at the time that the button is pressed. To do that you can save a reference to the textctrl in self, and then use self.boxx.GetValue() to fetch the value you want to write to the file.

相关阅读:
Top