显示方形Tkinter.Button的?

eal*_*nso 4 python tkinter

为什么这段代码显示的按钮比它们宽?

import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = "right")
font = tkFont.Font(family="Helvetica", size=60, weight = tkFont.BOLD)

for i in xrange(6):
    b = Tkinter.Button(right, text = str(i), font = font, width = 1, height = 1)
    top.rowconfigure(i, weight = 1)
    top.columnconfigure(i, weight = 1)
    b.grid(row = i/3, column = i%3, sticky = "NWSE")

top.mainloop()
Run Code Online (Sandbox Code Playgroud)
  • 所有按钮都是用.创建的 width=1, height=1
  • 对于每一行和每一列right都有一个right.rowconfigure(rowi, weight=1)(或到columnconfigure)的调用.
  • 每个按钮的每个网格放置b都是粘性的NSEW.
  • 我已经设定 right.grid_propagate(0)

我究竟做错了什么?

如果我直接按下按钮top,按钮就会变得比高大.它们似乎正在调整大小以适应传播的空间.如何防止此大小调整?

Laf*_*los 6

如果Button显示文本,则在使用heightwidth选项时,它们的单位为文本单位.为了使它们成方形,使用像素单元会更好.为此,您需要将该按钮放在a中Frame,并确保框架不会传播(grid_propagate)并允许其子项填充它(columnconfigure&rowconfigure).

这只是一个例子,因为我没有看到你的代码.

import Tkinter as tk

master = tk.Tk()

frame = tk.Frame(master, width=40, height=40) #their units in pixels
button1 = tk.Button(frame, text="btn")


frame.grid_propagate(False) #disables resizing of frame
frame.columnconfigure(0, weight=1) #enables button to fill frame
frame.rowconfigure(0,weight=1) #any positive number would do the trick

frame.grid(row=0, column=1) #put frame where the button should be
button1.grid(sticky="wens") #makes the button expand

tk.mainloop()
Run Code Online (Sandbox Code Playgroud)

编辑:我刚看到你的编辑(添加你的代码).将相同的内容应用于您的代码后;

import Tkinter, tkFont
top = Tkinter.Tk()
right = Tkinter.Frame(top)
right.pack(side = "right")
font = tkFont.Font(family="Helvetica", size=20, weight = tkFont.BOLD)

for i in xrange(6):
    f = Tkinter.Frame(right,width=50,height=50)
    b = Tkinter.Button(f, text = str(i), font = font)

    f.rowconfigure(0, weight = 1)
    f.columnconfigure(0, weight = 1)
    f.grid_propagate(0)

    f.grid(row = i/3, column = i%3)
    b.grid(sticky = "NWSE")

top.mainloop()
Run Code Online (Sandbox Code Playgroud)