Counter always reseting

Question:

I have been trying to make a Python script that counts how many people are coming and going from your store.

How it is supposed to work:

  • you have a +1, and a -1 buttons;
  • when someone comes in, you click +1, and when someone goes away, you do -1.

What is wrong: when I click +1 it changes the counter from 0 to 1, but if I click it again, it doesn’t change to 2.

The same thing happens when I do -1.

Here is the code:

import tkinter as tk
import customtkinter as ctk

app  = ctk.CTk()
app.title('People Counter')
app.geometry('300x180')
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
Label = ctk.CTkLabel
StringVar = ctk.StringVar

counter = 0

l1 = tk.Label(app, text=counter)


def pl1():
    l1.config(text=counter + 1)


def mi1():
    l1.config(text=counter - 1)


p1 = ctk.CTkButton(master=app,text = '+1', command=pl1, height=5 , width=30)
p1.place(relx=0.3, rely=0.5, anchor=tk.CENTER)

m1 = ctk.CTkButton(master=app, text="-1", command=mi1, height=5 , width=30)
m1.place(relx=0.7, rely=0.5, anchor=tk.CENTER)

l1.pack()

app.mainloop()
Asked By: Darky

||

Answers:

You only update the text on the label. You don’t actually change the value of the counter variable. Try this:

def pl1():
    global counter
    counter += 1
    l1.config(text=counter)


def mi1():
    global counter
    counter -= 1
    l1.config(text=counter)
Answered By: Selcuk

Another option is to create a simple Counter class with methods add() and sub(). It will help you avoid the use of global variables. I also added a test to prevent the counter get negative numbers.

import tkinter as tk
import customtkinter as ctk

app = ctk.CTk()
app.title('People Counter')
app.geometry('300x180')
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
Label = ctk.CTkLabel
StringVar = ctk.StringVar


class Counter():
    def __init__(self):
        self.count = 0

    def add(self):
        self.count += 1
        counter_display.config(text=self.count)
        return self.count

    def sub(self):
        self.count -= 1
        if self.count < 0:
            self.count = 0
        counter_display.config(text=self.count)
        return self.count

    def __repr__(self):
        return str(self.count)


counter = Counter()

counter_display = tk.Label(app, text=counter)

add_one = ctk.CTkButton(
    master=app,
    text='+1',
    command=counter.add,
    height=5,
    width=30
)
add_one.place(relx=0.3, rely=0.5, anchor=tk.CENTER)

sub_one = ctk.CTkButton(
    master=app,
    text='-1',
    command=counter.sub,
    height=5,
    width=30
)
sub_one.place(relx=0.7, rely=0.5, anchor=tk.CENTER)

counter_display.pack()

app.mainloop()
Answered By: accdias