Search code examples
pythontkintertkinter-button

How to pass a variable in and out of a tkinter widget


Using tkinter i have a widget for a button - pressing the button runs a function that calls upon num and increases it by 1, prints it and returns it

It calls upon num correctly,will add one to it and then print it however when it is pressed again num has reset suggesting something has gone wrong when returning it

Here is the sample of the code:

import tkinter as tk

num = 0

def increment(num):
    num = num + 1
    return num
    
window = tk.Tk()

button1 = tk.Button(
    text="Button1",
    command= lambda: num == increment(num)
)

button1.pack()
window.mainloop()

No errors occur - any advice / help is appreciated

pressing the button the first time should pass through num as 0 then increase it to 1. Then it should return num as 1 so that when pressed again num is passed though as 1 and then returned as 2. instead num is always passed through as 0


Solution

  • Python uses pass by value for variable of primitive types, like integer, for function argument. So updating that argument inside the function will not change the actual variable.

    For your case, you can use tk.IntVar() instead:

    import tkinter as tk
    
    def increment(num):
        num.set(num.get()+1)
        print(num.get())
    
    window = tk.Tk()
    
    num = tk.IntVar(value=0)
    
    button1 = tk.Button(
        text="Button1",
        command=lambda: increment(num)
    )
    button1.pack()
    
    window.mainloop()