user16378160
user16378160

Reputation:

How to use the 'in' attribute of grid in Tkinter

In Tkinter using grid geometry manager, how can I put Other widgets inside of a Frame? I know there is a 'in' attribute of grid, but I Am not sure about the correct syntax

I have used master=frame in the widget but still, by row and column it is coming in the root and not in the frame (I know it's because I have not used the 'in' attribute of grid)

If I just do grid(row=0,column=0,in=frame) Then an error comes, so how exactly should I use the 'in' attribute of grid

Upvotes: 0

Views: 356

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

In Tkinter using grid geometry manager, how can I put Other widgets inside of a Frame?

The normal way is to make the widget a child of a frame.

frame = tk.Frame(...)
other_widget = tk.Label(frame, ...)

I know there is a 'in' attribute of grid, but I Am not sure about the correct syntax

The correct syntax is to set the attribute in_ to some other widget. We have to use in_ rather than in because in is a reserved word in Python.

Further, there are restrictions for which widgets can be a target of in_. From the canonical documentation:

The container for each content must either be the content's parent (the default) or a descendant of the content's parent. This restriction is necessary to guarantee that the content can be placed over any part of its container that is visible without danger of the content being clipped by its parent.

I have used master=frame in the widget but still, by row and column it is coming in the root

If that is the case, frame is most likely set to None. That will happen if you create frame and call pack or grid all in a single statement (eg: frame = tk.Frame(root).pack()). This is a very common mistake.

The reason that frame is None is due to how python handles function results. If you do x = y().z(), x will be set to the result of .z(). Since pack, place, and grid all return None, if you do frame = tk.Frame(...).grid(...), frame will be None.

Here's an example of how to use in_, though it's far more common to make the widgets a child of the frame instead of using in_:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

frame1 = tk.Frame(root, background="bisque")
frame1.pack(side="top", fill="x", expand=False)

# create a label as a child of the root window
label = tk.Label(root, text="Hello, world")

# add the label to the frame. 
label.grid(in_=frame1, row=0, column=0, padx=4, pady=4)

root.mainloop()

screenshot

Upvotes: 2

Related Questions