Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Grid Columnspan ignored

Consider the following python script

#!/usr/bin/env python
from Tkinter import Tk, Label

width = SOME_VALUE_HERE

root = Tk()
label1 = Label(root, text='1 columns wide')
label2 = Label(root, text='%i columns wide' % width)

label1.grid()
label2.grid(row=0, column=1, columnspan=width)

root.mainloop()

When I run this, no matter what value is set for SOME_VALUE_HERE, both labels take up half the window, regardless of whether or not Grid.columnconfigure is called, or the sticky parameter is used in grid().

Unless I've overlooked something, I would have thought that setting the columnspan would force the second label to be SOME_VALUE_HERE times as wide as the first.

Have I misunderstood how grid works? How would I go about achieving this behavior?

like image 744
user2085282 Avatar asked Jun 16 '26 05:06

user2085282


2 Answers

By default, empty grid column are zero width, so you described the following table. Grid geometry manager will by default try to optimize the screen real estate used by your application. It will integrate all the constraint and produce the fittest layout.

+---------------+---------------++++
|       0       |       1       |||| <-- 2,3,4 empty, 0 width
+---------------+---------------++++
| 1 column wide | 4 column wide    |
+---------------+---------------++++

To provide strict proportional column width, you have to use the uniform option of columnconfigure. uniform takes an arbitrary value to designate the group of the column that share these proportions, and the weight argument is used to properly handle widget resizing.

label1.grid(row=0, column=0)
label2.grid(row=0,column=1, columnspan=width)
for i in range(width+1):
    root.grid_columnconfigure(i, weight=1, uniform="foo")

Note that with only these two labels, you could achieve the same layout by adjusting the width of column 1. Differences will occur still while you populate column 2,3,4...

label2.grid(row=0,column=1) #no columnspan
root.grid_columnconfigure(0, weight=1, uniform="foo")
root.grid_columnconfigure(1, weight=width, uniform="foo")
like image 54
FabienAndre Avatar answered Jun 18 '26 00:06

FabienAndre


When you put something in column 1 with a columnspan of two (or more) that means it will be in column 1 and column 2 (etc). However, if there is nothing controlling the width of a column, that column will have a width of zero. You need to force column 2 to have a widtheither by putting something in there, giving it a minsize, or forcing uniform columns.

When I look at your code, I can't guess how wide you think column 2 should be, and neither can the computer.

like image 40
Bryan Oakley Avatar answered Jun 17 '26 22:06

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!