Search code examples
pythonwxpython

Getting integer values from TextCtrl-box in wxPython


I am writing a wx application where values entered into TextCtrl-boxes are to be used as arguments to functions. This does not work, and I am starting to suspect it's because they are not properly read from the beginning. I have a window with some of these boxes, and use the GetValue() function to get values from them, like this:

var = tc1.GetValue()

This causes an error further down the line where the values are not considered to be integers, as they are supposed to be. I tried to correct this, using this line:

var = int(tc1.GetValue())

This gives the error message "Value error: invalid literal for int() with base 10:". I have no idea what this means.

What should I do?


Solution

  • You will get this error if you are trying to convert a non integer or a floating point number string to an integer. Your best bet is to put a try: - except: block to handle this error.

    Try something like this:

    import wx
    
    class Frame(wx.Frame):
        def __init__(self,parent,id):
            wx.Frame.__init__(self, parent, id,
                              'Read Number',
                              size = (200,150),
                              style=wx.MINIMIZE_BOX | wx.RESIZE_BORDER 
        | wx.SYSTEM_MENU | wx.CAPTION |  wx.CLOSE_BOX)
            self.initUI()
    
        def initUI(self):
    
            widgetPanel=wx.Panel(self, -1)
    
            Button = wx.Button(widgetPanel, -1, "Read", pos=(10,10), size=(30,30))
    
            self.Bind(wx.EVT_BUTTON, self.read, Button)
            Button.SetDefault()
    
            self.Text = wx.TextCtrl(widgetPanel, -1, "", pos=(10, 50), 
                                    size =(100,30), style=wx.TE_CENTER)
    
            self.Text.SetFont(wx.Font(20, wx.DECORATIVE, wx.NORMAL, wx.NORMAL))
    
        def read(self, event):
            try:
                var = int(float(self.Text.GetValue()))
                wx.MessageDialog(self, "You entered %s"%var, "Number entered", wx.OK | wx.ICON_INFORMATION).ShowModal()
            except:
                wx.MessageDialog(self, "Enter a number", "Warning!", wx.OK | wx.ICON_WARNING).ShowModal()
    
    
    if __name__ == "__main__":
        app = wx.App(False)
        frame = Frame(parent=None,id=-1)
        frame.Show()
        app.MainLoop()