Home > front end >  centering a text within a button in tk
centering a text within a button in tk

Time:04-12

usually buttons in tkinter center their texts automatically but i can't seem to get it i don't know why!

from tkinter import *
from tkinter import messagebox
from PIL import Image,ImageTk
from getpass import getpass
huh=Tk()
huh.title('Login page')
huh.configure(bg='white')
huh.resizable(False,700)
huh.geometry('925x500 300 200')
my_fr=Frame(huh,width=350,height=350,bg='white')
my_fr.place(x=480,y=90)
btn=Button(my_fr,width=50,border=0,text="Connexion",bg='#000000',fg="#ffffff",font='Railway',anchor=CENTER)
btn.place(x=43,y=300)
huh.mainloop()

CodePudding user response:

Here is a solution using grid() that positions the button, with text centered, at the x, y coordinates used with the original place() statement.

Note that resizeable() takes only boolean parameters, so '700' would be interpreted as True. Assuming that a maximum window height of 700 with a minimum height of 500 was the intention, resizeable() was replaced with minsize() and maxsize() statements.

The geometry() statement was retained, but if the system's default window position is suitable, then it can be removed.

Replacing my_fr.grid() with my_fr.pack() would horizontally center the button, thus ignoring the padx specification.

import tkinter as tk

huh = tk.Tk()
huh.title('Login page')
huh.configure(bg='white')

huh.geometry('925x500 300 200')
huh.minsize(925, 500)
huh.maxsize(925, 700)

my_fr = tk.Frame(huh, bg='white')
btn = tk.Button(my_fr, width=50, text="Connexion",
                bg='black', fg="white", font='Railway')

my_fr.grid()
btn.grid(padx=43, pady=300)

huh.mainloop()
  • Related