Displaying square Tkinter.Button's?

前端 未结 2 1513
广开言路
广开言路 2020-12-21 02:04

Why does this code display buttons taller than they are wide?

import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = \"right\         


        
2条回答
  •  别那么骄傲
    2020-12-21 02:23

    Another method is to trick the Button into thinking it's displaying an image, so its units can be manipulated by pixels instead of text-size.

    You can do this by creating an empty instance of PhotoImage, setting it to the image option of the button, and using the compound option of the button to combine the "image" and text. Here's an example using part of your code:

    import Tkinter, tkFont
    
    
    root = Tkinter.Tk()
    
    font = tkFont.Font(family="Helvetica", size=60, weight = tkFont.BOLD)
    blank_image = Tkinter.PhotoImage()
    
    for i in xrange(6):
        b = Tkinter.Button(root, image=blank_image, text=str(i),
                           font=font, compound=Tkinter.CENTER)
    
        # get the height of the font to use as the square size
        square_size = font.metrics('linespace')
        b.config(width=square_size, height=square_size)
    
        b.grid(row = i/3, column = i%3, sticky = "NWSE")
    
    root.mainloop()
    

提交回复
热议问题