从函数Ruby Tk中访问局部变量

问题描述 投票:0回答:1

我希望能够从proc {}或function()内部访问局部变量。每当我尝试这样做时,都会得到此NameError: unknown option 'htmllabel' for #<Tk::Button:0x0000000004f95fc0 @path=".w00003"> (deleted widget?)。根据我的猜测和阅读的内容,这是一个范围界定的问题?

我正在尝试用来自变量的值替换标签的文本值。我的代码如下:

#title

root = TkRoot.new { title "Ruby Restful Client" }

#window size

root['geometry']='800x600'

#top side in-window opening title

TkLabel.new(root) {
    text  'Ruby Restful Client'
    pack  { side 'top'}
}
#variables

txthost=TkVariable.new
txthost.value="Enter host here"

#inputs

hostfield=TkEntry.new(root){
    width 40
    background "cyan"
    foreground "red"
    pack('side'=>'top','padx'=>10, 'pady'=>10)
}

hostfield.textvariable = txthost

TkButton.new(root){
    text "GET"
    #command proc { p txthost.value; p txtpath.value;exit }
    command proc{
            htmllabel.text=txthost.value
        }
    pack('side'=>'bottom', 'padx'=>10, 'pady'=>10)
}

codelabel=TkLabel.new(root){
    width 45
    background "cyan"
    foreground "red"
    pack('side'=>'top','padx'=>10, 'pady'=>10)
}

Tk.mainloop 

任何建议将不胜感激,谢谢您的阅读!

ruby tk
1个回答
0
投票
为了将某些东西定义为方法,请使用def关键字:

def htmllabel 42 end

为了将某些东西定义为局部变量,您可以使用赋值运算符,无需声明局部变量:局部变量在解析后会自动定义,而在解析后会自动初始化首先分配。

htmllabel = 42

© www.soinside.com 2019 - 2024. All rights reserved.