Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make tkinter::pack() place label on top left corner in below program?

I am using pack() to align label and buttons on tkinter.The following code:

from tkinter import *
wind=Tk()
wind.geometry('450x450')
l1=Label(wind,text='Did you mean:')
l1.pack(side=LEFT)
b1=Button(wind,text='Button1',width=450)
b1.pack()
b2=Button(wind,text='Button2',width=450)
b2.pack()
wind.mainloop()

gives output:1

I tried removing the side=LEFT from l1.pack(side=LEFT) it gives: 2.

For me expected output is label l1 on top left corner and the buttons stacked below it.

like image 847
Nikith Clan Avatar asked Sep 19 '19 17:09

Nikith Clan


People also ask

How do I change the position of a label in Python?

We can use place() method to set the position of the Tkinter labels.

How is pack () function works on Tkinter widget?

The pack() fill option is used to make a widget fill the entire frame. The pack() expand option is used to expand the widget if the user expands the frame. fill options: NONE (default), which will keep the widget's original size.

Can we use pack and place together in Tkinter?

Important: pack(), place(), and grid() should not be combined in the same master window. Instead choose one and stick with it.

What is the use of the place () function in Tkinter Python?

Python - Tkinter place() Method This geometry manager organizes widgets by placing them in a specific position in the parent widget.


1 Answers

pack works with a box model, aligning widgets along one side of the empty space in a container. Thus, to put something along the top, you need to use side="top" (or side=TOP if you prefer using a named constant), and it needs to come before other widgets.

In your specific case, to get the widget aligned at the top, you would do the following:

l1.pack(side=TOP)

By default this will center the widget along the top edge. If you also want the label aligned to the left, you would use the anchor option, which takes points of a compass ("n", "s", "e", "w", "nw", etc).

Thus, to place the widget at the top, and anchor it to the top-left corner you would do something like this:

l1.pack(side=TOP, anchor=NW)
like image 99
Bryan Oakley Avatar answered Oct 12 '22 14:10

Bryan Oakley