Python 3 – Tkinter Anchors
If you want to create a GUI (Graphical User Interface) with Python 3, Tkinter is a great choice. One useful feature of Tkinter is the ability to anchor widgets within frames. Anchors dictate where a widget should be placed within a frame. In this article, we will explore how to use the anchor feature in Tkinter.
Basic Syntax
Here’s the syntax for creating a widget in a frame with anchor:
widgetName = Tkinter.Widget(parent, anchor=position)
The parent
argument is the frame in which you want to place the widget, and widgetName
is the name you want to give to the widget. The anchor
argument is where you want to place the widget within its frame. The position
argument can be one of the following values:
- N: North
- NE: Northeast
- E: East
- SE: Southeast
- S: South
- SW: Southwest
- W: West
- NW: Northwest
- CENTER: Center (default)
For example, to place a label widget named lblHello
in the top-right corner of a frame named frameMain
, you would use the following code:
lblHello = Tkinter.Label(frameMain, text="Hello, Tkinter", anchor="NE")
lblHello.pack()
The .pack()
method is used to place the widget within the frame.
Anchor Example
Let’s create a simple GUI to demonstrate how the anchor feature works.
import tkinter as tk
root = tk.Tk()
frameMain = tk.Frame(root)
frameMain.pack()
lblHello = tk.Label(frameMain, text="Hello, Tkinter", anchor="NE")
lblHello.pack(side="left")
btnQuit = tk.Button(frameMain, text="Quit", command=root.quit)
btnQuit.pack(side="right")
root.mainloop()
In this example, we first import the tkinter
module and create a root window using the Tk()
function. Next, we create a frame named frameMain
and pack it using the .pack()
method.
We then create a label widget named lblHello
with the text “Hello, Tkinter”. We set the anchor to “NE” to place the label in the top-right corner of the frame. We use the .pack(side="left")
method to pack the label widget to the left side of the frame.
Finally, we create a button widget named btnQuit
with the text “Quit” and the command root.quit
to exit the GUI. We pack the button widget to the right side of the frame using the .pack(side="right")
method.
As you can see, the label is placed in the top-right corner of the frame, and the Quit button is placed in the top-left corner of the frame.
Conclusion
In this article, we learned how to use the anchor feature in Tkinter. Anchors allow us to place widgets within frames and dictate where they should be placed. We explored the basic syntax and saw an example of how to use anchors to create a GUI. With this knowledge, you can now start creating your own GUIs with Tkinter!