将默认文件目录添加到Traits中的FileDialog

时间:2014-10-02 21:00:37

标签: python file enthought traitsui

我正在使用TraitsUI中的FileDialog类,它运行得很好,除了我的生活,我还无法弄清楚如何传递默认目录,以便对话使用。

理想情况下,对话框会在本地文件系统中除树顶之外的某个位置打开...

非常感谢新手的任何见解或指导。

基本代码非常通用/标准如下。

demo_id = 'traitsui.demo.standard_editors.file_dialog.file_info'

class FileDialog ( HasTraits ):

    # The name of the selected file:
    file_name = File
    # The button used to display the file dialog:
    open = Button( 'Open...' )

    #-- Traits View Definitions ------------------------------------------------

    view = View(
        HGroup(
            Item( 'open', show_label = False ),
            '_',
            Item( 'file_name', style = 'readonly', springy = True )
        ),
        width = 0.5
    )

    #-- Traits Event Handlers --------------------------------------------------

    def _open_changed ( self ):
        """ Handles the user clicking the 'Open...' button.
        """
        file_name = open_file( extensions = FileInfo(), id = demo_id )
        if file_name != '':
            self.file_name = file_name

3 个答案:

答案 0 :(得分:1)

我建议使用TraitsUI FileDialog。我认为你可以使用pyface.api.FileDialog做得更好(特定于工具包;对于API,请参阅https://github.com/enthought/pyface/blob/master/pyface/i_file_dialog.py)。

答案 1 :(得分:0)

这很简单。基本上,当您执行open_file方法时,您有机会向其传递特征定义,这些特征将依次传递给在该便捷方法中创建的OpenFileDialog对象。您已经使用以下

进行此操作
  

open_file(extensions = FileInfo(),id = demo_id)

只需添加" file_name"的定义即可。而且你已经确定了。

  

open_file(file_name =" / foo / bar" extensions = FileInfo(),id = demo_id)

traitui.file_dialog.py的源代码中读取,您可以看到file_name从open_file传递到OpenFileDialog的机制,Handler负责表示文件对话框本身。

def open_file ( **traits ):
  ...
  fd = OpenFileDialog( **traits )
  ...

class OpenFileDialog ( Handler ):
  ...
  # The starting and current file path:
  file_name = File
  ...

答案 2 :(得分:0)

可能为时已晚,但这是一个例子:

#other traits imports
from pyface.api import FileDialog
class Something(HasTraits):
    txt_file_name = File
    openTxt = Button('Open...')
    traits_view = View( 
        VGroup( 
            HGroup(
              Item( 'openTxt', show_label = False ),
              '_',
              Item( 'txt_file_name', style = 'readonly', width = 200 ),
            ),
        )
        )
    def _openTxt_fired(self):
        """ Handles the user clicking the 'Open...' button.
        """
        extns = ['*.txt',]#seems to handle only one extension...
        wildcard='|'.join(extns)

        dialog = FileDialog(title='Select text file',
            action='open', wildcard=wildcard,
             default_path = self.txt_file_name)
        if dialog.open() == OK:
            self.txt_file_name = dialog.path
            self.openTxtFile(dialog.path)     
    def openTxtFile(self, path):
        'do something'
        print path