簡體   English   中英

選擇目錄之前,如果目錄包含文件,則會彈出警告[Python,traitsui]

[英]Pop-up warning if directory contains file before selecting it [Python, traitsui]

我正在使用有思想的traitsui和traits模塊來制作一個簡單的GUI。

我現在擁有的代碼如下所示。 我正在尋找一種在新的Study_info實例的“基本目錄”包含一個名為“ conf.txt”的文件之前彈出警告的方法。 然后,如果study_info.base目錄不包含“ conf.txt”文件,或者如果用戶同意在警告彈出時繼續進行操作,則我將創建一個新的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()

有任何想法嗎 ? 有沒有一種方法可以覆蓋任何檢查目錄是否存在的目錄,從而還可以檢查文件夾中的文件是否存在? 如何鏈接到此以打開警告窗口?

提前謝謝了 !

在此代碼中:

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

似乎您假設如果用戶單擊OK,則configure_traits將返回true,否則返回false。 這根本不是configure_traits所做的。 (我猜這可能實際上是部分正確,但是在我可以找到的任何文檔中都未指定configure_traits的返回值)。

確切地說, configure_traits創建一個與其模型(上下文)對象相對應的視圖,並在屏幕上顯示該視圖,然后啟動其事件循環,該事件循環接管主線程(以便直到對話框退出時才返回控件)。

要執行您要執行的操作,您不應嘗試依賴configure_traits或其返回值來執行控制流。 相反,您應該使用traits豐富的事件處理系統。 這是一個簡單的示例,旨在直接說明您要執行的任務,而不是直接解決您要求的任務(有一些區別,主要是因為我不想編寫更多文本,並添加第三個有點多余的對話框,如您的示例所示):

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()

如果需要檢查特定目錄是否為空,則可以使用os.listdir()方法。 這是一個簡單的例子。 我在c:\\驅動器上有一個名為test的空文件夾,我可以使用以下代碼來測試它是否為空。

import os

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

您可以更改dir的值以測試其他任何目錄!

如果要檢查目錄是否包含特定文件,則可以使用以下代碼。 它的工作方式與上面的代碼相同,它首先檢查目錄是否為空。 如果不為空,則獲取其中所有文件的列表。 然后,它檢查是否存在您將在腳本中指定名稱的文件。 例如:在我的情況下,我在目錄c:\\test有一個名為test.txt的文件。 這是完整的代碼:

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

請注意,此腳本僅檢查給定目錄中的文件,如果該目錄包含任何子目錄,則此腳本將不檢查它們。 您可以自己嘗試一下。 ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM