Search code examples
pythonpython-3.xtkintertkinter-button

Is it possible to reduce a button size in tkinter?


I'm working on a little text editor and currently making the buttons, on the picture bellow the 'B' button for bold. I would like to reduce his size in order to make him fit his true size, like a square box, and get rid of the extra-height.

enter image description here

How could I go below this size that seems to be the default minimum? Both the frame and button height are set to 1 and expecting an integer, so I'm not allowed to go below with something like 0.5.

top_menu = tk.Frame(root)
bold_button = tk.Button(top_menu, text='B', font=('EB Garamond ExtraBold',)) #here a tuple because tkinter needs it when the font name have multiple spaces
bold_button.pack(side='left', padx=4)

Solution

  • The width and height attributes are in units of characters (eg: 1 means the size of one average character). You can specify the width and height in units of pixels if the button has an image.

    A button can have both an image and text, so a simple trick is to add a one-pixel transparent pixel as an image, which will then allow you to specify the size in pixels.

    The padx and pady options also contributes to the size of the button. If you are trying to get a precise size, you need to set those to zero.

    Here is a simple example:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry("200x100")
    
    pixel = tk.PhotoImage(width=1, height=1)
    toolbar = tk.Frame(root)
    toolbar.pack(side="top")
    for size in (12, 16, 24, 32):
        button = tk.Button(toolbar, text=str(size), width=size, height=size,
                           image=pixel, compound="center", padx=0, pady=0)
        button.pack(side="left")
    
    root.mainloop()
    

    screenshot