I'm writing a custom Python class that simplifies interaction with tkinter so I can simplify the process of writing my own GUI applications. So far it's been tricky, but progress has been steady and it works pretty well.
However, I've run into specific unexpected behavior and I can't pinpoint the cause. When I define an element to have a rowspan it doesn't expand to fit the number of rows I specify.
Here is a screenshot of my current output:
The GUI in the screenshot is defined in the order specified:
10 labels are defined "1" to "10", in cells 0,0 - 0,10.
A frame with rowspan = 1 is added containing a label "Rowspan 1" to 1,0
A frame with rowspan = 2 is added to 2,0
A frame with rowspan = 3 is added to 3,0
...
A frame with rowspan = 10 is added to 10,0
A label with "After Stretched" is added to 11,0
As you can see in the above screenshot, the rowspan does not appear to match the rowspan that was set.
Here is the relevant code:
self.frame = tkinter.Frame(self.frame, borderwidth=1, relief=border)
self.frame.grid(row=self.grid_y, column=self.grid_x,
columnspan=self.grid_x_span, rowspan=self.grid_y_span,
padx=5, pady=5, sticky="nsew")
print("Frame:")
print("X,Y:",self.grid_x,self.grid_y)
print("X,Y Spans:",self.grid_x_span, self.grid_y_span)
...and here is the printed output showing what values the variables had when generating this output:
Frame:
X,Y: 1 0
X,Y Spans: 1 1
Frame:
X,Y: 2 0
X,Y Spans: 1 2
Frame:
X,Y: 3 0
X,Y Spans: 1 3
Frame:
X,Y: 4 0
X,Y Spans: 1 4
Frame:
X,Y: 5 0
X,Y Spans: 1 5
Frame:
X,Y: 6 0
X,Y Spans: 1 6
Frame:
X,Y: 7 0
X,Y Spans: 1 7
Frame:
X,Y: 8 0
X,Y Spans: 1 8
Frame:
X,Y: 9 0
X,Y Spans: 1 9
Frame:
X,Y: 10 0
X,Y Spans: 1 10
Any ideas why this might be happening? When I hard-code rowspan it still exhibits this behavior.
So you want something like this:
Here's the code:
import tkinter as tk
root = tk.Tk()
main_frame = tk.Frame(root, border=3, relief=tk.GROOVE)
main_frame.grid()
for i in range(10):
#Create Labels for numbering the rows:
tk.Label(main_frame,
text=str(i+1),
border=1,
relief=tk.GROOVE,
padx=20,
pady=20,
).grid(column=0, row=i)
#Create Frames with a Label inside:
frame = tk.Frame(main_frame,
border=1,
relief=tk.GROOVE,
background="blue",
)
frame.grid(row=0, column=i+1, rowspan=i+1, sticky=tk.N+tk.S)
tk.Label(frame,
text='Rowspan {}'.format(i+1),
border=1,
relief=tk.GROOVE,
padx=20,
pady=20,).grid()
root.mainloop()
Normally, a frame hugs the widgets inside it. The sticky
argument for grid() makes the frame stretch vertically and fill the rows specified by rowspan.
If you remove the border around the labels and the background color of the frames, you'll get this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With