grid虽然简单,但是本人想通过grid,说些其它的问题。tk的资料本来就比较少,而ruby tk的资料当然就更少了,所以需要一点一点的去尝试。
先帖上一个图:
接下来帖上代码:
require 'tk'
root = TkRoot.new {
title "布局测试"
minsize(200,200)
}
frame = TkFrame.new do
relief 'sunken'
borderwidth 3
background "red"
padx 15
pady 20
pack('side' => 'left')
end
TkButton.new(frame) do
text "按钮1"
background "#ccc"
grid :column=>1,:row=>1,:ipadx=>10,:ipady=>10
end
TkButton.new(frame) do
text "按钮2"
background "#ccc"
grid :column=>2,:row=>2
end
TkButton.new(frame) do
text "删除整个frame"
background "#ccc"
command{
frame.unpack
TkLabel.new do
text "删除整个frame成功!"
pack
end
}
grid :column=>0,:row=>0,:rowspan=>5,:sticky=>"nsew"
end
TkButton.new(frame) do
text "按钮4"
background "#ccc"
grid :column=>2,:row=>1
end
button5 = TkButton.new(frame) do
text "按钮5"
background "#ccc"
grid :column=>1,:row=>2
end
TkButton.new(frame) do
text "删除按钮5"
background "#ccc"
command{button5.grid_forget}
grid :column=>1,:row=>4,:columnspan=>3,:sticky=>"nsew"
end
Tk.mainloop
针对这段代码,讲几点:
1.使用grid布局后,就不要再使用pack方式了。
2.跨行、跨列使用columnspan、rowspan这两个属性,但是如果只使用这两个属性的话,按钮只会占据中间的一个格式,不会自动填满。如果要自动占满整行或整列,需要使用sticky属性。关于sticky这个属性,英文的描述是这样的:
The value associated with -sticky is a string containing the compass points to which the widget should "stick." If the widget should always "stick" to the top of the cell, you would use -sticky => "n". To force the widget to fill the cell completely, use -sticky => "nsew". To make the widget as tall as the cell but only as wide as it needs to be, use -sticky => "ns". The string value can contain commas and whitespace, but they will be ignored. These two statements are equivalent:
3.关于ipadx、ipady,其实前一篇博客已经说了,再引用一下吧:
-ipadx => amount $widget becomes larger in x direction by 2 ✕ amount.
-ipady => amount $widget becomes larger in y direction by 2 ✕ amount.
-padx => amount Buffer space equal to amount is placed to left and right of widget.
-pady => amount Buffer space equal to amount is placed on top and bottom of widget.
4.其实本人最想说的,是关于怎么来删除按钮或者整个frame,在上面的图中,就实现了这两个功能。删除按钮,使用的是grid_forget方法,而删除frame,使用的是unpack。这两个功能是很重要的,在JAVA 的SWING中,一般通过设置显示或隐藏的方法(专门有设置一个组件显示或隐藏的方法),而在TK中,翻遍了所有资料,就是没找到,最后在翻看ruby源代码时,看见这个方法有点像,试了下果然行,真是不容易!