user2536262
user2536262

Reputation: 279

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?

Upvotes: 0

Views: 3158

Answers (3)

user2963623
user2963623

Reputation: 2295

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

Upvotes: 3

Yoriz
Yoriz

Reputation: 3625

Consider using a wx.lib.intctrl.IntCtrl

It provides a control that takes and returns integers as value, and provides bounds support and optional value limiting.

Upvotes: 1

heinst
heinst

Reputation: 8786

try

var = float(tc1.GetValue())

I dont know what the exact value is, if the number you are trying to cast is a decimal or not, but if it is this should work.

Also, if the string value you are trying to covert (tc1.GetValue()) is empty, you will get this error as well.

Upvotes: 0

Related Questions