1

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

Tytey
  • 13
  • 2

2 Answers2

0

This is the working code.

import tkinter as tk

num = 0

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

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

button1.pack()
window.mainloop()

This code uses the global keyword inside the increment() function to modify the global variable num directly, while the original code creates a new local variable named num inside the function, which does not affect the value of the global variable num. Also you were using the comparison operator "==" instead of the assignment operator "=".

Also if you want to do this without global variables, look into object oriented Tkinter, this may be more useful for you:

import tkinter as tk

class Counter:
    def __init__(self):
        self.num = 0
        
        self.window = tk.Tk()
        
        self.button1 = tk.Button(
            text="Button1",
            command=self.increment
        )
        
        self.button1.pack()
        
        self.window.mainloop()
    
    def increment(self):
        self.num += 1
        print(self.num)

counter = Counter()
# waits until the counter window is closed, then returns the result
print("Counter result:", counter.num)
Brock Brown
  • 956
  • 5
  • 11
0

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()
acw1668
  • 40,144
  • 5
  • 22
  • 34