显示方形Tkinter.Button的?
为什么此代码显示的按钮比宽度高?
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()
- 所有按钮都使用
width=1, height=1
- 对于其中的每一行和每一列,
right
都有一个right.rowconfigure(rowi, weight=1)
(或columnconfigure
)调用。 - 每个按钮的每个网格位置都
b
带有粘性NSEW
。 - 我已经设定
right.grid_propagate(0)
我到底在做什么错?
如果将按钮直接放在上top
,则按钮会变得比高度宽。似乎正在调整它们的大小以适应传播的空间。如何防止调整大小?
-
如果
Button
显示文本,则在使用height
和width
选项时,它们的单位以文本为单位。为了使它们方形,使用像素单位会更好。为此,您需要将该按钮放置在中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()
编辑: 我刚刚看到您的编辑(添加您的代码)。将相同的内容应用于代码后;
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()