Home > other >  Is there a way to toggle/hide/show tkinter buttons
Is there a way to toggle/hide/show tkinter buttons

Time:12-24

I am making blackjack in tkinter and instead of placing buttons over the existing buttons i want to toggle them when, say a new game.

CodePudding user response:

There are many ways of doing this. One option (I think he simplest one) is to get your buttons in a frame that you can pack and unpack using pack and packing_forget. In this case you need another frame where your button frame is the only packed widget, so the buttons will appear in the same place when you pack them again. You can also resize the frame so things on it will become invisible when it becomes really small. Another option is to use a canvas where your buttons are canvas objects. You can them move or hide them as you want.

CodePudding user response:

In addition to @Flavio Moraes answer you can use grid_remove() method to save a widget before remove it (if you don't need it anymore you can also destroy() the widget:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("300x80")
root.title('Toogle button')

def crea():
    """ restore button """
    btn.grid(column=0, row=0, sticky='nsew')
        
def remo():
    """remove button"""
    btn.grid_remove()
    
    
def btn_off():
    btn.after(1500, remo)
    btn.after(3000, crea)

btn = ttk.Button(root, text='Hide', command=btn_off)
btn.grid(column=0, row=0, rowspan=2, sticky='nsew')


root.columnconfigure(0, weight=3)
root.mainloop()
  • Related