≡ 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) }
  exit_b = TkButton.new(parent) { text 'Exit'; pack(ph)}
  exit_b.command{ exit }
  @canvas = TkCanvas.new(parent)
  @start_x = @start_y = 0
  @canvas.bind("1", lambda {|e| do_press(e.x, e.y)})
    lambda {|x,y| do_motion(x,y)}, "%x %y")
    lambda {|x,y| do_release(x,y)}, "%x %y")

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

def clear
  if @canvas

Easy as pie! ;)