From: Hidetoshi NAGAI Date: 2005-06-24T12:35:50+09:00 Subject: Re: ruby/tk question From: Joe Van Dyk Subject: ruby/tk question Date: Fri, 24 Jun 2005 09:36:15 +0900 Message-ID: > I have to draw a colored bar in a Tk application that has differently > colored segments. > > Like: > > ---------------------------------------- > | red | green | orange | > ---------------------------------------- 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[i] / @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, :orange).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 ----------------------------------------------------------- -- Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)