Search code examples
pythonuser-interfacedirectorywxpython

WxPython limit user from moving away from a specified directory


After creating a wx.DirDialog at a certain path (ex. "C:\Users\ExampleUser\Documents"), is there a way to limit the user from moving away from the specified folder?


Solution

  • The user will be picking the file name of a photo

    So you don't want DirDialog but FileDialog
    I don't think that is a way of restricting the widget to a specific directory but you could certainly do it within your code. e.g.

    #!/usr/bin/python
    import wx
    import os
    
    class choose(wx.Frame):
        def __init__(self, parent):
            wx.Frame.__init__(self, parent, -1)
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            dirname = os.getcwd()
            dlg = wx.FileDialog(self, "Choose Image file", dirname, "", "Image files (jpg)|*.jpg|All files (*.*)|*.*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
            my_file = "No file selected"
            if dlg.ShowModal() == wx.ID_CANCEL:
                pass
            else:
                sel_dir = dlg.GetDirectory()
                if sel_dir != dirname:
                    wx.MessageBox('Please choose a file from the given directory', 'Error', wx.OK | wx.ICON_ERROR)
                else:
                    my_file = dlg.GetFilename()
            print "Chosen file:",my_file
            self.Destroy()
    
        def OnClose(self, event):
            self.Destroy()
    
    if __name__ == '__main__':
        my_app = wx.App()
        p = choose(None)
        my_app.MainLoop()