Elle Nolan
Elle Nolan

Reputation: 399

Math with Tkinter IntVar()'s not working?

Essentially, I'm using Tkinter in python so that 1 is added to a variable when a button is pushed. I have another variable that is equal to my first variable times 10. When I hit the button that adds one to my original variable, the second variable (x*10) is not doubled. Take a look:

def add1():
    var1.set(var1.get() + 1)

def pringvar3()
    print(var3.get())

from tkinter import *
main = Tk()
button = Button(main, text="Add 1", command=add1)
button.pack()
button2 = Button(main, text="Print var3", command=printvar3)
button2.pack()

var1 = IntVar()
var1.set(1)
var2 = IntVar()
var2.set(10)
var3 = IntVar()
var3.set(var2.get() * var1.get())

What's wrong with that code? When I click the buttons, first 1 then 2, it still prints the variable as 10.

Upvotes: 0

Views: 754

Answers (2)

martineau
martineau

Reputation: 123403

tkinter IntVar objects don't update others that may have used their value at some point, so changing var1 won't automatically update var3 -- you have to make it happen explicitly.

Here's a simple demonstration based on your code that has an extra button added that does this when clicked:

def add1():
    var1.set(var1.get() + 1)

def updatevar3():
    var3.set(var2.get() * var1.get())  # recalulate value

def printvar3():
    print(var3.get())

from tkinter import *

main = Tk()
button = Button(main, text="Add 1", command=add1)
button.pack()
button2 = Button(main, text="Update var3", command=updatevar3)
button2.pack()
button3 = Button(main, text="Print var3", command=printvar3)
button3.pack()

var1 = IntVar()
var1.set(1)
var2 = IntVar()
var2.set(10)
var3 = IntVar()
var3.set(var2.get() * var1.get())  # set initial value

main.mainloop()
print('done')

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

You have a bunch of spelling errors and missing colons, but more importantly you don't change the value in the function callback. Remember, you only set the value once, you never actually reset it.

def printvar3():
    global var3
    var3.set(var2.get() * var1.get())
    print(var3.get())

Upvotes: 1

Related Questions