≡ Menu

Clearing a TkCanvas in Ruby

Something so simple, yet so seemingly undocumented…

After struggling for about 10 minutes with trying to clear a TkCanvas from Ruby, and only finding what seemed to be one message discussing it (but not answering it), I stumbled across the answer – delete('all').

So, if I have a canvas like this:

def initialize(parent)
  @parent = parent
  ph = { 'padx' => 10, 'pady' => 10 }
  clear_b = TkButton.new(parent) { text 'Clear'; pack(ph) }
  clear_b.command{clear}
  exit_b = TkButton.new(parent) { text 'Exit'; pack(ph)}
  exit_b.command{ exit }
  @canvas = TkCanvas.new(parent)
  @canvas.pack
  @start_x = @start_y = 0
  @canvas.bind("1", lambda {|e| do_press(e.x, e.y)})
  @canvas.bind("B1-Motion",
    lambda {|x,y| do_motion(x,y)}, "%x %y")
  @canvas.bind("ButtonRelease-1",
    lambda {|x,y| do_release(x,y)}, "%x %y")
end

I can use this as the clear method to wipe the canvas:

def clear
  if @canvas
    @canvas.delete('all')
  end
end

Easy as pie! ;)

self.out