Enrique Metner
Enrique Metner

Reputation: 189

tkinter positioning objects: anchor

I am trying to position stuff and found out about the anchor keyword. But nothing seems to work as I want. The tutorials don't explain it well enough and even a code as simple as that does not work. How do I place something for example in the bottom right corner. (I am working with the place method and would appreciate solutions with that method)

from tkinter import *

root = Tk()
root.geometry("300x300")

frame = Frame(root, bg="blue", width=50, height=50 )
frame.place(anchor=SE)
root.mainloop()

Upvotes: 2

Views: 5088

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

anchor tells place which part of the widget to put at the coordinates within the master. An anchor of "nw" (northwest) tells tkinter to put the northwest (upper-left) corner of the widget at the given coordinates. Likewise, "se" (southeast) puts the lower-right corner at the given coordinates.

Other options are "sw" (southwest) for the lower-left corner, and "ne" (northest) for the upper-right corner.

In the following example, the red frame is placed using anchor='nw' and the green frame is placed using anchor='se'. In both cases they are placed at position 100,100 within a window that is 200x200 (thus, the coordinate is the center of the window)

import tkinter as tk
root = tk.Tk()
root.configure(width=200, height=200, background="black")

f1 = tk.Frame(width=50, height=50, background="red")
f2 = tk.Frame(width=50, height=50, background="green")

f1.place(x=100, y=100, anchor="nw")
f2.place(x=100, y=100, anchor="se")

root.mainloop()

screenshot of nw and se anchors

How do I place something for example in the bottom right corner.

For that you'll want to use a combination of anchor with relative placement. With relative coordinates, a relative x coordinate of zero is the far left edge of the master window, and 1.0 is the far right edge. Likewise, a relative y coordinate of zero is the top edge and 1.0 is the bottom edge. A relative value of .5 represents the center of a widget.

To put something at the bottom right corner you want the relative x and y locations of 1.0 and an anchor of "se" to put the bottom-right part of the widget at that position

import tkinter as tk
root = tk.Tk()
root.configure(width=200, height=200, background="black")

f1 = tk.Frame(width=50, height=50, background="white")
f1.place(relx=1.0, rely=1.0, anchor="se")

root.mainloop()

screenshot of bottom-right corner placement

Upvotes: 3

Related Questions