Python : How To Center Label In Tkinter Window
Solution 1:
Have you considered using the .pack() method instead for this. You could achieve the desired effect far easier that way:
from tkinter import *
root = Tk()
top = Toplevel(root)
w = '400'
h = '100'
top.geometry('{}x{}'.format(w, h))
frame = Frame(top)
label = Label(frame, text="This is an error message")
button = Button(frame, text="Ok")
frame.pack(expand=True) #expand assigns additional space to the frame if the parent is expanded
label.pack()
button.pack()
root.mainloop()
After some research, doing this with grid is an awful lot easier than expected, see below:
from tkinter import *
root = Tk()
w = '400'
h = '100'
root.geometry('{}x{}'.format(w, h))
label = Label(root, text="text")
label.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.mainloop()
If we assign .rowconfigure() and .columnconfigure() a weight which is not 0 then the specified row and column will expand to fill the space given to it in the window.
Solution 2:
A way to center Frame inside root window can be done in this manner:
Part A) Create A window with a specific size
h,w(since it is a popup - in this example I disable resizing it ). Inside the frame- aLabeland aButton:
root = Tk()
w = '200'
h = '80'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen') ###To diff between root & Frame
root.resizable(False, False)
txt = StringVar()
txt.set("This is an error message")
testframe = ttk.Frame(root)
testframe.grid(row=0, column=1)
label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0, pady=10)
ok_button = ttk.Button(testframe, text="OK", command=root.destroy)
ok_button.grid()
Part B) In order to get frame's dimensions ( including
LabelandButtoninside ) we usetestframe.update()and thentestframe.winfo_width()testframe.winfo_height()to obtain frame's updated values.xbiasandybiascalculates the center to place the frame in the middle:
testframe.update()
xbias = int(w) / 2 - testframe.winfo_width() / 2
ybias = int(h) / 2- testframe.winfo_height() / 2
testframe.grid(row=0, column=1, pady=ybias, padx=xbias)
root.mainloop()
Solution 3:
A little late but I've found that using the anchor makes it easier to center a label in the window.
from tkinter import *
root = Tk()
w = 100
h = 100
root.geometry(f"{w}x{h}")
label = Label(root, text="text")
label.place(anchor=CENTER, relx=0.5, rely=0.5)
root.mainloop()
Post a Comment for "Python : How To Center Label In Tkinter Window"