Home > Enterprise >  What is more correct to use to centralize this case
What is more correct to use to centralize this case

Time:09-08

I want to centralize frm_login using pack or grid without using another auxiliary widget. Is it possible?

I put an anchor="center" in frm_login.pack(side="left") but it didn't work.

import tkinter as tk
from tkinter import ttk

principal = tk.Tk()
principal.title("Login")
principal.resizable(False, False)
largura = 300
altura = 200
posx = int(principal.winfo_screenwidth() / 2 - largura / 2)
posy = int(principal.winfo_screenheight() / 2 - altura / 1.2)
principal.geometry("{0}x{1} {2} {3}".format(largura, altura, posx, posy))

frm_login = ttk.Frame(principal)
frm_login.pack(side="left")

lb_usuario = ttk.Label(frm_login, text="Usuário")
lb_usuario.grid(row=0, column=0, padx=5, pady=5, sticky="e")
ed_usuario = ttk.Entry(frm_login, width=24)
ed_usuario.grid(row=0, column=1, sticky="w")

lb_senha = ttk.Label(frm_login, text="Senha")
lb_senha.grid(row=1, column=0, padx=5, pady=5, sticky="e")
ed_senha = ttk.Entry(frm_login, width=24)
ed_senha.grid(row=1, column=1, sticky="w")

frm_botoes = ttk.Frame(frm_login)
frm_botoes.grid(row=2, column=1, pady=5, sticky="w")
bt_entrar = ttk.Button(frm_botoes, text="Entrar")
bt_entrar.grid(row=1, column=1)
bt_sair = ttk.Button(frm_botoes, text="Sair")
bt_sair.grid(row=1, column=2)

principal.mainloop()

enter image description here

CodePudding user response:

If you add expand=True to the call to pack, it will be centered. expand tells the packer to expand the allocated space to consume all extra space. By default the frame will be centered in the space allocated. The net result is that the frame will be centered in the window.

frm_login.pack(side="left", expand=True)

CodePudding user response:

I think this will answer your question. When you are using tkinter .grid to place your elements, you can define the weight of each column and each row. An example is the following: Let's say that I want my column number 0 to occupy less than my column number 1, for this:

main.grid_columnconfigure(0, weight=1)
main.grid_columnconfigure(1, weight=3)

In this example, the column number 1 triples the value of column 0.

This way, the elements that are placed in a column will adjust to the weight of that same column. You can do this with each column and with each row. Greetings and good luck!

  • Related