2015-10-30 79 views
2

當我在bash終端(Ubuntu 14.04,ruby 1.9.3)中運行以下ruby代碼時, folder_test正常工作,但my_test顯示出奇怪的行爲: 它沒有關閉gtk對話窗口,當我從 書籤中選擇一個文件夾並且焦點保留在對話框窗口上,而不是返回到終端 ,儘管所選文件夾已被正確報告給終端。 出了什麼問題,我該如何強制關閉對話窗口?Ruby中的GTK FileChooserDialog不關閉窗口

# -*- encoding : utf-8 -*- 
#!/usr/bin/ruby 

require 'gtk3' 

def get_folder(folder) 
    a=''  
    Dir.chdir(File.expand_path(folder)) { 
    dialog = Gtk::FileChooserDialog.new(
    :title => "Choose folder", :parent => nil, 
    :action => :select_folder, 
    :buttons => [[Gtk::Stock::OPEN, Gtk::ResponseType::ACCEPT], [Gtk::Stock::CANCEL, Gtk::ResponseType::CANCEL]]) 
    if dialog.run == Gtk::ResponseType::ACCEPT 
    a=dialog.filename 
    end 
    dialog.destroy } 
    return a 
end 

def folder_test 
    b=get_folder("/home") 
    if b=="/home" 
    puts "No folder chosen" 
    exit 
    end 
    puts "#{b} was choosen." 
end 

def my_test 
    while true do 
    folder_test 
    puts "Another folder?(y/n)" 
    answer=gets.chomp.downcase 
    unless answer=='y' 
     exit 
    end 
    end 
end 

#folder_test 
my_test 

回答

0

可以dialog.destroy後使用下面的代碼:

while Gtk.events_pending? 
    Gtk.main_iteration 
end 

例如:

if dialog.run == Gtk::ResponseType::ACCEPT 
    a=dialog.filename 
    end 
    dialog.destroy 
    while Gtk.events_pending? 
    Gtk.main_iteration 
    end 
    } 
    return a 
end 

DIFF:

@@ -13,7 +13,11 @@ def get_folder(folder) 
    if dialog.run == Gtk::ResponseType::ACCEPT 
    a=dialog.filename 
    end 
- dialog.destroy } 
+ dialog.destroy 
+ while Gtk.events_pending? 
+ Gtk.main_iteration 
+ end 
+ } 
    return a 
end 
+0

是的,這確實關閉對話窗口。謝謝。現在 - 之後 - 在my_test中第二次調用FileChooserDialog時,它不會獲得焦點,但會保留在背景中。任何建議如何解決這個問題? –

+0

嗯......一個解決方案之一就是在一個單獨的文件中調用get_folder方法作爲外部命令。例如:'b = \'ruby ./get_folder.rb「/ home」\'' – myokoym

+0

嗯,這對我不起作用,但幸運的是,當我通過Ubuntu中的.desktop文件啓動我的原始程序時,問題是不見了。所以一切都好,再次感謝您的幫助。 –