Ruby + Tk 命令绑定 - 范围问题? [英] Ruby + Tk command binding - scope issue?

查看:55
本文介绍了Ruby + Tk 命令绑定 - 范围问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个应用

require 'tk'
class Foo
  def my_fancy_function
    puts "hello, world!"
  end

  def initialize
    @root = TkRoot.new{title "Hello, world!"}
    frame = TkFrame.new
    my_fancy_button = TkButton.new(frame) do
      text "Press meee"
      command {my_fancy_function}
      pack
    end
    frame.pack
    Tk.mainloop
  end
end

bar = Foo.new

但是如果我按下按钮,我会得到NameError: undefined local variable or method `my_fancy_function' for #<TkButton:..."

But if I press the button, I get "NameError: undefined local variable or method `my_fancy_function' for #<TkButton:..."

我很确定我遗漏了一些与范围相关的小东西……我如何正确地将该命令绑定到按钮?

I'm pretty sure I'm missing something trivial related to scope... how do I bind that command to the button correctly?

好的,如果我将 my_fancy_button 块更改为参数,即

Okay, if I change my my_fancy_button block to parameters, i.e.

my_fancy_button = TkButton.new(frame, :text => "Press meee", :command => proc{my_fancy_function}).pack

然后就可以了.但为什么?

Then it works. But why?

推荐答案

如果你把一个

p self

进入代码的 do ... end 块,然后您可能会发现当前范围与您的 Foo 对象不同.

into the do ... end block of your code, then you'll probably find out that the current scope is different than your Foo object.

这篇关于Ruby + Tk 命令绑定 - 范围问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆