Reputation:
I'm currently writing a Python Tkinter START and STOP button.
As it uses tkinter
when I click START the STOP button should appear in it's place. But to do this I need to use .destroy()
on the button. So to get around this I've done the following (see code blow); however it seems bulky and can't but feel I've over complicated it. Any suggestions would be great
def stop():
global start_button
try:
stop_button.destroy()
except NameError:
pass
print("Stopped. Hit GO to go again!")
start_button = Button(self.b, text="GO!", font="calibri, 18", command=started, fg="white", width=10)
start_button.pack(side=BOTTOM)
start_button.config(bg="green")
def started():
global stop_button
try:
start_button.destroy()
except NameError:
pass
print("Started. Hit ENTER to Stop!")
stop_button = Button(self.b, text="STOP!", font="calibri, 18", command=stop, fg="white", width=10)
stop_button.pack(side=BOTTOM)
stop_button.config(bg="red")
def first_start():
start.destroy()
started()
start = Button(self.b, text="START!", font="calibri, 18", command=first_start, fg="white", width=10)
start.pack(side=BOTTOM)
start.config(bg="green")
Upvotes: 0
Views: 66
Reputation: 36682
Here is a minimalist start/stop button that toggles its aspect and behavior when clicked. There is no need to destroy and replace buttons with such a toggling mechanism.
import tkinter as tk
def do_the_start_things():
# replace print with the things to do at start
print('starting now')
def do_the_stop_things():
# replace print with the things to do at stop
print('stopped!')
def toggle_start_stop():
if startstop['text'] == 'START':
startstop.config(text='STOP', fg='red')
do_the_start_things()
else:
startstop.config(text='START', fg='green')
do_the_stop_things()
root = tk.Tk()
startstop = tk.Button(root, text='START', command=toggle_start_stop, fg='green')
startstop.pack()
root.mainloop()
Upvotes: 2