mburleson
mburleson

Reputation: 13

How do I position tkinter widgets under an existing widget?

I was recently introduced to tkinter, and I'm attempting to write a calculator application to become familiar with it. The Entry widget where the input goes, which I call the "display" seems to be pushing the Button widgets to the right. My question is very similar to this question, however all of the answers there involve the pack() method while I'm only trying to use the grid() method for my layout. How can I position the Button widgets so that they are directly under the Entry widget rather than being pushed off to the right? Here's the current code for my application:

import tkinter as tk

root = tk.Tk()

button = list()
numbers = ("789456123")

def create_number_buttons():
    i = 0
    for row in range(1, 4):
        for column in range(1, 4):
            button.append(tk.Button(root, text=numbers[i], padx=10, pady=10))
            button[i].grid(row=row, column=column, padx=1, pady=1)
            i += 1

display = tk.Entry(root, width=25)
display.grid(row=0, column=0)
create_number_buttons()

root.mainloop()

Upvotes: 1

Views: 760

Answers (2)

Jahangeer
Jahangeer

Reputation: 478

you just have to add "columnspan=4" as an parameter to display grid something like this

display.grid(row=0, column=0, columnspan=4)

by default value of columnspan is set to 1

rest of your code seems OK :)

Upvotes: 1

Reblochon Masque
Reblochon Masque

Reputation: 36662

You can add a columnspan key word argument to the geometry manager of display:

import tkinter as tk

root = tk.Tk()

button = list()
numbers = ("789456123")

def create_number_buttons():
    i = 0
    for row in range(1, 4):
        for column in range(1, 4):
            button.append(tk.Button(root, text=numbers[i], padx=10, pady=10))
            button[i].grid(row=row, column=column, padx=1, pady=1)
            i += 1

display = tk.Entry(root)
display.grid(row=0, column=0, columnspan=4)
create_number_buttons()

root.mainloop()

Upvotes: 1

Related Questions