1

我在 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
4

3 回答 3

2

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

于 2014-10-02T21:49:45.293 回答
1

这是个简单的。基本上,当您执行该open_file方法时,您有机会将特征定义传递给它,而特征定义又将传递给OpenFileDialog在该便捷方法中创建的对象。您已经通过以下方式这样做了

open_file(扩展 = 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
  ...
于 2014-11-15T22:56:42.803 回答
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
于 2015-07-20T22:09:35.973 回答