Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change tkinter.StringVar into a integer type

Tags:

python

tkinter

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...

like image 811
Prasanta Roy Choudhury Avatar asked Jan 18 '26 12:01

Prasanta Roy Choudhury


1 Answers

I believe you need to "get" the value, otherwise you are trying to convert the class and not the value.

num = int(self.string.get())
like image 183
CodeCupboard Avatar answered Jan 21 '26 02:01

CodeCupboard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!