At the moment I’m planning to write a Minesweeper game in Python using Tkinter.
I’m trying to find an elegant way to determine the height of the playfield buttons based on the font used on these buttons. Then I can set the colum widths of the grid to that value to get square buttons.
This is an abridged version of the code I’ve got so far:
from tkinter import Tk, Button, Frame
from tkinter.font import nametofont
CELL_SIZE = 21
class MainGui(Frame):
def __init__(self):
super().__init__()
def init(self):
self.button = Button(self)
self.button.grid(column=0, row=0, sticky="ensw")
self.columnconfigure(0, minsize=CELL_SIZE)
self.rowconfigure(0, minsize=CELL_SIZE)
self.pack()
font = nametofont(self.button.cget("font"))
print(font)
print(font.metrics())
pady2 = self.button.cget("pady")
print(pady2)
bd = self.button.cget("bd")
print(bd)
def main():
main_window = Tk()
main_gui = MainGui()
main_gui.init()
main_window.mainloop()
if __name__ == '__main__':
main()
When I look at the test output, I see that the button uses TkDefaultFont, which has a linespace of 15 pixels.
Border width (bd) of the button = 2 and pady = 1. I would expect the minimal button height to be 15 + 2×bd + 2×pady = 15 + 2×2 + 2×1 = 21 pixels.
However, at lower CELL_SIZE values the button height will never go below 26 pixels. Why 26?
I tried setting the button’s bd and pady to zero. Then I get a height of 20 pixels. That would make sense given the above. It still leaves 5 pixels unaccounted for, though.
PS: I read in another SO post that it might be a better idea to use Label’s instead of Button’s.
When using a label I do get the minimal height of 21 pixels I’d expect.
However, I’m still curious why buttons have this minimal height of 26 pixels.