我正试图通过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']
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.getOpenFile
在Tk命令和Ruby文档中进行了解释。