Search code examples
pythonpython-3.xuser-interfacetkintercustomtkinter

Counter always reseting


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()

Solution

  • 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)