ruby,tk lib。从getopenfile输出

问题描述 投票:2回答:2

我试图通过ruby / tk lib加载多个文件并将它们放入数组:

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']
arrays ruby tk
2个回答
2
投票

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"]

0
投票

这对我在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 CommandsRuby文档中有解释。

© www.soinside.com 2019 - 2024. All rights reserved.