Vittawat Laorungroj
Vittawat Laorungroj

Reputation: 99

how to show/hide widget in tkinter without moving other widget

I'm using grid_remove() and grid() command to hide/show the widget but the result is the other widget is move out of the original position.

How to hide/show the widget without moving widget

Example:

from tkinter import *
from tkinter import ttk


GUI = Tk()
GUI.title("myTest")
GUI.geometry("700x700")

Nameget = StringVar()
Priceget = StringVar()
Quantityget = StringVar()
Unitget = StringVar()
Partnumget = StringVar()

L_Partnum = ttk.Label(GUI, text = 'Part number')
L_Partnum.grid(row = 0, column = 0)

L_namme = ttk.Label(GUI, text = 'Name')
L_namme.grid(row = 0, column = 1)

L_quan = ttk.Label(GUI, text = 'Quantity')
L_quan.grid(row = 1, column = 2)
L_quan.grid_remove()

L_price = ttk.Label(GUI, text = 'Price')
L_price.grid(row = 3, column = 3)

E_partnum = ttk.Entry(GUI, textvariable = Partnumget)
E_partnum.grid(row = 1, column = 0)

E_namme = ttk.Entry(GUI,textvariable = Nameget)
E_namme.grid(row = 1, column = 1)

E_unit = ttk.Entry(GUI,textvariable = Unitget)

E_quan = ttk.Entry(GUI,textvariable = Quantityget)
E_quan.grid(row = 2, column = 2)
E_quan.grid_remove()

E_price = ttk.Entry(GUI,textvariable = Priceget)
E_price.grid(row = 4, column = 3)

I_check_vat = IntVar()

def d_check_vat_1():
    E_partnum.focus()
    if I_check_vat.get() == 1:
        L_quan.grid()
        E_quan.grid()
    elif I_check_vat.get() == 0:
        L_quan.grid_remove()
        E_quan.grid_remove()

C_CHECK_VAT = ttk.Checkbutton(GUI, text="click here to see the result", variable=I_check_vat, command=d_check_vat_1)
C_CHECK_VAT.grid(row = 5, column = 0)

GUI.mainloop()

Before clicking:

enter image description here

After clicking:

enter image description here

image with the expected output: enter image description here

Upvotes: 0

Views: 1729

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15088

The problem is grid() does not take up empty space by default, it gives the last empty row/col to the widget(if previous rows before it are empty).

So what you can do is, set minimum space for your column and row so that those space will remain empty, so change your function to:

def d_check_vat_1():
    E_partnum.focus()
    if I_check_vat.get():
        L_quan.grid(row=2, column=2)
        E_quan.grid(row=3, column=2)
        
        width = E_quan.winfo_reqwidth() # Get widget width
        height = L_quan.winfo_reqheight() # Get widget height
        
        GUI.rowconfigure(2,minsize=height) # Now apply the values
        GUI.rowconfigure(3,minsize=height)
        GUI.columnconfigure(2,minsize=width)
    
    else:
        L_quan.grid_remove()
        E_quan.grid_remove()

Now its dynamic as well, it takes the width of widget and applies that as the minsize of that row so that row will have that empty space.

Upvotes: 2

Related Questions