Aug-24-2019, 06:53 AM
How would I make a Gui when a button is pressed it displays a message 'On' with a green background and when pressed again displays a message 'Off' with a red background?
def toggle_gui(): for tog in gui: if tog[0] == default_window: default_window = Label(the_window, bg = 'gray', height=3, width=25, bd=1, relief = 'raised', font =('times', 18, 'bold')) default_window.pack(fill=X, padx=5, pady=5) elif tog[1] == on_window: on_window = Label(the_window, text = 'ON', bg = 'green', height=3, width=25, bd=1, relief = 'raised', font =('times', 18, 'bold')) on_window.pack(fill=X, padx=5, pady=5) else: off_window = Label(text = 'OFF', bg = 'red', height=3, width=25, bd=1, relief = 'raised', font =('times', 18, 'bold')) off_window.pack(fill=X, padx=5, pady=5) toggle_button = Button(text = 'Toggle',bg = 'gray', height=1, width=15, relief = 'raised', font =('times', 10)) toggle_button.pack()How can I make this code go back and forth displaying on_window and off_window?
import tkinter as tk class MainFrame(tk.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.toggle_state = True self.create_controls() def create_controls(self): self.label = tk.Label(self, bg='gray', height=3, width=25, bd=1, relief='raised', font=('times', 18, 'bold')) self.label.pack(fill=tk.X, padx=5, pady=5) self.button = tk.Button(self, text='Toggle', bg='gray', height=1, width=15, relief='raised', font=('times', 10), command=self.on_button) self.button.pack(pady=15) self.pack() def on_button(self): if self.toggle_state: self.toggle_state_on() else: self.toggle_state_off() self.toggle_state = not self.toggle_state def toggle_state_on(self): self.label.configure(text='ON', bg='green') def toggle_state_off(self): self.label.configure(text='OFF', bg='red') if __name__ == '__main__': app = tk.Tk() main_frame = MainFrame() app.mainloop()
# Import the Tkinter functions from tkinter import * # Create a window the_window = Tk() # Give the window a title the_window.title('Toggle Changer') toggle_window = Label(the_window, bg = 'gray', height=3, width=25, bd=1, relief = 'raised', font =('times', 18, 'bold')) toggle_window.pack(fill=X, padx=5, pady=5) def toggle_gui(): for click in range(4): if click == 1: toggle_window.config (bg = 'green', text = 'ON') elif click == 2: toggle_window.config(bg = 'red', text = 'OFF') else: toggle_window.config (bg = 'green', text = 'ON') #Toggle Button Button(text = 'Toggle', command = toggle_gui, bg = 'gray', height=1, width=15, relief = 'raised', font =('times', 10)).pack()Why is the for loop not working? It only displays the else: and wont toggle to the OFF state