在Ruby中使用GTK3进度条

时间:2018-06-03 21:26:22

标签: ruby progress-bar gtk3

这是我的代码:

require "gtk3"
builder_file = "#{File.expand_path(File.dirname(__FILE__))}/example.ui"
builder = Gtk::Builder.new(:file => builder_file)
window = builder.get_object("window")
window.signal_connect("destroy") { Gtk.main_quit }
progressbar=builder.get_object("progressbar1")
progressbar.set_fraction(0.5)
button = builder.get_object("button1")
button.signal_connect("clicked") {
  for i in(0..4)
    sleep(1)
    puts "query " + (i+1).to_s + " done"
    a=(i+1)/5.to_f
    puts a
    progressbar.set_fraction(a)
  end
  }
Gtk.main

sleep只是网页查询的占位符,大约需要1秒钟。当我在我的机器上执行此代码时,控制台输出正常,但进度条保持空白,直到它在五秒后跳转到满,这不是我想要的。如何使用进度条?

1 个答案:

答案 0 :(得分:2)

GUI工具的事件循环(Gtk,Tk等)和Ruby的集成使包括我在内的初学者感到厌烦。我知道两种方式。

1.add thread

require 'gtk3'

win = Gtk::Window.new('Sample')
win.signal_connect('destroy') { Gtk.main_quit }

box = Gtk::Box.new(:vertical)

pb = Gtk::ProgressBar.new
pb.set_fraction(0.5)

b = Gtk::Button.new(label: 'Button')
b.signal_connect('clicked') do
  Thread.new do
    5.times do |i|
      sleep 1
      pb.fraction = (i + 1) / 5.0
    end
  end
end

win.add box
box.pack_start pb
box.pack_start b

win.show_all

Gtk.main

2.使用GLib :: Timeout

b.signal_connect('clicked') do
    i = 0.0
    GLib::Timeout.add(1000) do |a|
           i += 0.2
           pb.fraction = i
           i < 1.0 # return false and stop when i >= 1.0
    end
end