简体   繁体   中英

How to change tkinter.StringVar into a integer type

Actually, I am working on a python GUI project using Tkinter. So for that, I have to take some integer values from users. So I have just created a class and defined an instance attribute inside init constructor which takes input as String from the users. Apart from that, I have also created a method to convert the StringVar() into an integer using type conversion. But here I have stuck... an error is popped up as follows:

Traceback (most recent call last):
  File "E:\admin\Programs\Python\demo\attributes_conversion.py", line 26, in <module>
    root = myString(window)
  File "E:\admin\Programs\Python\demo\attributes_conversion.py", line 14, in __init__
    myString.conversion(self)
  File "E:\admin\Programs\Python\demo\attributes_conversion.py", line 17, in conversion
    num = int(self.string)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'StringVar'**

I know we have IntVar() in our hand but it returns 0 like this: demo page with IntVar()

here is my actual code:

from tkinter import *
class myString:
    def __init__(self, master):
        self.master = master
        self.string = StringVar()

        #label
        self.master.label = Label(master, text = "Num : ")
        self.master.label.grid(row = 0, column = 0, padx = 10, pady = 20)
        #entry
        self.master.num_entry = Entry(master, textvariable = self.string)
        self.master.num_entry.grid(row = 0, column = 1, padx = 10, pady = 20)

        myString.conversion(self)

    def conversion(self):
        num = int(self.string)
        print(num)


if __name__ == "__main__":
    window = Tk()
    window.geometry("200x150")
    window.resizable(0, 0)
    window.title("demo page")
    root = myString(window)
    window.mainloop()

I just want to store or convert my data into integer form. So if anyone has any solution please inform me. I will be thankful for your help. And yeah, I'm new to python, and stack overflow as well, if I did any mistake please forgive me...

我相信你需要“获得”价值,否则你试图转换类而不是价值。

num = int(self.string.get())

self.string isn't a number, it's an object. The first part of the problem is that you need to convert the value of the object to an integer. You can get the string that is stored in the object with the get method:

num = int(self.string.get())

The second problem is that you're calling this function a few milliseconds after you create the widget, way before the user has a chance to enter any data. Because the entry widget has nothing in it, you are trying to convert an empty string to an integer, and python doesn't know how to convert an empty string to an integer.

The first step is to remove this line:

myString.conversion(self)

Next, you need to decide when you want the function to be called. Is it when they press the return key? Is it when they click a button? If you want it to be called when they press the return key, you can "bind" the return key to a function so that the function is called when the key is pressed.

When you bind a function to a key, the function will be called with a parameter which represents the event. This parameter by convention is named event . Add the following line of code in place of the line you just removed:

self.master.num_entry.bind("<Return>", self.conversion)

Finally, modify your conversion function to accept this event object. The function doesn't have to use it, but it has to be prepared to accept it. In the following code, I define the default value of None so that the function can be used with or without the parameter.

def conversion(self, event=None):
    num = int(self.string.get())
    print(num)

ValueError: invalid literal for int() with base 10: - it is probably a dynamic error due of you call the conversion method in the class constructor (that is ok), but the self.string field does not have a suitable value at this moment. Try to do this:

class myString:               # Your existing code
def __init__(self, master):
    self.master = master
    self.string = StringVar()

    self.string.set('20')     # new line as an example

(And .get() as CodeCupboard adviced, of corse.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM