Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

python - Use start and stop function with same button in Tkinter

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 counter
    counter+=1
    label.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 tk

counter = 0
active_counter = False


def count():
    if active_counter:
        global counter
        counter += 1
        label.config(text=counter)
        label.after(1000, count)


def start_stop():
    global active_counter
    if button['text'] == 'Start':
        active_counter = True
        count()
        button.config(text="Stop")
    else:
        active_counter = False
        button.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 tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Counting Seconds")
        self.counter = 0
        self.active_counter = False
        self.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 += 1
            self.label.config(text=self.counter)
            self.label.after(1000, self.count)

    def start_stop(self):
        if self.button['text'] == 'Start':
            self.active_counter = True
            self.count()
            self.button.config(text="Stop")
        else:
            self.active_counter = False
            self.button.config(text="Start")


if __name__ == "__main__":
    App().mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...