Sami Ullah
Sami Ullah

Reputation: 89

Why are my widgets not positioning on given row and column?

I am trying to place a label and a button widgets at row=0 and different columns, inside a nested frame (i.e result frame). But inside result frame, label and button widgets appears in the center. Can you me to place widgets on intended positions.

Screenshot of my app and explaining what |I want

import tkinter as tk

window = tk.Tk()
window.title("ASA Downloader")
window.geometry("400x400")
frame1 = tk.LabelFrame(window, padx=5, pady=5, height="200")

#Labels
weight_label = tk.Label(frame1, text= "Weight")
height_label = tk.Label(frame1, text= "Height")

weight_label.grid(row=0,column=0)
height_label.grid(row=1,column=0)

result_frame = tk.LabelFrame(frame1, text="result frame")
result_frame.grid(row=2, column=0)

result_lable= tk.Label(result_frame, text=" result is none")
result_lable.grid(row=0, column=0)

button = tk.Button(result_frame, text="My button inside nested frame")
button.grid(row=1, column=0)


frame1.place(relx=.5, rely=.5, anchor="center")
window.mainloop()

Upvotes: 0

Views: 65

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385800

By default, widgets are centered by grid unless you tell it to do otherwise. You aren't telling it to do otherwise, so that is what is happening.

The width of the column is being set by the widest thing in the column. In this case the width of column 0 is the width of the inner frame (which itself is controlled by the width of the button). Since the column is widget than the labels, the labels are centered.

If you are wanting the width and height labels to be on the left, the simplest solution is to set the sticky option to "w" (for west).

weight_label.grid(row=0,column=0, sticky="w")
height_label.grid(row=1,column=0, sticky="w") 

Another option would be to set sticky to "ew" (east-west) so that the widget expands to fill the column. You can then set the "anchor" attribute of each label to "w" so that the text is left-aligned. The choice of which solution to use depends a bit on whether you plan to have other widgets in your window.

weight_label = tk.Label(frame1, text= "Weight", anchor="w")
height_label = tk.Label(frame1, text= "Height", anchor="w")

weight_label.grid(row=0,column=0, sticky="ew")
height_label.grid(row=1,column=0, sticky="ew")

screenshot

Upvotes: 1

Related Questions