Reputation: 39
My aim is that, as soon as I execute the program, the main window appears exactly on the center of the screen instead of any other place. By default it appears on the left side right at the top, but I did a function to move it to the center, but what I get is that the window seems like disappearing. It shows only a bar with the minimize and the X botton to close it, as this:
What am I doing wrong?
My code is down here:
from tkinter import *
from tkinter import ttk
class GUI:
def __init__(self):
self.root = Tk()
self.root.withdraw()
self.login_window = Toplevel()
self.login_window.title("Registro")
self.login_window.resizable(False, False)
self.login_window.configure(width = 400, height = 200, cursor="hand2")
self.centrar_ventana()
self.message = Label(self.login_window, text = "Registrate para continuar", font = ("Helvetica", 12, 'bold'), justify = CENTER)
self.message.place(relheight = 0.15, relx = 0.25, rely = 0.07)
self.LabelUser = Label(self.login_window, text = "Nombre de usuario: ")
self.LabelUser.place(relheight = 0.2, relx = 0.1, rely = 0.3)
self.UserName = Entry(self.login_window)
self.UserName.place(relwidth = 0.4, relheight = 0.10, relx = 0.40, rely = 0.35)
style = ttk.Style()
style.map("C.TButton", foreground=[('pressed', 'red'), ('active', 'blue')], background=[('pressed', '!disabled', 'black'), ('active', 'white')])
self.button_mainWindow = ttk.Button(self.login_window, text = "Confirmar", style="C.TButton")
self.button_mainWindow.place(relx = 0.4, rely = 0.65)
self.root.mainloop()
def centrar_ventana(self):
width = self.login_window.winfo_width()
height = self.login_window.winfo_height()
x = (self.login_window.winfo_screenwidth() // 2) - (width // 2)
y = (self.login_window.winfo_screenheight() // 2) - (height // 2)
self.login_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
GUI()
Upvotes: 2
Views: 3128
Reputation: 3942
Add update_idletasks()
:
def centrar_ventana(self):
self.root.update_idletasks() #Add this line
width = self.login_window.winfo_width()
height = self.login_window.winfo_height()
x = (self.login_window.winfo_screenwidth() // 2) - (width // 2)
y = (self.login_window.winfo_screenheight() // 2) - (height // 2)
self.login_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
This updates the window so tkinter realises that it has changed size. This means it returns the correct sizes so the window is centered properly.
Upvotes: 1