Jan-22-2020, 09:08 AM
I have written a program (Python V3.7.4) for a games timer and there is a bug in it that I have not been able to fix. It contains one instance of class 'ButtonClass' and (potentially) multiple instances of 'DisplayClass'. This is so that I can have multiple clock displays set to different timezones, yet all working as one clock. Because it is a large and complex program, I have produced a much simplified example to show the problem (see attached). When I press the 'reset' button, the counter does not reset to zero. I have studied other questions relating to linking of classes, and this is how far it has got me. As an aside, when I produced a variant of this, where everything was in just one class, it worked as I wanted. I suspect that the problem may be one of scope of my variable 'old_day', but cannot see how to fix it. I also tried another variant, where DisplayClass is called from within the initialisation of ButtonClass, but that would not reset either. Can someone point out how to put it right. Thanks.
from tkinter import * from time import strftime class ButtonClass: def __init__(self, master): master.geometry("500x200") master.resizable(0, 0) frame1 = Frame(master) frame1.pack() resetbutton = Button(frame1, text="Reset", font=('Courier', 10, 'bold'), relief=RAISED, width=10, command=self.reset_counter) resetbutton.grid(row=1, column=2) def reset_counter(self): print("reset_counter method") DisplayClass.reset(self) class DisplayClass: def __init__(self, master, ButtonClass): old_day = 0 self.old_day = old_day frame2 = Frame(master) frame2.pack() label1 = Label(frame2, font=('Courier', 10, 'bold'), relief=RAISED, width=10, height=5) label1.grid(row=1, column=1, padx=1, pady=1) self.counter_label(label1) def counter_label(self, label): print("this is the counter_label method") print("old day = ",self.old_day) def counter(): print("This is counter method") self.old_day += 1 print("old day = ",self.old_day) string = str(self.old_day) label.config(text=string) label.after(2000, counter) counter() def reset(self): print("this is the reset method") #self.old_day = 0 DisplayClass.old_day = 0 def main(): root = Tk() a = ButtonClass(root) b = DisplayClass(root, a) print("End") root.mainloop() if __name__ == '__main__': main()