ruby, tk 库。 getopenfile 的输出

ruby, tk lib. Output from getopenfile

我正在尝试通过 ruby/tk 库加载多个文件并将它们放入数组中:

def openFiles
return Tk.getOpenFile(  'title' => 'Select Files',
                        'multiple' => true, 
                        'defaultextension' => 'csv',
                        'filetypes' => "{{Comma Seperated Values} {.csv}} {TXT {.txt}} {All files {.*}}")
end

然后在代码中

filess = TkVariable.new()

button1 = TkButton.new(root){
text 'Open Files'
command (proc {filess.value = openFiles; puts filess; puts filess.class; puts filess.inspect})

}.grid(:column => 1, :row => 1, :sticky => 'we')

问题是我无法设法将输出作为数组获取,我不知道这是否可能,否则我将不得不以某种方式解析输出。嗯?请帮忙。谢谢。

这是我点击按钮时的输出:

C:\file1
C:\file2
TkVariable
#<TkVariable: v00000>

我觉得应该是:(数组部分)

['C:\file1','C:\file2']

TkVariable 实现 #to_a,您可以使用它来将其 value 转换为您想要的 Array

button1 = TkButton.new(root) {
  text 'Open Files'
  command (proc do
    filess.value = openFiles
    puts filess.to_a.class
    puts filess.to_a.inspect
  end)
}.grid(:column => 1, :row => 1, :sticky => 'we')
Array
["C:\file1", "C:\file2"]

这对我在 Windows 7:

上使用 Ruby 2.2.5(使用 Tk 8.5.12)有效
require 'tk'

def extract_filenames_as_ruby_array(file_list_string)
  ::TkVariable.new(file_list_string).list
end

def files_open
  descriptions = %w[
      Comma\ Separated\ Values
      Text\ Files
      All\ Files
      ]
  extensions = %w[  {.csv}  {.txt}  *  ]
  types = descriptions.zip(extensions).map {|d,e| "{#{d}} #{e}" }
  file_list_string = ::Tk.getOpenFile \
      filetypes: types,
      multiple: true,
      title: 'Select Files'
  extract_filenames_as_ruby_array file_list_string
end

def lambda_files_open
  @lambda_files_open ||= ::Kernel.lambda do
    files = files_open
    puts files
  end
end

def main
  b_button_1
  ::Tk.mainloop
end

# Tk objects:

def b_button_1
  @b_button_1 ||= begin
    b = ::Tk::Tile::Button.new root
    b.command lambda_files_open
    b.text 'Open Files'
    b.grid column: 1, row: 1, sticky: :we
  end
end

def root
  @root ||= ::TkRoot.new
end

main

作为参考,Tk.getOpenFileTk Commands and Ruby 文档中进行了解释。