简体   繁体   中英

With Tkinter, how to make ttk.Button size fit to its text?

I looked through the Button widget's options, but couldn't find anything that looks like "fit to content" there.

Do I have to set size explicitly in order to fit the button size to its text ?

Example:

import tkinter as TK
from tkinter import ttk

root = TK.Tk()
root.title('Buttons bigger than text')
root.geometry('{}x{}+0+0'.format(800, 800))
root.resizable(width=False, height=False)

mainFrame = TK.Frame(root, bg='green')
mainFrame.pack(side="top", fill="both", expand=True)

for r in range(0, 5):
    row = TK.Frame(mainFrame, bg='blue')
    mainFrame.grid_rowconfigure(r, weight=1)
    mainFrame.grid_columnconfigure(0, weight=1)
    row.pack(side="top", fill="both", expand=True)
    bt1 = ttk.Button(row, text='mybutton')
    bt2 = ttk.Button(row, text='?')
    row.grid_rowconfigure(0, weight=1)
    row.grid_columnconfigure(0, weight=1)
    row.grid_columnconfigure(1, weight=1)
    bt1.grid(row=0, column=0, sticky='nsw')
    bt2.grid(row=0, column=1, sticky='nsw')
root.mainloop()

Is it a ttk.Button specific issue? I tested with Tk.Button and it worked as expected.

Environment

Python 3.6.4 Homebrew on macOS High Sierra.

By default, button widgets will try to fit their text. That is their documented behavior. You're explicitly asking for them to stretch to fill their space when you use the sticky option.

Also, on OSX specifically, I think there may be limitations in the minimum size of the button when using the native theme, but I could be mistaken.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM