Oct-16-2018, 08:24 AM
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.
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.