How to Control Layout with place() Method in Python


In this example, we will create two buttons and set their positions using place() with different parameters in Python.

2. Parameters

The place() method sets the absolute or relative position of the control in the form or window. The place() method has the following parameters:

  • anchor: This parameter defines the orientation of the control within the form or window. It can be N, NE, E, SE, S, SW, W, NW, or CENTER. The default value is NW, which means the orientation is in the upper left corner.
  • bordermode: This parameter defines the coordinates of the control, whether to consider the width of the border. This parameter can be OUTSIDE or INSIDE. The default value is INSIDE.
  • height: This parameter defines the height of the control in pixels.
  • width: This parameter defines the width of the control in pixels.
  • in(in_): This parameter defines the position of the control relative to the reference control. If you are using a key value, you must use in_.
  • relheight: This parameter defines the height of the control relative to the reference control (using the in_ option).
  • relwidth: This parameter defines the width of the control relative to the reference control (using the in_ option).
  • relx: This parameter defines the horizontal displacement of the control relative to the reference control (using the in_ option). If the in_ option is not set, it is relative to the parent control.
  • rely: This parameter defines the vertical displacement of the control relative to the reference control (using the in_ option). If not set, the in_ option is relative to the parent control.
  • x: This parameter defines the absolute horizontal position of the control. The default value is 0.
  • y: This parameter defines the absolute vertical position of the control. The default value is 0.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# placeLayout.py

from tkinter import *

# the main window
win = Tk()

# create the window
frame = Frame(win, relief=RAISED, borderwidth=3, width=300, height=300)
frame.pack(side=TOP, fill=BOTH, ipadx=5, ipady=5, expand=1)

# place the first button on the left upper corner with coordinate (30, 30)
coordinate1 = (30, 30)
button1 = Button(frame, text="Button West")
button1.place(x=coordinate1[0], y=coordinate1[1], anchor=W, width=75, height=40)

# place the first button on the right upper corner with coordinate (270, 80)
coordinate2 = (270, 80)
button2 = Button(frame, text="Button East")
button2.place(x=coordinate2[0], y=coordinate2[1], anchor=E, width=75, height=40)

win.mainloop()

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement