Python Forum
Python Counter - Convert to a Class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Counter - Convert to a Class
#1
I need to create a program that has two buttons and a label that displays the current value of a counter. One button, bearing the text +1, should add one to the counter, while the other button, labelled -1, should subtract one from it (there is no minimum and maximum value). The counter should start at zero.

When designing the functions for each button, we need to get the current value, change the value depending on the button press, then set the new value.

Hint: as in the button example above you will need two global variables: one for the current count and one for the label widget.

Here's what I could come up with so far.

from tkinter import *
from tkinter.ttk import *

def plus_one():
    """Increments counter by 1 """
    global click_counter, counter_label

    click_counter += 1
    counter_label["text"] = str(click_counter)

def minus_one():
    """Reduces counter value by 1"""
    global click_counter, counter_label

    click_counter -= 1
    counter_label["text"] = str(click_counter)

def main():
    """Program"""
    global click_counter, counter_label
    click_counter = 0
    window = Tk()

    counter_label = Label(window, text=str(click_counter))
    counter_label.grid(row=0, column=0)

    plus_one_button = Button(window, text="+1", command=plus_one)
    plus_one_button.grid(row=2, column=0)
    minus_one_button = Button(window, text="-1", command=minus_one)
    minus_one_button.grid(row=2, column=1)

    window.mainloop()

main()
Now, I am trying to encapsulate the GUI code section into a class as follows:

from tkinter import *
from tkinter.ttk import *

# Class code to be inserted here


def main():
    """Set up the GUI and run it"""
    window = Tk()
    counter_gui = CounterGui(window)
    window.mainloop()

main() 
Please help.
Reply
#2
you need to learn the basics of classes.
I would expect the 'classes basic' post will contain enough information to complete your task, but I include all, if you wish (or need) to read further:
classes basic
Class Intermediate: Inheritance
Class Intermediate: Operator Overloading
Classes [advanced]: Dependent attributes (and Descriptors)
Classes [advanced]: Descriptors (managed attributes)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  newbie in python. odd ,even & Zero counter. output not crrect khan001 2 3,656 Dec-06-2017, 04:56 PM
Last Post: gruntfutuk
  How do you compute tf-idf from a list without using the counter class syntaxkiller 8 5,218 Dec-01-2017, 05:24 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020