With the help of the command button, I am able to disconnect the frame in Tkinter. But is there any way which helps to use the same button to start also?
import tkinter as tk
counter = 0
def counter_label(label):def count():global countercounter+=1label.config(text=counter)label.after(1000, count)count()root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
Suggestions will be grateful
You could simple use an if/else statement to check if the buttons text is Start
or Stop
then change a Boolean variable that controls the counter while also update the text on the button.
import tkinter as tkcounter = 0
active_counter = Falsedef count():if active_counter:global countercounter += 1label.config(text=counter)label.after(1000, count)def start_stop():global active_counterif button['text'] == 'Start':active_counter = Truecount()button.config(text="Stop")else:active_counter = Falsebutton.config(text="Start")root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
button = tk.Button(root, text='Start', width=25, command=start_stop)
button.pack()
root.mainloop()
Here is an OOP example as well:
import tkinter as tkclass App(tk.Tk):def __init__(self):super().__init__()self.title("Counting Seconds")self.counter = 0self.active_counter = Falseself.label = tk.Label(self, fg="green")self.label.pack()self.button = tk.Button(self, text='Start', width=25, command=self.start_stop)self.button.pack()def count(self):if self.active_counter:self.counter += 1self.label.config(text=self.counter)self.label.after(1000, self.count)def start_stop(self):if self.button['text'] == 'Start':self.active_counter = Trueself.count()self.button.config(text="Stop")else:self.active_counter = Falseself.button.config(text="Start")if __name__ == "__main__":App().mainloop()