简体   繁体   中英

How can I convert a value of a variable to StringVar or IntVar() to .get() it?

I want to get the value in a variable to place it to a text file. But I don't know what method should I do. I tried to convert it using the statement self.score = StringVar() or self.score = str(self.score) or self.score = IntVar() . But it results to what I am not expecting. I need help to fix this for my project. These piece of my codes may help you understand. Thank you.

        self.score = IntVar ()
        f = open('E.txt','a')
        f.write(self.name_ent.get() + '-' + self.score.get() + '\n')
        f.close()

self.score.get was error, because it's an int .

If you have an instance of IntVar , the .get() method returns an integer -- that's why you would use IntVar vs. StringVar . Like any other integer in python, you convert it with str :

score = str(self.score.get())

You get an error from trying to concatenate an integer with a string when forming the string to write to the file. This is the basis of your error. You can fix it by making the 'int' into a 'str' with a simple cast, str(some_int) . In your case, changing self.score.get() to str(self.score.get()) on line 3 will do the trick.

Alternatively, you could make self.score a StringVar() instead of an IntVar() on line 1, and then the problem on line 3 goes away. You still need to assign a value to the score, which you can do with self.score.set(value) .

By default, an IntVar() gets the value 0 and a StringVar() get the value of "" (the empty string). You can assign a value to an IntVar in at least two ways:

(1) on creation, with iv = IntVar(value=1)

and

(2) after creation, with iv.set(1)

The same goes for StringVar(), as well.

Changing self.score to a StringVar() from an IntVar() may seem a little strange at first, but just be aware of the difference in the default values.

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