-1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Jakub Zak
  • 35
  • 6
  • check this thread https://stackoverflow.com/questions/3819354/in-tkinter-is-there-any-way-to-make-a-widget-invisible – Rafael Mar 04 '22 at 12:46

2 Answers2

2

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

quamrana
  • 37,849
  • 12
  • 53
  • 71
glory9211
  • 741
  • 7
  • 18
0

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()   
furas
  • 134,197
  • 12
  • 106
  • 148