Reputation:
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.
I worked and after much trial and error, I got it working as follows:
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()
I was wondering if it was possible to encapsulate the GUI code into a class Countergui like this:
from tkinter import *
from tkinter.ttk import *
# Write your code here
def main():
"""Set up the GUI and run it"""
window = Tk()
counter_gui = CounterGui(window)
window.mainloop()
main()
Additional Information: Recreate the program but encapsulate the GUI code in a class CounterGui. This program should have all the same functionality as the program in Question 4: The program 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. The counter should start at zero.
Upvotes: 1
Views: 128
Reputation: 1991
It is best to create a class for the counter, and further, best not to create globals
if you can avoid it.
class Counter(object):
def __init__(self, start=0):
self.count = start
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
It is best not to create a mixed use class - this class will take care of handling the storage, increment and decrement of your values.
You can then create a separate class to draw the buttons and basic component interface and pass it an instance of your Counter
class
Good luck
Upvotes: 1