Ruby + Tk command binding - scope issue?

后端 未结 2 969
花落未央
花落未央 2021-01-14 01:04

So I have this app

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

  def initialize
    @root = TkRoot.new{title \"Hello,          


        
2条回答
  •  抹茶落季
    2021-01-14 01:17

    Usually, passing blocks to Tk constructors is unnecessary. The resulting scope is confusing, so I think it should be discouraged.

    Examples of same which contain only literal values are inflexible, and teach a bad habit.

    Here, a minimal change to your program makes it work, while maintaining readability:

    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 = begin
          b = TkButton.new frame
          b.text "Press meee"
          b.command {my_fancy_function}
          b.pack
        end
        frame.pack
        Tk.mainloop
      end
    end
    
    bar = Foo.new
    

    It works for me using Ruby 2.2.5 (with Tk 8.5.12) on Windows 7.

提交回复
热议问题