How To Position Buttons In Tkinter With Grid

tkinter position with grid

When a Python GUI application is designed with Tkinter, widgets (including buttons) require programming so that the underlying application logic can respond to mouse clicks and other actions. Additionally, in order for them to work as intended, widgets need to be positioned intuitively for the user.

Tkinter has three built-in layout managers that use geometric methods to position buttons in an application frame: pack, grid, and place

  • The pack manager organizes widgets in horizontal and vertical boxes that are limited to left, right, top, bottom positions offset from each other.
  • The grid manager locates widgets in a two dimensional grid using row and column relative coordinates.  
  • The place manager places widgets in a two dimensional grid using x and y absolute coordinates.

How to position a button in Tkinter with Grid

In this example, grid() is used to position buttons based on row and column coordinates on a grid in a frame:
This code will draw four buttons, and the placement of each button is specified by left, top, right, and bottom sections of a frame and are specified here. When you run the code it generates a dialog box with all four buttons at the specified locations.

 

import tkinter
master=tkinter.Tk()
master.title("grid() method")
master.geometry("350x275")
button1=tkinter.Button(master, text="button1")
button1.grid(row=1,column=0)
button2=tkinter.Button(master, text="button2")
button2.grid(row=2,column=2)
button3=tkinter.Button(master, text="button3")
button3.grid(row=3,column=3)
button4=tkinter.Button(master, text="button4")
button4.grid(row=4,column=4)
button5=tkinter.Button(master, text="button5")
button5.grid(row=5,column=5)
master.mainloop()

Learn more about Tkinter and how to install it here.

If you want to take advantage of the latest version of Tkinter, you’ll need to install a version of Python that supports Tcl/Tk 8.5 or greater. This will provide you with the Ttk (Tile extension integrated into Tk), which is required in order to run the current Tk widget set.

There are two other ways of installing a button in Tkinter – find them here.

Other Python Packages For Data Science, Web Development, Machine Learning, Code Quality And Security

ActivePython includes over 400 of the most popular Python packages. We’ve built the hard-to-build packages so you don’t have to waste time on configuration…get started right away! Learn more here.

 

Recent Posts

Tech Debt Best Practices: Minimizing Opportunity Cost & Security Risk

Tech debt is an unavoidable consequence of modern application development, leading to security and performance concerns as older open-source codebases become more vulnerable and outdated. Unfortunately, the opportunity cost of an upgrade often means organizations are left to manage growing risk the best they can. But it doesn’t have to be this way.

Read More
Scroll to Top