Reputation: 9541
Here's a Tkinter program with two modes to select from. Selecting 'blue' shows the blue frame and selecting 'green' shows a green frame.
The code that does this:
from tkinter import Tk, Frame, Button, ttk
class App():
def __init__(self, parent):
self.parent = parent
self.build_mode_selector_frame()
self.build_green_frame()
self.build_blue_frame()
def build_mode_selector_frame(self):
choices = ['blue','green']
self.mode_selector_frame = Frame(self.parent, width=300, height=50)
self.mode_selector = ttk.Combobox(self.mode_selector_frame, values=choices)
self.mode_selector.bind("<<ComboboxSelected>>", self.on_mode_changed)
self.mode_selector.grid(row=0, column=1)
self.mode_selector_frame.grid(row=0, column=0)
def build_blue_frame(self):
self.blue_frame = Frame(self.parent, width=300, height=50, background="blue")
self.blue_frame.grid(row=1, column=0)
#Button(self.blue_frame).grid(row=0, column=1)
def build_green_frame(self):
self.green_frame = Frame(self.parent, width=300, height=50, background="green")
self.green_frame.grid(row=1, column=0)
def show_blue_frame(self):
self.green_frame.grid_remove()
self.blue_frame.grid()
def show_green_frame(self):
self.green_frame.grid()
self.blue_frame.grid_remove()
def on_mode_changed(self, event):
selected_mode = self.mode_selector.get()
if selected_mode == 'blue':
self.show_blue_frame()
elif selected_mode == 'green':
self.show_green_frame()
root = Tk()
App(root)
root.mainloop()
This uses grid_remove()
and the grid()
to hide and show the elements.
But now if I add a button to the blue frame (uncomment the button line in the build_blue_frame
method above), grid_remove
seems to loose all the frame information like height and color as can seen in this gif.
Isn't grid_remove
supposed to remember all the configuration like height, background color etc, even after a button is added to the frame?
Upvotes: 2
Views: 519
Reputation: 386352
Isn't grid_remove supposed to remember all the configuration like height, background color etc, even after a button is added to the frame?
No. grid_remove
only remembers the data that grid
knows about (row
, column
, sticky
, etc). It doesn't remember anything about the attributes of the widget that is being removed.
The behavior you are seeing is how tkinter is designed to work. If a widget has children, it will grow or shrink to fit the children as best that it can. When you add the button to the blue frame, and because you didn't configure the blue frame to "stick" to the edges of the space it is in, the blue frame will shrink to fit the button.
As a general rule, you should almost always give a sticky
value when using grid
. You also should give at least one row and one column a weight
(with grid_rowconfigure
and grid_columnconfigure
) so that the children will use up an extra space.
Upvotes: 1