I'd like a to make a scrolled Tkinter textbox that fills the maximum alloted space. I have it working kind of...
For some reason when I stretch the window the text widget is fine; However, the scroll bar gets a ton of padding on the x axis.
The second problem is when I shrink the window the scrollbar goes of the screen.
Anyone know the solutions to these two programs?
snippet:
self.Fr = Tkinter.Frame(self, width=self.Wi, height=self.He)
self.Fr.pack(side='right', fill='both', expand='yes')
self.Te = Tkinter.Text(self.Fr, font=self.Fo, fg=self.FG, bg=self.BG,
selectforeground=self.SFG,
selectbackground=self.SBG,
insertbackground=self.IBG, wrap='word',
undo=True, maxundo=100)
#self.Te.grid(column=0, row=0, sticky='NSEW')
self.Te.pack(side='left', fill='both', expand='yes')
self.Sc = Tkinter.Scrollbar(self.Fr, elementborderwidth=1)
#self.Sc.grid(column=1, row=0, sticky='NSEW')
self.Sc.pack(side='right', fill='both', expand='yes')
self.Te.configure(yscrollcommand=self.Sc.set)
self.Sc.configure(command=self.Te.yview)
Your scrollbar gets all the padding because you use fill='both'. Even though it's a vertical scrollbar you asked it to take up extra space along the x axis, which results in the padding since the scrollbar itself won't stretch to make a wide scrollbar. You want vertical scrollbars to only fill in the Y direction and horizontal ones to fill in the X direction.
As to the scrollbar going off screen, that's a little complex to explain but it has a simple solution.
The problem is this: if you shrink a window managed by pack to a point where it's smaller than that required by the widgets inside, it starts clipping widgets. The way this works is it processes the widgets in order, laying out the window and then allocating any left-over space for any remaining widgets. This means that if a widget early in the order takes up all the remaining visual space, any later widgets will not appear.
The "order" mentioned above is the order of the packing list. Specifically, the order in which items were packed. So, if you pack the text widget and then the scrollbar Tk will first lay out the text widget, and any remaining space will be allocated to the scrollbar. IF you had packed the scrollbar first, it would get laid out and any remaining space would be given to the text widget.
It all sounds very complex, but the cool thing is that if you pack things in the proper order it all just works.
The general rule of thumb, then, is to make sure the last widget you pack is the one with expand set to true. This is your "elastic" widget. That way all the fixed-size widgets will take up whatever space they need first, and your "elastic" widget will take up all that is left.
There is another solution which is to give your text widget a requested width and height of one. With that, when the packer initially allocates space it will allocate only a small amount of space. Thus, when the window shrinks the text widget will shrink until it gets down to that tiny size. This isn't very practical though, since one of the great features of pack is that you can give all widgets their natural size (or they assume their natural size based on their content in the case of buttons and labels) and the packer does all the work. If you set the width and height to one, your initial window (unless explicitly set to a larger size) will be rather small.
This behavior is all documented in the man page for pack, though you have to read it really closely to fully grasp this behavior.
Related
I want to eliminate strange extra space that seems to resist any size tweaking in my layout when using grid() alone, but calling in pack() sometimes make things worse: The GUI simply disappear entirely!
I read a few eye-opening layout answers from #Bryan Oakley such as:
When to use pack or grid layouts in tkinter?
and
Tkinter: grid or pack inside a grid?
but when I get down to write my own stuff, I still often have troubles.
My understanding:
I must have a Frame to fill the root window, otherwise there'd be no hope to fill the extra space in the window, however I tweak widgets alone.
For all the child widgets sitting inside a common parent Frame, I must use either pack() or grid() but not both.
When using grid() in a Frame, it's mandatory to specify Frame.grid_rowconfigure() and .grid_columnconfigure() with non-zero weight arguments. Otherwise, nothing would show up.
It's thus possible to have the main Frame using pack(), but its immediate child Frames all using grid(); Inside each of these child Frames on the grid, we could then pack() their own child widgets. In other words, we could interleave grid() and pack() by "regions" or container hierarchy levels, but never mix them in the same container: The only restriction.
By a careful weight design, I could fill a horizontal space in a parent Frame with a child Frame full of widgets laid out horizontally, e.g., all widgets use grid(sticky='nsew'), and the child Frame uses pack(side='top', fill='both', expand=True).
If my understanding was correct, then I could never figure out why #5 couldn't work for me, e.g., there is always unused extra space towards the right end of my horizontal child Frame inside the main Frame of the root window.
UPDATE 2
I figured it out. #5 didn't work for me because I forgot to specify .grid_columnconfigure(0, weight=1) in the main Frame before using grid(). My bad! Case closed.
UPDATE
I'm on macOS High Sierra, running python 3.6.4 Homebrew.
In what cases Tkinter's grid() cannot be mixed with pack()?
In all cases, you cannot use both grid and pack for widgets that have a common master. Within a master, all direct children must use the same geometry manager. Within an application as a whole, you can mix pack and grid all you want as long as you follow that one rule that you can't use them both for widgets that have the same parent.
I must have a Frame to fill the root window, otherwise there'd be no hope to fill the extra space in the window, however I tweak widgets alone.
This is not correct. You can easily fill all of the space in the root window without using a frame.
For all the child widgets sitting inside a common parent Frame, I must use either pack() or grid() but not both.
That is correct. The third option is to use place, though it's rarely the best choice.
When using grid() in a Frame, it's mandatory to specify Frame.grid_rowconfigure() and .grid_columnconfigure() with non-zero weight arguments. Otherwise, nothing would show up.
That is not true -- configuring rows and columns to have a non-zero weight isn't mandatory. It's usually a best practice, but it's not required in order for widgets to show up. The weight only applies to how grid manages extra space. Any widgets with a non-zero size should appear whether you use weights or not.
It's thus possible to have the main Frame using pack(), but its immediate child Frames all using grid()
Correct.
By a careful weight design, I could fill a horizontal space in a parent Frame with a child Frame full of widgets laid out horizontally, e.g., all widgets use grid(sticky='nsew'), and the child Frame uses pack(side='top', fill='both', expand=True).
That is correct.
My code is the following:
import tkinter as tk
#setting up window.
root = tk.Tk()
root.title("CSV Maker")
root.geometry("600x300")
#setting up frames.
leftFrame = tk.Frame(root, bg="red", width=300, height=300)
rightFrame = tk.Frame(root, bg="blue", width=300, height=300)
#placing frames on window.
leftFrame.grid(row=0, column=0)
rightFrame.grid(row=0, column=1)
#setting up labels.
inputPathLabel = tk.Label(leftFrame, text="Input File Path:")
#placing labels on frames.
inputPathLabel.grid(row=0, column=0)
root.mainloop()
When I remove the label I get the following:
Without label
However when I leave the code as it is below (with a label), I get a completely different result. It seems as if the frame was resized to another size than the one that I selected and the color is gone. Why is this?
With label
That is simply how tkinter was designed to work. When you use pack or grid, frames (or any other widget) will shrink or expand to try to fit all of its contents.
99.9% of the time, this is the behavior you want. Tkinter is really good at making GUIs the appropriate size.
From the official documentation for grid:
The grid geometry manager normally computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions. This causes geometry information to propagate up through a window hierarchy to a top-level window so that the entire sub-tree sizes itself to fit the needs of the leaf windows. However, the grid propagate command may be used to turn off propagation for one or more masters. If propagation is disabled then grid will not set the requested width and height of the master window. This may be useful if, for example, you wish for a master window to have a fixed size that you specify.
From the documentation for pack:
The packer normally computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions. This causes geometry information to propagate up through a window hierarchy to a top-level window so that the entire sub-tree sizes itself to fit the needs of the leaf windows. However, the pack propagate command may be used to turn off propagation for one or more masters. If propagation is disabled then the packer will not set the requested width and height of the packer. This may be useful if, for example, you wish for a master window to have a fixed size that you specify.
Notice that place doesn't have the same behavior. From the place documentation:
Unlike many other geometry managers (such as the packer) the placer does not make any attempt to manipulate the geometry of the master windows or the parents of slave windows (i.e. it does not set their requested sizes). To control the sizes of these windows, make them windows like frames and canvases that provide configuration options for this purpose.
I've always found the pack() geometry manager quite ambiguous in terms of how it acts when widgets are added.
Here I have a simple code for creating a new frame within a much bigger parent frame. The frame size has been set to 300x300. The problem is that if I create a label with the pack() geometry manager within this frame, it will suppress the original frame size. Basically the frame will become as big as is the label.
If I use the place() geometry manager, then there is no problem and the frame stays at the original 300x300 size.
The question is - why does packing a label within the frame affects its size? And then what is the best way to avoid this problem and have everything fixed at the size as they are set?
class MainRightFrame(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.place(x=600, y=0)
self.config(height=300, width=300, bg='green')
label = Label(self, text='Left Frame')
label.place(x=10, y=10) # OPTION 1
# label.pack() # OPTION 2
why does packing a label within the frame affects its size?
Because that is how the packer is designed to work. It will shrink or grow to fit its contents, which is what you want 99.99% of the time.
For the canonical documentation for how pack works, see the official tcl/tk documentation here:
The packer algorithm
And then what is the best way to avoid this problem and have everything fixed at the size as they are set?
The best wait to avoid this "problem" is to use place. However, the way both pack and grid works makes it much easier then using place to create a responsive UI that can handle changes in font size, resolution, and the user manually resizing the window.
In over a couple decades of writing GUIs with python/tkinter and tcl/tk, I have never used place except for extremely special circumstances. Its simply too difficult to use for must common layouts.
If you absolutely insist on using pack or grid without this "shrink to fit" behavior, you can pass a false value to the pack_propagate or grid_propagate method of the containing frame (eg: self.pack_propagate(False)). In my experience this is very rarely the right solution.
To fix this, add the following line after the line beginning: self.config(...:
self.pack_propagate(0)
See here for a documentary explaining this.
As #KārlisRieksts noted, this approach does not work however if the frame (or other parent widget) is packed with place() geometry manager. The child widgets will then affect the size of the parent.
This is the code that's giving me trouble.
f = Frame(root, width=1000, bg="blue")
f.pack(fill=X, expand=True)
l = Label(f, text="hi", width=10, bg="red", fg="white")
l.pack()
If I comment out the lines with the Label, the Frame displays with the right width. However, adding the Label seems to shrink the Frame down to the Label's size. Is there a way to prevent that from happening?
By default, both pack and grid shrink or grow a widget to fit its contents, which is what you want 99.9% of the time. The term that describes this feature is geometry propagation. There is a command to turn geometry propagation on or off when using pack (pack_propagate) and grid (grid_propagate).
Since you are using pack the syntax would be:
f.pack_propagate(0)
or maybe root.pack_propagate(0), depending on which widgets you actually want to affect. However, because you haven't given the frame height, its default height is one pixel so you still may not see the interior widgets. To get the full effect of what you want, you need to give the containing frame both a width and a height.
That being said, the vast majority of the time you should let Tkinter compute the size. When you turn geometry propagation off your GUI won't respond well to changes in resolution, changes in fonts, etc. Tkinter's geometry managers (pack, place and grid) are remarkably powerful. You should learn to take advantage of that power by using the right tool for the job.
I am using the grid manager and have two frames side by side, and five columns with 1 button in each below the two frames in a second row, evenly spaced. All use "sticky" NSEW since I want them to scale proportionally if I enlarge the window.
When I add a text entry widget to the right frame, it distorts the buttons below them so they are larger than those to the left. I can't figure out how to prevent this distortion, or put another way, how to keep each column the same size.
Is there a reason why the text entry widget is not respective the row/col/weighting? Thanks in advance!
You can try to use columnspan or rowspan. This should allow the buttons to be unaffected by the text widget.
for example:
root=Tk()
button1=Button(root,text="button1")
button1.grid(row=1,column=0)
textbox=Text(root)
textbox.grid(row=1,column=1,rowspan=2)
In each frame you should set the "propagate" status to false, this will keep the frame from resizing based on what is inside. So if the frame uses grid() set grid_propagate(False) and so on.
I think this is due to the fact you've given the entry widget a specific width (or are accepting the default). Since the widget wants to be a particular size, it will cause the column to grow in order to fit the requested size of its children.
One solution is to set the size of the entry widget to 1. Then, because of the sticky settings for E and W, it will expand to exactly fit the column.