Ruby 用 TK 编写自定义对话框

africwildman · February 07, 2015 · 3017 hits

在网上没找到怎么写,根据《tcl/tk 入门》捉摸了半天,感觉应该是这么写:

#!/usr/bin/ruby
require 'tk'

class TestDialog
    def initialize parent=nil
        @b_value="CANCEL"
        @e_var=TkVariable.new
        t=TkToplevel.new parent
        t.transient
#transient告诉tk该窗口是瞬态窗口,升到最上面。目前我没看出有什么用,没有这句也照常运行。
        e=TkEntry.new(t,:textvariable=>@e_var){pack}
        b_ok=TkButton.new(t,:text=>"OK",:command=>proc{@b_value='OK';t.destroy}){pack}
        b_cancel=TkButton.new(t,:text=>"CANCEL",:command=>proc{@b_value='CANCEL';t.destroy}){pack}
        t.grab
#grab使只有本窗口接收焦点,其他窗口不能接收焦点
        t.wait_destroy
#wait_destroy等待该窗口销毁,之前我用t.wait,怎么试也不行,一查还有个wait_destroy,然后成了
    end
    def value
        @b_value
    end
    def name
        @e_var
    end
end
d=TestDialog.new
p "d.value:#{d.value}"
p "d.name:#{d.name}"
Tk.mainloop

tk 的控件不能直接输出数据,需要一个变量作代理,这也是我开始时抓狂困惑的地方。

var=TkVariable.new
entry=TkEntry.new(:textvariable=>var)
No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.