pythontkintertkinter-label

How to center tkinter label between two x coordinates


If I have a tkinter window of width 300 and height 500, what code do I use to center a label between the lines of x=100 and x=300?

import tkinter

root = tkinter.Tk()
root.geometry('300x500')

label = tkinter.Label(root, text='Test.')

label.place(???)

tkinter.mainloop()

Solution

  • import tkinter
    
    root = tkinter.Tk()
    root.geometry('300x500')
    
    label = tkinter.Label(root, text='Test.')
    
    label.place(anchor=tkinter.CENTER, relx=.5, rely=.5)
    
    tkinter.mainloop()
    

    For easier understanding

    import tkinter
    
    root = tkinter.Tk()
    root.geometry('300x500')
    root['background']='white'
    label = tkinter.Label(root, text='Test.', width=10, height=10, bg='red')
    
    label.place(anchor=tkinter.CENTER, relx=.5, rely=.5)
    
    tkinter.mainloop()