Create a Basic Counter using Button Widget

 import tkinter as tk


# Create the main application window

root = tk.Tk()

root.title("Counter")


# Initialize counter variable

counter = 0


# Function to increment the counter

def increment_counter():

    global counter

    counter += 1

    label.config(text=str(counter))


# Function to decrement the counter

def decrement_counter():

    global counter

    counter -= 1

    label.config(text=str(counter))


# Button to increment the counter

increment_button = tk.Button(root, text="Increment", command=increment_counter)

increment_button.pack()


# Button to decrement the counter

decrement_button = tk.Button(root, text="Decrement", command=decrement_counter)

decrement_button.pack()


# Label to display the counter value

label = tk.Label(root, text=str(counter))

label.pack()


# Run the Tkinter event loop

root.mainloop()



Comments