Home > Software design >  How to align widgets in Tkinter to center
How to align widgets in Tkinter to center

Time:10-20

I am working on a simple counter app in tkinter. I rigged up some code looking at few tutorial on web. All the functions of a counter are set up. But when it comes to the designing of the app, I want the Count, the Count button, and the reset button to be aligned at the center.

The code is as below

from tkinter import Label, Button, Tk
from tkinter import font


window = Tk()

window.geometry('500x500')

window.title("Counter")

window.count = 0

def increment():
    window.count  = 1
    lbl.configure(text=window.count)


def reset():
    window.count = 0
    lbl.configure(text=window.count)


lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.grid(column=0, row=0)

btn1 = Button(window, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(window, text="Reset", command=reset)
btn2.grid(column=1, row=1)

btn1['font'] = btn2['font'] = font.Font(size=30)

window.mainloop()

A Screenshot of my counter app is here

Tkinter Count app screenshot

Any help in this aspect will be appreciated.

Thanks,

CodePudding user response:

It is easier to use pack() instead of grid() for your requirement.

lbl = Label(window, text="0", font=("Apple Braille", 60))
lbl.pack()

# frame for the two buttons
frame = Frame(window)
frame.pack()

btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)

If you want to put at the center of the window:

# frame for the label and buttons
frame = Frame(window)
frame.place(relx=0.5, rely=0.5, anchor="c") # put at center of window

lbl = Label(frame, text="0", font=("Apple Braille", 60))
lbl.grid(row=0, column=0, columnspan=2)

btn1 = Button(frame, text="Count", command=increment)
btn1.grid(column=0, row=1)

btn2 = Button(frame, text="Reset", command=reset)
btn2.grid(column=1, row=1)
  • Related