Reputation: 161
I am trying to place label at the center using place()
but when the text is changed its alignment shift to the right because of length of new word. How do I fix this using place()
.
from tkinter import *
BACKGROUND_COLOR = "#B1DDC6"
# ------------------------------ UI --------------------------------------#
window = Tk()
window.title('Flashy')
window.config(padx = 50, pady = 50,bg=BACKGROUND_COLOR )
canvas = Canvas(window, width= 800, height = 626,bg = BACKGROUND_COLOR,highlightthickness=0)
canvas.grid(row = 0, column = 0, columnspan = 2)
card_front_img = PhotoImage(file="./images/card_front.png")
canvas.create_image(400,263,image = card_front_img)
lang_label = Label(text = 'French', font = ('Ariel',40,'italic'),anchor = CENTER)
lang_label.place(x = 300, y = 100)
word_label =Label(text = 'trouva', font = ('Arial',60,'bold'),anchor= CENTER)
word_label.place(x = 250, y = 200 )
window.mainloop()
Before:
word_label =Label(text = 'trouve', font = ('Arial',60,'bold'),anchor= CENTER)
word_label.place(x = 250, y = 200 )
After:
word_label =Label(text = 'trodawdauve', font = ('Arial',60,'bold'),anchor= CENTER)
word_label.place(x = 250, y = 200 )
Upvotes: 1
Views: 1393
Reputation: 386362
If you want to use place
, you simply need to set the anchor
attribute to "n"
(north). That will cause the "north" (top-center) portion of the widget to be at the specified coordinates. Using "s"
(south) or "c"
(center) would give a similar effect, though it changes which part of the label is at the given y coordinate.
lang_label.place(x = 250, y = 100, anchor="n")
word_label.place(x = 250, y = 200, anchor="n" )
No matter how long the text in world_label
is, it will always be centered at the exact same point as lang_label
.
Note: the x and y coordinates are just for illustrative purposes, you'll want to compute them to be the appropriate value for where you want them to be. The point being, if the x coordinate is the same, the labels will be centered with respect to each other.
Upvotes: 1
Reputation: 25
You can also create a frame that's centered and then place the label onto it. Here's a great website that really helped me learn thinker: https://www.tutorialspoint.com/python/python_gui_programming.htm
Upvotes: 0
Reputation: 161
I found an alternative which works fine but doesn't use the place()
.By using canvas.create_text()
instead of place()
the text aligns itself in the centre irrespective of the length of the word
canvas.create_text(400,150, text='French', font=('Ariel', 40, 'italic'))
canvas.create_text(400,263, text='wordwdawdadawd', font=('Ariel', 60, 'bold'))
Upvotes: 1