ruby/tk question

J

Joe Van Dyk

I have to draw a colored bar in a Tk application that has differently
colored segments.

Like:

----------------------------------------
| red | green | orange |
----------------------------------------

What widget do I want to use for that? Canvas?

Thanks,
Joe
 
H

Hidetoshi NAGAI

From: Joe Van Dyk <[email protected]>
Subject: ruby/tk question
Date: Fri, 24 Jun 2005 09:36:15 +0900
Message-ID: said:
I have to draw a colored bar in a Tk application that has differently
colored segments.

Like:

Although I may misunderstand, is the following what you want?
-----------------------------------------------------------
require 'tk'

class ColoredBar < TkWindow
@@DEFAULT_HEIGHT = 5
@@DEFAULT_WIDTH = 100

def initialize(parent, *cols)
if parent.kind_of?(Symbol) || parent.kind_of?(String)
cols.unshift(parent)
parent = nil
end

@frame = TkFrame.new(parent,
:height=>@@DEFAULT_HEIGHT, :width=>@@DEFAULT_WIDTH)
@path = @frame.path

@sum = 0.0
@ratio = []
@cols = cols.collect{|c|
@ratio << 1.0
@sum += 1.0
TkFrame.new(@frame, :background=>c)
}

TkGrid.configure(*(@cols + [:sticky=>:news]))
@frame.grid_rowconfigure(0, :weight=>1)
(0...(@cols.size)).each{|i| @frame.grid_columnconfigure(i, :weight=>1) }
TkGrid.propagate(@frame, false)

@frame.bind('Configure'){ _config_ratio }
end

def _config_ratio
frame_width = @frame.winfo_width
@cols.each_with_index{|c, i|
c.width(frame_width * @ratio / @sum)
}
end
private :_config_ratio

def ratio(*params)
if @cols.length != params.length
raise ArgumentError, "params length doesn't match colors length"
end

sum = 0.0
params.each{|n|
raise ArgumentError, "params must be positive values" if n < 0
sum += n
}

@sum = sum
@ratio = params.dup

_config_ratio

self
end
end

if __FILE__ == $0
b = ColoredBar.new:)red, :green, :eek:range).pack:)expand=>true, :fill=>:both)
b.width 300
b.height 20

TkButton.new:)text=>'ratio 1:1:1', :command=>proc{b.ratio(1,1,1)}).pack
TkButton.new:)text=>'ratio 1:2:3', :command=>proc{b.ratio(1,2,3)}).pack
TkButton.new:)text=>'ratio 0.25:0.82:0.16',
:command=>proc{b.ratio(0.25,0.82,0.16)}).pack

Tk.mainloop
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top