1

我正在使用 enthought traitsui 和 traits 模块来制作一个简单的 GUI。

我现在拥有的代码如下所示。如果新 Study_info 实例的“基本目录”在选择之前包含名为“conf.txt”的文件,我正在寻找一种弹出警告的方法。然后,如果 study_info.base 目录不包含“conf.txt”文件,或者用户同意在弹出警告时继续,我将创建一个新的 Study 实例。

目前,我在单击“新研究窗口”窗口的“确定”按钮后检查文件是否存在于文件夹中。我想知道有没有办法让之前的警告弹出(在目录浏览窗口中点击“确定”之后),这样如果用户点击“取消”,他/她可以直接点击“浏览”再次选择另一个文件夹(无需返回“主窗口”窗口)。现在,用户必须点击“New Study”才能选择另一个文件夹。

from traitsui.api import *
from traits.api import *
import os

class Study_info(HasTraits):
    base_directory = Directory(exists=True)
    new_study_view = View('base_directory',title="New study window", buttons=['OK','Cancel'],kind='modal')
    warning_msg = '\nWarning: Folder already contains configuration file.\n\nProceed ?\n'
    warning = View(Item('warning_msg',show_label=False,style='readonly'),title='Warning',kind='modal',buttons = ['OK','Cancel'])

class Study(HasTraits):
    def __init__(self, study_info):
        self.base_directory = study_info.base_directory
    # plus some other processing stuff
    view = View(Item('base_directory',style='readonly'))

class study_handler(Handler):
    def new_study(self, ui_info):
        new_study_info = Study_info()
        ns_res = new_study_info.configure_traits(view='new_study_view')
        if ns_res and os.path.exists(new_study_info.base_directory):
            new_study = Study(new_study_info)
            if os.path.exists(os.path.join(new_study.base_directory,'conf.txt')):
                warn_res = new_study_info.configure_traits(view='warning')
                if warn_res:
                    ui_info.ui.context["object"].study = new_study
            else:
                ui_info.ui.context["object"].study = new_study

class GUI(HasTraits):
    study = Instance(HasTraits)
    new_study = Action(name="New Study",action="new_study")
    view = View(Item('study',style='custom',show_label=False),buttons = [new_study], handler = study_handler(),title="Main window",resizable=True)

g = GUI()
g.configure_traits()

有任何想法吗 ?有没有办法覆盖任何检查该目录是否存在的目录,以便它还检查文件夹内的文件是否存在?如何链接这个以打开警告窗口?

提前谢谢了 !

4

2 回答 2

1

在这段代码中:

warn_res = new_study_info.configure_traits(view='warning')
if warn_res:
  ui_info.ui.context["object"].study = new_study

似乎您正在假设某些内容,configure_traits如果用户单击确定,则返回 true,否则返回 false。这根本不是什么configure_traits。(我想这实际上可能部分正确,但在configure_traits我能找到的任何文档中都没有指定返回值)。

准确地说,configure_traits创建一个与其模型(上下文)对象相对应的视图,并将该视图显示在屏幕上,然后启动其事件循环,该循环接管主线程(这样在对话框退出之前不会返回控制)。

做你想做的事,你不应该试图依赖configure_traits它的返回值来执行控制流。相反,您应该使用 trait 丰富的事件处理系统。这是一个简单的示例,旨在更多地说明您想要做的事情可能需要的事件处理和特定的处理程序操作,而不是直接解决您要求的任务(有一些差异,主要是因为我不想编写更多文本并添加第三个有点多余的对话框,如您的示例):

class WarningWindow(Handler):
  finished=Bool
  notify=Event

  def init_info(self,info):
    self.finished=False

  #this is a method defined on the handler that executes when the window closes
  #
  #is_ok is True if the user closed the window ok and False if the user closed 
  #the window some other way such as clicking cancel or via the window manager
  def closed(self,info,is_ok):
    self.finished=is_ok
    self.notify=True

  view=View(Label('WARNING: YOU WILL BE EATEN BY A GRUE'),buttons=OKCancelButtons)

class StudyMenu(Handler):
  warning_window=Instance(WarningWindow)
  dir=Directory
  make_study_button=Button('Make new study')
  info=Instance(UIInfo)

  def make_study(self):
    print "now make the study"

  def _make_study_button_fired(self):
    if os.path.exists(os.path.join(self.dir,'conf.txt')):
      warning_window.edit_traits()  #note, not configure_traits

  @on_trait_change('warning_window:notify')
  def warning_window_listen(self):
    if self.warning_window.finished:
    #user is OK to overwrite the conf file
       self.make_study()
    else:
    #user does not want to overwrite
       self.info.ui.dispose() #this discards the window
                              #which is the main window in this example
       print "everything is terrible!"
       sys.exit(666)

  #this is a handler method that executes when the window opens. its primary
  #purpose here is to store the window's UIInfo object in the model object.
  def init_info(self,info):
    self.info=info

StudyMenu().configure_traits()
于 2014-02-25T00:00:55.330 回答
-1

如果您需要检查特定目录是否为空,您可以使用os.listdir()方法。这是一个简单的例子。我有一个名为testat c:\drive 的空文件夹,我可以使用以下代码测试它是否为空。

import os

dir='c:\\test'
if not os.listdir(dir):
    print "Empty Dir."

您可以更改 的值dir以测试任何其他目录!

如果要检查目录是否包含特定文件,则可以使用以下代码。它的工作原理与上面的代码相同,它首先检查目录是否为空。如果它不为空,则它会获取其中所有文件的列表。然后,它会检查是否存在您将在脚本中指定的名称的文件。test.txt例如:在我的情况下,我在目录中有一个名为的文件c:\test。这是完整的代码:

import os
dir = "C:\\test"
fileName = "test.txt"
if not os.listdir(dir):
    print "Empty directory."
else:
    filesList = os.listdir(dir)
    for i in range(0,len(filesList)):
        if filesList[i]=="test.txt":
            print "Yes, there is a file with name %s in %s"%(fileName,dir)
        else:
            pass

在我的情况下的输出是:

Yes, there is a file with name test.txt in C:\test

请注意,此脚本仅检查给定目录中的文件,如果该目录包含任何子目录,则此脚本将不会检查它们。这是你可以自己尝试的东西。;)

于 2014-02-20T22:16:49.460 回答