Search code examples
pythonuser-interfacetkinterframetogglebutton

tkinter Toggle button frame not hinding?


I want to make a frame toggle button with tkinter. but the code i have seems not to be functioning properly, this is what i mean my code seems be adding a frame but it does not delete that frame for some reason.

My code:

import tkinter as tk

def toggle():
    if toggle_btn.config('text')[-1] == 'add frame':
        x = tk.Frame(Tk,width=5,height=4,bg='black')
        x.pack()
        
    else:
        print('the frame is turned off')
        x.pack_forget()

Tk = tk.Tk()

toggle_btn = tk.Button(text="add frame", width=12, command=toggle)
toggle_btn.pack()

Tk.mainloop()

Solution

  • First of all, since the line if toggle_btn.config('text')[-1] == 'add frame': checks if the text of the button is "Add Frame" and you do not change the button text, the else part of the statement is never run. This can be fixed by changing the text of the button in the if statement. For example

     if toggle_btn.config('text')[-1] == 'add frame':
        x = tk.Frame(Tk,width=5,height=4,bg='black')
        toggle_btn.config(text='Delete Frame') #Changes the button text to 'Delete Frame'
        x.pack()
    

    Next, in the else statement the x is not defined, so that will throw an error. You can solve this simply by defining x outside the function, under Tk = tk.Tk() and then setting it as a global variable inside the toggle function like so.

     def toggle():
        global x
        if toggle_btn.config('text')[-1] == 'add frame':
          toggle_btn.config(text='Delete Frame') 
          x.pack()
        
        else:
          print('the frame is turned off')
          x.pack_forget()
    
     Tk = tk.Tk()
     x = tk.Frame(Tk,width=5,height=4,bg='black')
     ...
    

    Finally, you want to change the label back to 'add frame', when the frame has been deleted.

    import tkinter as tk
    def toggle():
        global x
        if toggle_btn.config('text')[-1] == 'add frame':
            toggle_btn.config(text='Delete Frame')
            x.pack()
            
        else:
            print('the frame is turned off')
            toggle_btn.config(text='add frame')
            x.pack_forget()
    
    Tk = tk.Tk()
    x = tk.Frame(Tk,width=5,height=4,bg='black')
    
    toggle_btn = tk.Button(text="add frame", width=12, command=toggle)
    toggle_btn.pack()
    
    Tk.mainloop()