Lotsofpeople
Lotsofpeople

Reputation: 23

My variable will not change in function

My variable is not changing and I know it's not changing because "1" is printed to the console. I'm trying to make the label increment when i press the button. However when I press the button, the variable stays at 1. What am I doing wrong? I've looked online for an answer but I cannot really find one that I can understand.

num = 0
import tkinter
box = tkinter.Tk()
v = tkinter.StringVar()
labels = tkinter.Label(box, textvariable = v)
labels.pack()

def numberz(num,v):
    num += 1
    v.set(num)
    print(num)

class MainWindow():
     box.title("My Stupid Program")
     buddon = tkinter.Button(box, text='PRESS ME', command = lambda:numberz(num,v))
     buddon.pack()

box.mainloop()

Upvotes: 1

Views: 68

Answers (1)

mementum
mementum

Reputation: 3203

num = 0
import tkinter
box = tkinter.Tk()
v = tkinter.StringVar()
labels = tkinter.Label(box, textvariable = v)
labels.pack()

def numberz(num,v):
    num += 1
    v.set(num)
    print(num)

class MainWindow():
     box.title("My Stupid Program")
     buddon = tkinter.Button(box, text='PRESS ME', command = lambda:numberz(num,v))
     buddon.pack()

box.mainloop()

You are changing the parameter num and not the global variable num

To change the global you need to specifically reference it. Notice how num is not passed in the lambda and now there is a global num in you function.

num = 0
import tkinter
box = tkinter.Tk()
v = tkinter.StringVar()
labels = tkinter.Label(box, textvariable = v)
labels.pack()

def numberz(v):
    global num
    num += 1
    v.set(num)
    print(num)

class MainWindow():
     box.title("My Stupid Program")
     buddon = tkinter.Button(box, text='PRESS ME', command = lambda:numberz(v))
     buddon.pack()

box.mainloop()

In any case, using globals should be restricted to very specific cases and not be of general use.

Upvotes: 1

Related Questions