Get integer from a record

How to get integer type from Tkinter Entry widget?

If I try to get the value using variable_name.get() , it says it's str . If I try to change the type with int(variable_name.get()) , it says that int can only accept a string or a number.

Any help would be appreciated!

+4
source share
6 answers

In the end, I just initialized the variable as tk.IntVar() instead of tk.StringVar()

This way you don't need to specify it as an int, it will always be one, and the default value from the Entry element will now be 0 instead of

How I nevertheless approached him seems to be the easiest way and to avoid the need for a significant check, which you will need to do otherwise ...

+3
source

See the following example from Tkinter:

 v = StringVar() e = Entry(master, textvariable=v) e.pack() v.set("a default value") s = v.get() 

v is the StringVar class. try to do - int (str (variable.get ()))

But the class says variable.get should return a string to you.

Tkinter Entry has a default text value, which can be a problem if it is not an integer.

+1
source

I recently ran into this problem. I had a small method:

 newSave = self.EntryDict[key].get try: int(newSave) bool = True except ValueError: bool = False 

And I have an error that you describe that it can only take a string or a number. And my problem was that my .get did not have parentheses. After I put .get (), it worked. I think this may be your problem. But without seeing any code, I definitely do not know.

+1
source

I am also familiar with Tkinter, and I also had the same problem. I think the problem is that the default value for the Entry field is an empty string that cannot be converted to an integer.

I suggest you try adding an if statement to test this case:

 if variable.get() != '': other_variable = int(variable.get()) 

I understand that the question is old, but it worked for me, and I thought I would share it.

+1
source

When you say "variable" in your question, are you referring to an instance of StringVar or a reference to the widget itself?

If you have a widget link, you can use the get method to write. This will return a string that you can then pass to the int function:

 s = e.get() i = int(s) 

If this does not solve your problem, can you provide some kind of working code that accurately shows your problem?

0
source
 int(str(variable.get())) 

I try this and now it works.

0
source

All Articles