Search code examples
pythontkinterwidgetlabelwidth

How do I change the width of Tkinter widgets in smaller increments (Python)?


The left side of the box is aligned with the left side of some_label. I am unable to set the width so that the right side of some_label also aligns with the right side of the box because the increments between different width values are too large. A width of 35 puts the right end of some_label too far left and a width of 36 puts it too far right.

from tkinter import *
root = Tk()

root.geometry('500x500')

box = Frame(root, width=383, height=246, bg='black')

box.place(x=241, y=65, anchor=CENTER)

some_label = Label(root, text='Some Label', borderwidth=1, relief='solid')

some_label.place(x=50, y=210)

some_label.config(width=35, font=('TkDefaultFont', 15))  # whether width is 35 or 36, the label never aligns with the box

mainloop()

Solution

  • Since you use place(), you can specify the width directly:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry('500x500')
    
    box = tk.Frame(root, width=383, height=246, bg='black')
    box.place(x=241, y=65, anchor='c')
    
    some_label = tk.Label(root, text='Some Label', borderwidth=1, relief='solid')
    some_label.place(x=241, y=210, width=383, anchor='c') # set width to same as 'box'
    some_label.config(font=('TkDefaultFont', 15))
    
    root.mainloop()