Denny
Denny

Reputation: 225

Python- How to place two buttons left-right and next to each other in the middle of screen?

First, I read the related discussion: How can I put 2 buttons next to each other?.

However, I still confused about it. My codes:

#Import the required Libraries

from tkinter import *
from tkinter import ttk
import random


win = Tk()
win.geometry("750x250")

def clear():
   entry.delete(0,END)
def display_num():
   for i in range(1):
      entry.insert(0, random.randint(5,20))

entry= Entry(win, width= 40)
entry.pack()
button1= ttk.Button(win, text= "Print", command=display_num)
button1.pack(side= LEFT)
button2= ttk.Button(win, text= "Clear", command= clear)
button2.pack(side=LEFT)

win.mainloop()

Now I got

enter image description here

I want two buttons in the middle of screen just below the Entry (white box).
How to fix it? Thanks!

Upvotes: 0

Views: 3853

Answers (2)

Thingamabobs
Thingamabobs

Reputation: 8037

Working with pack means working with parcels, therefore Imagine a rectangle around your widgets while we discuss further more. By default your values look like this:

widget.pack(side='top',expand=False,fill=None,anchor='center')

To get your widget in the spot you like you will need to define it by these parameters. the side determinates in which direction it should be added to. Expand tells your parcel to consume extra space in the master. fill tells your widget to strech out in its parcel in x or y or both direction. you can also choose to anchor your widget in your parcel in east,west,north,south or a combination of it.

from tkinter import *
from tkinter import ttk
import random


win = Tk()
win.geometry("750x250")

def clear():
   entry.delete(0,END)
def display_num():
   for i in range(1):
      entry.insert(0, random.randint(5,20))

entry= Entry(win)
entry.pack(fill='x')
button1= ttk.Button(win, text= "Print", command=display_num)
button1.pack(side= LEFT,expand=1,anchor='ne')
button2= ttk.Button(win, text= "Clear", command= clear)
button2.pack(side=LEFT,expand=1,anchor='nw')

win.mainloop()

To learn more about orginizing widgets and the geometry management of tkinter, see my answer here.

Upvotes: 1

qr7NmUTjF6vbA4n8V3J9
qr7NmUTjF6vbA4n8V3J9

Reputation: 451

You can make another tk.Frame which is arranged horizontally and pack it below; for example:

entry= Entry(win, width= 40)
entry.pack()
buttons = ttk.Frame(win)
buttons.pack(pady = 5)
button1= ttk.Button(buttons, text= "Print", command=display_num)
button1.pack(side = LEFT)
button2= ttk.Button(buttons, text= "Clear", command= clear)
button2.pack()

pack with padding

Alternatively you can use the grid layout manager.

entry= Entry(win, width= 40)
entry.grid(row = 0, column = 0, columnspan = 2)
button1= ttk.Button(win, text= "Print", command=display_num)
button1.grid(row = 1, column = 0)
button2= ttk.Button(win, text= "Clear", command= clear)
button2.grid(row = 1, column = 1)

Upvotes: 3

Related Questions