Search code examples
tkintertkinter-button

How to control tkinter Button width with left alignment?


Consider this:

from tkinter import mainloop, Button
import tkinter as tk

def cmd():
    print('Hello World')

class my_class(tk.Tk):
    def __init__(self):
        super().__init__()
        Button(self, text="Button A", command = cmd ).place(x=10, y=10)
        Button(self, text="Button B has a long name", command = cmd).place(x=10, y=60)
        Button(self, text="Button C has a long name", command = cmd, width = 25 ).place(x=10, y=110)
        Button(self, text="Button D", command = cmd, width = 25 ).place(x=10, y=160) 
           
    
if __name__ == '__main__':
    app = my_class()
    app.geometry = ('400x300')
    app.mainloop()

That give the following.

tkinter Buttons

Text in the two upper buttons is left aligned, but the buttons have different width. Text in the two lower buttons is centered in the buttons, but the buttons have the same width. How do I make text in all the buttons left aligned AND make all the button the same width?


Solution

  • "How do I make text in all the buttons left aligned AND make all the button the same width?"

    Set all buttons to the same width and anchor them to the "w"est

    from tkinter import mainloop, Button
    import tkinter as tk
    
    def cmd():
        print('Hello World')
    
    class my_class(tk.Tk):
        def __init__(self):
            super().__init__()
            Button(self, text="Button A", command = cmd, width=25, anchor = 'w').place(x=10, y=10)
            Button(self, text="Button B has a long name", command = cmd, width = 25, anchor = 'w').place(x=10, y=60)
            Button(self, text="Button C has a long name", command = cmd, width = 25, anchor = 'w' ).place(x=10, y=110)
            Button(self, text="Button D", command = cmd, width = 25, anchor = 'w' ).place(x=10, y=160)
    
    
    if __name__ == '__main__':
        app = my_class()
        app.geometry = ('400x300')
        app.mainloop()
    

    enter image description here