Sandrocottus
Sandrocottus

Reputation: 533

Python 3: Positions of button and input text in a text box

I am new to python and learning to create a text box with two entries and one button.

I am able to set the position of my both entries, but I am not able to set the position of my button below them.

I tried to use:

b.place(anchor=S, bordermode=OUTSIDE, height=5, width=10)

but the button doesn't move at all. It stays at the lower right corner.

Following is my code:

from tkinter import *
root = Tk()

l1 = Label(root, text="Variable_1")
l1.pack( side = LEFT)
e1 = Entry(root, bd = 5)
e1.pack(side = LEFT)

l2 = Label(root, text="Variable_2")
l2.pack( side = LEFT)
e2 = Entry(root, bd = 5)
e2.pack(side = LEFT)

l = Label(root)
def callback():
    x = e1.get()
    y = e2.get()
    print(x)
    print(y)

b = Button(root, text="OK", command=callback)

for widget in (e1, e2, l, b):
    widget.pack()

How can I place the button at the bottom-centre of the text box?

Also, any suggestions to change the positions of the entries?

Thanks!

Upvotes: 0

Views: 1387

Answers (1)

figbeam
figbeam

Reputation: 7176

The usual way to build complex layouts is to group associated widgets together with frames. In the example below I'm grouping the entrys in one frame and the button in another. This makes it easier to control the vertical positioning.

from tkinter import *
root = Tk()

top = Frame(root)   # Create frame to hold entrys
top.pack()          # Pack top frame
l1 = Label(top, text="Variable_1")
l1.pack(side=LEFT)
e1 = Entry(top, bd=5)
e1.pack(side=LEFT)

l2 = Label(top, text="Variable_2")
l2.pack(side=LEFT)
e2 = Entry(top, bd=5)
e2.pack(side=LEFT)

l = Label(root)
def callback():
    x = e1.get()
    y = e2.get()
    print(x)
    print(y)

bottom = Frame(root)    # Create frame to hold button
bottom.pack()           # Pack bottom frame
b = Button(bottom, text="OK", command=callback)
b.pack()

You can also use the grid() geometry manager. See The Tkinter Grid Geometry Manager

Upvotes: 1

Related Questions