I want to create a GUI with tkinter in python using grid-Method and grid_columnconfigure/grid_rowconfigure.
Unfortunately, this is not working inside a Frame.
How can I get this work?
from tkinter import *
master = Tk()
master.state('zoomed')
f = Frame(master, width=800, height=400)
Label1 = Label(f, text='Label 1')
Label2 = Label(f, text='Label 2')
f.grid_columnconfigure(0, weight=1)
f.grid_columnconfigure(2, weight=1)
f.grid_columnconfigure(4, weight=1)
Label1.grid(row=0, column=1)
Label2.grid(row=0, column=3)
f.pack()
master.mainloop()
ADDITIONAL QUESTION:
I got great answers, all is working fine with pack-Manager.
But how could I do this if using grid-Manager?
The grid_columnconfigure is working fine. The problem is that your frame will by default set its size to the smallest possible size to fit the labels. Since empty columns don't have a size, the frame will be just wide enough to hold the two labels.
This will be easy to visualize if you give frame a distinctive color during development. It also sometimes helps to give the frame a visual border so you can see its boundaries.
While I don't know what your ultimate goal is, you can see the spaces between the column if you have the frame fill the entire window:
f.pack(fill="both", expand=True)
If you want to use grid instead of pack, you have to do a bit more work. In short, put the frame in row 0 column 0, and give that row and column a non-zero weight so that grid will give all unused space to that row and column.
f.grid(row=0, column=0, sticky="nsew")
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)
If you want to force the window to be a specific size, you can use the geometry method of the master window:
master.geometry("800x400")
Related
One thing that can do it is assigning weights to non existent columns and rows. Maybe users know of others?
I recently had to track down this problem, and place it here in the hope it will be useful to others.
After resizing your window frame, tkinter will not resize widgets if you have assigned a non zero weight to non existent columns. I ran into this situation where I had a dynamic UI which hid a panel, and replaced it with some buttons. For these buttons to resize properly, I did a columnconfigure and assigned weights of 1 to these extra columns. When the UI was restored, these buttons were removed, and we went back to one column. However the weights for these non existent columns still influenced the resizing as seen in the attached figure.
To solve the problem I reset the weights of these extra columns that I had set to 1 back to zero (even though these columns did not exist in the UI any more).
Minimal code to illustrate the problem is shown below:
The problem line is labelled # ####### this is a problem
import tkinter as tk
class frame_resize:
def setupGUI(self):
self._root = tk.Tk()
self._font = 'helvetica 16'
self._mainFrame = tk.Frame(self._root, bg='pink')
self._label = tk.Label(self._mainFrame,
font=self._font,
bg='sky blue',
text='this is some text')
self._mainButton = tk.Button(self._mainFrame, text='Press here',
font=self._font)
# give weights so that widgets expand when outer frame expands
tk.Grid.rowconfigure(self._root, 0, weight=1)
tk.Grid.columnconfigure(self._root, 0, weight=1)
tk.Grid.rowconfigure(self._mainFrame, 0, weight=1)
tk.Grid.columnconfigure(self._mainFrame, 0, weight=1)
# ####### this is a problem, if we have no column 1
tk.Grid.columnconfigure(self._mainFrame, 1, weight=1)
#pop elemnts into grid
self._mainFrame.grid(column=0, row=0, sticky='nsew')
self._label.grid(column=0, row=0, sticky='nsew')
self._mainButton.grid(column=0, row=1, sticky='nsew')
self._root.mainloop()
fr = frame_resize()
fr.setupGUI()
I would expect the text area that the below code produces to take up half of the screen because the weights of the columns are equal.
Why does the text area take up about 2/3 of the screen instead and how do I get the text area to only take up half the screen?
from tkinter import *
root = Tk()
root.wm_state('zoomed')
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.rowconfigure(0, weight=1)
root.configure(bg='red')
info_frame = Frame(root)
info_frame.grid(row=0, column=1, sticky="nsew")
info_frame.columnconfigure(0, weight=1)
info_frame.rowconfigure(0, weight=1)
user_frame = Frame(root, bg='blue')
user_frame.grid(row=0, column=0, sticky="nsew")
user_frame.columnconfigure(0, weight=1)
user_frame.rowconfigure(0, weight=1)
user_frame.rowconfigure(1, weight=1)
button_frame = Frame(user_frame)
button_frame.grid(row=0, column=0, sticky="nsew")
entry_frame = Frame(user_frame)
entry_frame.grid(row=1, column=0, sticky="nsew")
info_display = Text(info_frame, state=DISABLED)
info_display.grid(row=0, column=0, sticky="nsew")
scrollbar = Scrollbar(info_frame)
scrollbar.grid(row=0, column=1, sticky="nsew")
light_label = Label(entry_frame, text='Light').grid(row=0, column=0)
light_entry = Entry(entry_frame).grid(row=0, column=1)
current_label = Label(entry_frame, text='Current').grid(row=1, column=0)
current_entry = Entry(entry_frame).grid(row=1, column=1)
button1 = Button(button_frame, text='button1').grid(row=0, column=0)
button2 = Button(button_frame, text='button2').grid(row=0, column=1)
button3 = Button(button_frame, text='button3').grid(row=1, column=0)
button4 = Button(button_frame, text='button4').grid(row=1, column=1)
root.mainloop()
The weight tells tkinter how to allocate extra space, it's not a mechanism to guarantee that columns or rows have the same size.
Let's say you place a 100 pixel wide widget in column 0, and a 200 pixel wide widget in column 1, and you give both columns equal weight. The GUI will naturally try to be 300 pixels wide, because that's what you requested.
If you make the window larger (either through interactive resizing, by using the geometry method, or by zooming the window), tkinter will use the weight to decide how to allocate extra space.
For example, if you force the GUI to be 500 pixels wide, there are 200 unallocated pixels. Given that each column has the same weight, 100 pixels will go to each column, making one column 200 pixels and the other column 300. Thus, even though they have the same weight, they won't have the same size.
If you want columns to have an identical width, you can use the uniform option to make the columns part of a uniform group. Within that group, all columns will have the same width.
For example, this will guarantee that each column takes up half the space (by virtue of there being only two columns with weight, and they are the same size, by definition they must take up half the window)
root.columnconfigure(0, weight=1, uniform="half")
root.columnconfigure(1, weight=1, uniform="half")
Note: you can use any string you want in place of "half" -- the only critiera is that all columns with the same value will have the same width.
Grid weights distribute extra space. See reference.
weight To make a column or row stretchable, use this option and
supply a value that gives the relative weight of this column or row
when distributing the extra space. For example, if a widget w contains
a grid layout, these lines will distribute three-fourths of the extra
space to the first column and one-fourth to the second column:
w.columnconfigure(0, weight=3)
w.columnconfigure(1, weight=1)
The default size of the text widget is much bigger than the default size of the other stuff. If you want more equal columns, you must grow the other stuff and shrink the text.
How can I make two Frames occupy 50% each of the available width of the window?
Right now I'm just letting the contents dictate the widths and using pack(side=Tkinter.LEFT), and obviously that doesn't make them both equal width.
I tried using grid() instead, but then I couldn't get them to resize when I resize the window.
EDIT
Note that I want to be able to resize the window and the frames should resize with it to always be 50% of the width.
You can use grid, using the uniform option. Put both halves in a "uniform group" by setting the uniform option to the same value for both, and they will be the same size. To get the columns to grow/shrink with the window, give them equal weight.
Example:
frame1 = tk.Frame(parent, ...)
frame2 = tk.Frame(parent, ...)
frame1.grid(row=0, column=0, sticky="nsew")
frame2.grid(row=0, column=1, sticky="nsew")
parent.grid_columnconfigure(0, weight=1, uniform="group1")
parent.grid_columnconfigure(1, weight=1, uniform="group1")
parent.grid_rowconfigure(0, weight=1)
You should use expand and fill if using the pack method
Example
import Tkinter as tk
root = tk.Tk()
left_frame = tk.Frame(root, bg = 'yellow')
left_frame.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
right_frame = tk.Frame(root, bg = 'lime')
right_frame.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
root.mainloop()
I finally came up with a hack that works correctly.
In the start, I create 2 frames, one of them has a label with (intentionally) a long text, and the other one a simple button. You can add as many widgets to both frames as you want.
The idea is to bind a callback method which takes in consideration the new dimensions of the main window (in case the user stretches or moves the window with the mouse) and resize the 2 frames consequently.
This is achieved using <Configure> event which provides the new dimensions to set to our 3 main widgets (the main window and the 2 frames).
The next step is to fix the problem you mentioned below #StevenSummers ' answer. To do that, we can rely on grid_propagate() which enables or disables the geometry propagation.
Program:
Let us put these ideas into action (a quick dirty example to implement the ideas; I did the same for the height, but you can ignore it if you do not need it):
import Tkinter as Tk
# Main window
master = Tk.Tk()
# Callback event that resizes the main components
def resize_it(event):
global master # Main Window
global a # Red Frame
global b # Blue Frame
#Reconfigure the main window's and frames' dimensions
a.configure(width=event.width/2, height=event.height/2)
b.configure(width=event.width/2, height=event.height/2)
master.configure(width=event.width, height=event.height)
#Create a red (first) Frame
a = Tk.Frame(master, bg='red')
a.pack(side='left', expand=True, fill=Tk.BOTH)
# Draw a button on frame a
a1 = Tk.Button(a, text='Button 1')
a1.grid(row=0, column=0)
# Disable geometry propagation
a.grid_propagate(0)
#Create a blue (second) Frame
b = Tk.Frame(master, bg='blue')
b.pack(side='left', expand=True, fill=Tk.BOTH)
# Draw a label on frame b
l1 = Tk.Label(b, text='Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1Label 1')
l1.grid(row=0, column=0)
# Disable geometry propagation on frame b
# Note: always after adding ALL the desired widgets to b. Same note for frame b
b.grid_propagate(0)
master.bind('<Configure>', resize_it)
#Start program
master.mainloop()
Demo:
The output of the above program is always the same result you expect whenever you resize the main window using the mouse and whatever number of widgets you add to the 2 frames:
I'm using tkinter to write a card game, and I'm having trouble with he grid layout manager 'sticky' configuration. I would like help fixing my code to make the frames display in the desired location. In my code and illustration below, there is a frame (b2) that contains two other (one green, b2a; and one red; b2b) frames. I would like to display frame b2 at the bottom of the parent frame (frame b). I've tried various combinations of N+S+E+W as arguments for 'sticky', for both frame b2 and the child frames b2a and b2b. However, I've been unable to make frame b2 (and more importantly b2a and b2b) appear in the desired location (the bottom image below with the correct placement was made in Illustrator).
In particular, it seems that sticky arguments in lines 27, 36 and 37 have no effect on the placement of frame b2, b2a and b2b inside of frame b.
from tkinter import *
from PIL import Image, ImageTk
def main(root):
cons = Frame(root)
cons.grid()
frameDict = setup_frames(cons)
populate_frames(frameDict)
def setup_frames(cons):
frame = {}
# Parental Frames
frame['a'] = Frame(cons, borderwidth=2, relief='groove')
frame['b'] = Frame(cons, borderwidth=2, relief='groove')
frame['c'] = Frame(cons, borderwidth=2, relief='groove')
frame['a'].grid(row=0, column=0, sticky=N+S+E+W)
frame['b'].grid(row=0, column=1, sticky=N+S+E+W)
frame['c'].grid(row=1, column=0, columnspan=2)
# Progeny 0 Frames:
frame['b1'] = Frame(frame['b'], borderwidth=2, relief='groove')
frame['b2'] = Frame(frame['b'], borderwidth=2, relief='groove')
frame['b1'].grid(row=0, column=0, sticky=N+S+E+W)
frame['b2'].grid(row=1, column=0, sticky=N+S+E+W)
# Progeny 1 Frames:
frame['b2a'] = Frame(frame['b2'], borderwidth=2, relief='groove',
background='green')
frame['b2b'] = Frame(frame['b2'], borderwidth=2, relief='groove',
background='red')
frame['b2a'].grid(row=0, column=0, sticky=S)
frame['b2b'].grid(row=0, column=1, sticky=SW)
return frame
def populate_frames(fr):
# Populating 'a' frame
aLab = Label(fr['a'], image=img[0])
aLab.grid()
# Populating b2a & b2b frames
bLab = Label(fr['b2a'], image=img[1])
bLab.grid(row=0, column=0)
bLab = Label(fr['b2b'], image=img[2])
bLab.grid(row=0, column=1)
# Populating c1 frame
cLab = Label(fr['c'], image=img[3])
cLab.grid()
if __name__ == '__main__':
root = Tk()
img = []
w = [40, 160, 80, 480]
h = [180, 60, 60, 60]
for i in range(4):
a = Image.new('RGBA', (w[i], h[i]))
b = ImageTk.PhotoImage(a)
img.append(b)
main(root)
The images below illustrate where the offending frames (green and red) are displaying (top) and where I would like them displayed (bottom).
Could someone please help me display frame b2 (and ultimately b2a and b2b) in the correct position (Edit: at the bottom of frame b, and spanning from the right side of frame a to the right side of frame c)?
Update:
I've solved both problems (vertical placement and horizontal justification of frame b2) using grid weights, as Bryan suggested. The solution to the vertical placement problem is straightforward, but I would not have predicted the solution to the horizontal justification issue.
I solved the vertical placement problem by giving weight=1 to row 0 in frame b (resulting in the upper panel of the figure below).
I solved the horizontal justification problem (wherein frames b1 and b2 were not stretching to fill frame b) by assigning weight=1 to column 0 in frame b. The frame outlines in the figure below show that frame b is already stretched from the right side of frame a to the right side of frame c. It's strange to me that giving weight to the only column in a frame would be required to allow child frames to fill horizontally. In any case, I've pasted my working code below. Lines 40 and 41 solved the issue I was having.
from tkinter import *
from PIL import Image, ImageTk
def main(root):
cons = Frame(root)
cons.grid()
frameDict = setup_frames(cons)
populate_frames(frameDict)
def setup_frames(cons):
frame = {}
# Parental Frames
frame['a'] = Frame(cons, borderwidth=2, relief='groove')
frame['b'] = Frame(cons, borderwidth=2, relief='groove')
frame['c'] = Frame(cons, borderwidth=2, relief='groove')
frame['a'].grid(row=0, column=0, sticky=N+S+E+W)
frame['b'].grid(row=0, column=1, sticky=N+S+E+W)
frame['c'].grid(row=1, column=0, columnspan=2)
# Progeny 0 Frames:
frame['b1'] = Frame(frame['b'], borderwidth=2, relief='groove')
frame['b2'] = Frame(frame['b'], borderwidth=2, relief='groove')
frame['b1'].grid(row=0, column=0, sticky=N+S+E+W)
frame['b2'].grid(row=1, column=0, sticky=N+S+E+W)
# Progeny 1 Frames:
frame['b2a'] = Frame(frame['b2'], borderwidth=2, relief='groove',
background='green')
frame['b2b'] = Frame(frame['b2'], borderwidth=2, relief='groove',
background='red')
frame['b2a'].grid(row=0, column=0, sticky=S)
frame['b2b'].grid(row=0, column=1, sticky=SW)
# Weighting
frame['b'].grid_rowconfigure(0, weight=1)
frame['b'].grid_columnconfigure(0, weight=1)
return frame
def populate_frames(fr):
# Populating 'a' frame
aLab = Label(fr['a'], image=img[0])
aLab.grid()
# Populating b2a & b2b frames
bLab = Label(fr['b2a'], image=img[1])
bLab.grid(row=0, column=0)
bLab = Label(fr['b2b'], image=img[2])
bLab.grid(row=0, column=1)
# Populating c1 frame
cLab = Label(fr['c'], image=img[3])
cLab.grid()
if __name__ == '__main__':
root = Tk()
img = []
w = [40, 160, 80, 480]
h = [180, 60, 60, 60]
for i in range(4):
a = Image.new('RGBA', (w[i], h[i]))
b = ImageTk.PhotoImage(a)
img.append(b)
main(root)
Consistent with Bryan's advice, it does seem to be a good rule of thumb to assign a weight to at least one column and one row in every container.
Here's before and after I fixed the horizontal justification problem:
Using Python 3.4, Yosemite
You must give some rows and columns a weight, so tkinter knows how to allocate extra space.
As a rule of thumb when using grid, every container using grid should give at least one row and one column weight.
What I would do is start over. Be methodical. Get the main three areas working first before tackling other problems. What is making this problem hard to solve is that nothing is behaving right, so you're trying to adjust many things at once. Focus on one area at a time, get it working just right, and then move on.
Given your diagram, pack seems like a much simpler solution than using grid for the children of the root window Using grid inside of frames inside of other frames using grid can be confusing.
It looks like frame C is a status bar of some sort that stretches across the bottom, so pack it first. Above that you have two areas - frame a is to the left and looks to be a fixed width, and frame c is to the right and takes up all of the extra space. Using pack, it would look like this:
frame['c'].pack(side="bottom", fill="x")
frame['a'].pack(side="left", fill="y")
frame['b'].pack(side="right", fill="both", expand=True)
Of course, you can get the exact same appearance with grid, but it will take a couple more lines of code since you have to give column 1 and row 1 a weight.
That should get the three main areas working just fine. Now all you have to worry about is the contents of frame B.
Your diagram shows that you want b2a and b2b at the bottom of frame b, with more widgets above it. Is that correct? If that's the case, you need to leave at least one extra row above it to fill the extra space.
The blank row with a positive weight will force all of the widgets to be moved toward the bottom of the area. They will take up only as much space as they need vertically, with the empty row with the non-zero weight taking up all the extra.
You then only have to worry about horizontal placement. It's unclear exactly what you expect, but the solution again revolves around giving columns weight. If you want both b2a and b2b to expand equally, give both columns an equal weight. If you want b2a to do all of the expanding, give only column zero a weight.
I am faced with the problem to center side-stacked frames in a parent frame. I know how to center a single frame in a frame but I did not find a simple way to do this for several of them.
I get the following window
from the code below:
import Tkinter as tk
root = tk.Tk()
root.geometry("200x200")
# main frame
f = tk.Frame(root, background='black')
f.pack(expand=True, fill="both")
# two side-by-side frames inside, they fill up their space
f1 = tk.Frame(f, background='green')
f1.pack(side=tk.LEFT, expand=True, fill="both")
f2 = tk.Frame(f, background='red')
f2.pack(side=tk.LEFT, expand=True, fill="both")
# three fixed-size frames in the left frame above; I would like them to be centered in the frame
tk.Frame(f1, width=20, height=20, background="orange").pack(side=tk.LEFT, fill=None, expand=False)
tk.Frame(f1, width=20, height=20, background="white").pack(side=tk.LEFT, fill=None, expand=False)
tk.Frame(f1, width=20, height=20, background="gray50").pack(side=tk.LEFT, fill=None, expand=False)
root.mainloop()
I would like the three square frames to be centered in the green one. I had to use tk.LEFT to position them, otherwise they would have been stacked up by default.
In my complete program, the green frame is there to exclusively contain the three square frames.
What is the most standard way to center the three square frames in the green one?
While thinking about furas's comment I realized that I did not understand the true difference between expand and fill (it is still a bit vague). It is possible to center the three frames by changing the f1.pack() line to:
f1.pack(side=tk.LEFT, expand=True, fill=None)
The f1 frame is tight around the three square (fill=None) ones buts tries to take as much space as possible in all directions (expand=True), effectively being centered. Note that the green background is not visible, the frame being tight around its content.