tomasvg
tomasvg

Reputation: 21

Changing a variable with a button (and a function) in Python Tkinter

I have the following code (it's partly in Dutch but I don't think that'll be an issue):

from tkinter import *

root = Tk()

woorden_en = ["mouse", "armadillo", "caterpillar", "buffalo", "dragonfly", "eel", "monkey", "lark", "manatee", "squid"]
woorden_nl = ["muis", "gordeldier", "rups", "buffel", "libelle", "paling", "aap", "leeuwerik", "zeekoe", "inktvis"]


nummer = IntVar()
nlWoord = StringVar()
enWoord = StringVar()
goedfout = StringVar()

def vorige():
    nummer -= 1
def volgende(): 
    nummer += 1
def controleer():
    print("Correct!")

secondGrid = Frame(root)
secondGrid.grid(row = 2, column = 1, columnspan = 2)
labelVertaling = Label(root, text="vertaling")
textVertaling = Entry(root, width=30, textvariable = nlWoord)
runVorige = Button(secondGrid, text="vorige", command = vorige)
runVolgende = Button(secondGrid, text="volgende", command = volgende)
runControleer = Button(secondGrid, text="controleer", command = controleer)
labelWoord = Label(root, text="woord")
labelWoordEn = Label(root, textvariable = enWoord)
labelNo = Label(root, textvariable = nummer)
Correct = Label(root, textvariable = goedfout)

Correct.grid(row = 2, column = 0)
labelNo.grid(row = 0, column = 0)
labelWoord.grid(row = 0, column = 1)
labelWoordEn.grid(row = 1, column = 1)
labelVertaling.grid(row = 0, column = 2)
textVertaling.grid(row = 1, column = 2)
runVorige.grid(row = 0, column = 0, sticky = "W")
runVolgende.grid(row = 0, column = 1, sticky = "W")
runControleer.grid(row = 0, column = 2, sticky = "W")

nummer.set(1)
enWoord.set(woorden_en[0])

root.mainloop()

The start value of 'nummer' is 1, as set in the 3rd to last line. This value needs to be changed with either -1 or +1 when clicking buttons 'vorige' (previous) or 'volgende' (next). The current code in the functions give me erros. Apparently I need to use set/get functions, but I cannot find out how to make it work. Any input or help would be appreciated.

Upvotes: 1

Views: 164

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

Just change your function to:

def vorige():
    nummer_val = nummer.get()
    nummer_val -= 1
    nummer.set(nummer_val)
def volgende():
    nummer_val = nummer.get()
    nummer_val += 1
    nummer.set(nummer_val)

This is because nummer is an IntVar() and you have to get the value of the variable using get() method. After that you have to assign it to a variable and then reduce/increase its value by 1. The first error you were getting was because the nummer was not globalized inside the function, but that was not the approach you should have taken, anyway this should fix your errors.

Upvotes: 1

Related Questions