다음 코드는 3 개의 단추를 만들고 각 단추에 처리기를 추가합니다. Quit 버튼이 작동하면 Give Up 버튼은 NameError unknown_search settings_change 오류를 생성하고 객체가 삭제되었음을 나타냅니다. 다음 버튼과 동일합니다. 이벤트 처리기를 클래스 외부에 배치하면 코드가 제대로 작동합니다.Ruby/TK 단추 이벤트 처리기 코드가 예상대로 실행되지 않습니다.
next_note_proc = proc {next_note}와 같은 작업을 수행하여 콜백을 작성한 경우 단추 작성에서 next_note_proc 명령을 실행하십시오. 왜 이것이 작동합니까 ??
클래스 내부 또는 외부에서 콜백이 다른 이유는 무엇입니까? 글로벌 컨텍스트에서 실행 버튼에서 실행
require 'tk'
require 'tkextlib/tile'
class App
def next_note
puts "Got next note"
end
def settings_change
puts "Got settings change"
end
def quit
puts "Got exit"
exit(1)
end
def initialize
$number_correct = TkVariable.new;
$mode = TkVariable.new
@root = TkRoot.new {title "Music Training"}
@content = Tk::Tile::Frame.new(@root) {padding "0 0 0 0"}.grid(:sticky => 'nsew')
@a = Tk::Tile::Button.new(@content) {text 'Next'; command {next_note}}.grid(:column => 1, :row => 1, :sticky => 'w')
@b = Tk::Tile::Button.new(@content) {text 'Give up'; command {settings_change}}.grid(:column => 2, :row => 1, :sticky => 'w')
@c = Tk::Tile::Button.new(@content) {text 'Quit'; command {quit}}.grid(:column => 2, :row => 2, :sticky => 'w')
TkWinfo.children(@content).each {|w| TkGrid.configure w, :padx => 0, :pady => 0}
@c.bind("1") {quit}
@a.bind("1") {next_note}
@b.bind("1") {settings_change}
puts "Starting up"
end
def run
Tk.mainloop
end
end
the_app = App.new
the_app.run
리플렉션에서 질문은 http://stackoverflow.com/questions/1723101/ruby-tk-command-binding-scope-issue와 동일합니다. – qpit3a
아직 무슨 일이 벌어지고 있는지 이해하지 마십시오. – qpit3a