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

Time:11-21

First, I read the related discussion: enter image description here

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related