Home > Software design >  started using Tkinter, is it possible to show/hide a Label with a Checkbutton?
started using Tkinter, is it possible to show/hide a Label with a Checkbutton?

Time:03-05

just looking for an example, I know its possible with buttons but I wanted to use the different states of a Checkbutton (onvalue and offvalue) to show and hide a label.

CodePudding user response:

You can achieve this using the check button property command to call a function every time user changes the state of the check button.

def show_hide_func():
    if cb_val == 1:
        your_label.pack_forget() 
        # if you are using grid() to create, then use grid_forget()

    elif cb_val == 0:
        your_label.pack()


cb_val = tk.IntVar()

tk.Checkbutton(base_window, text="Click me to toggle label", variable=cb_val , onvalue=1, offvalue=0, command=show_hide_func).pack()

For detailed documentation about the check button and other Tkinter widgets read here

CodePudding user response:

Simply use comman=function to run code which hide (pack_forget()/grid_forget()/place_forget()) and show it again (pack()/grid(...)/place(...)).

With pack() can be the problem because it will show it again but at the end of other widgets - so you could keep Label inside Frame which will not have other widgets. Or you can use pack(before=checkbox) (or simiar options) to put again in the same place (before checkbox)


Label inside Frame

import tkinter as tk
        
# --- functions ---

def on_click():
    print(checkbox_var.get())
    
    if checkbox_var.get():
        label.pack_forget()
    else:        
        label.pack()
    
# --- main ---

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

label = tk.Label(frame, text='Hello World')
label.pack()

checkbox_var = tk.BooleanVar()
checkbox = tk.Checkbutton(root, text="select", variable=checkbox_var, command=on_click)
checkbox.pack()

root.mainloop()   

use pack(before=checkbox)

import tkinter as tk
        
# --- functions ---

def on_click():
    print(checkbox_var.get())
    
    if checkbox_var.get():
        label.pack_forget()
    else:        
        label.pack(before=checkbox)
    
# --- main ---

root = tk.Tk()

label = tk.Label(root, text='Hello World')
label.pack()

checkbox_var = tk.BooleanVar()
checkbox = tk.Checkbutton(root, text="select", variable=checkbox_var, command=on_click)
checkbox.pack()

root.mainloop()   
  • Related