hakeの日記

Windows環境でプログラミングの勉強をしています。

Ruby/Tk ウィジェットへのパラメータ指定方法

サンプルをみると書き方がいろいろあって混乱するのでメモ

#coding: windows-31J
require 'tk'

# Widjetのパラメータの指定方法


# newの引数として指定する方法
# 第1引数は親ウィジェット
# 第2引数以降はHashのキーと値
#   キーはStringでもSymbolでもOK
#   値も定数はSymbolでOK
TkButton.new(nil, text:'ボタン1', command:proc{puts 'Button 1 Pushed'}).pack(fill: :x)
#TkButton.new(nil, 'text'=>'ボタン1', 'command'=>proc{puts 'Button 1 Pushed'}).pack('fill'=>'x')



# blockとして指定する方法
TkButton.new(nil) do
  text( 'ボタン2' )                       # 丸カッコは省略可
  command( proc{puts 'Button 2 Pushed'} )
  pack(fill: :x)
end




# インスタンスのメソッドとして指定する方法
b3 = TkButton.new(nil)
# 値を代入
b3.text = 'ボタン3'
b3.command = proc{puts 'Button 3 Pushed'}
# 値を引数としても渡せる
#b3.text( 'ボタン3' )                    # 丸カッコは省略可
#b3.command( proc{puts 'Button 3 Pushed'} )
b3.pack(fill: :x)


Tk.mainloop