tkFileDialog.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #
  2. # Instant Python
  3. # $Id: tkFileDialog.py 36560 2004-07-18 06:16:08Z tim_one $
  4. #
  5. # tk common file dialogues
  6. #
  7. # this module provides interfaces to the native file dialogues
  8. # available in Tk 4.2 and newer, and the directory dialogue available
  9. # in Tk 8.3 and newer.
  10. #
  11. # written by Fredrik Lundh, May 1997.
  12. #
  13. #
  14. # options (all have default values):
  15. #
  16. # - defaultextension: added to filename if not explicitly given
  17. #
  18. # - filetypes: sequence of (label, pattern) tuples. the same pattern
  19. # may occur with several patterns. use "*" as pattern to indicate
  20. # all files.
  21. #
  22. # - initialdir: initial directory. preserved by dialog instance.
  23. #
  24. # - initialfile: initial file (ignored by the open dialog). preserved
  25. # by dialog instance.
  26. #
  27. # - parent: which window to place the dialog on top of
  28. #
  29. # - title: dialog title
  30. #
  31. # - multiple: if true user may select more than one file
  32. #
  33. # options for the directory chooser:
  34. #
  35. # - initialdir, parent, title: see above
  36. #
  37. # - mustexist: if true, user must pick an existing directory
  38. #
  39. #
  40. from tkCommonDialog import Dialog
  41. class _Dialog(Dialog):
  42. def _fixoptions(self):
  43. try:
  44. # make sure "filetypes" is a tuple
  45. self.options["filetypes"] = tuple(self.options["filetypes"])
  46. except KeyError:
  47. pass
  48. def _fixresult(self, widget, result):
  49. if result:
  50. # keep directory and filename until next time
  51. import os
  52. # convert Tcl path objects to strings
  53. try:
  54. result = result.string
  55. except AttributeError:
  56. # it already is a string
  57. pass
  58. path, file = os.path.split(result)
  59. self.options["initialdir"] = path
  60. self.options["initialfile"] = file
  61. self.filename = result # compatibility
  62. return result
  63. #
  64. # file dialogs
  65. class Open(_Dialog):
  66. "Ask for a filename to open"
  67. command = "tk_getOpenFile"
  68. def _fixresult(self, widget, result):
  69. if isinstance(result, tuple):
  70. # multiple results:
  71. result = tuple([getattr(r, "string", r) for r in result])
  72. if result:
  73. import os
  74. path, file = os.path.split(result[0])
  75. self.options["initialdir"] = path
  76. # don't set initialfile or filename, as we have multiple of these
  77. return result
  78. if not widget.tk.wantobjects() and "multiple" in self.options:
  79. # Need to split result explicitly
  80. return self._fixresult(widget, widget.tk.splitlist(result))
  81. return _Dialog._fixresult(self, widget, result)
  82. class SaveAs(_Dialog):
  83. "Ask for a filename to save as"
  84. command = "tk_getSaveFile"
  85. # the directory dialog has its own _fix routines.
  86. class Directory(Dialog):
  87. "Ask for a directory"
  88. command = "tk_chooseDirectory"
  89. def _fixresult(self, widget, result):
  90. if result:
  91. # convert Tcl path objects to strings
  92. try:
  93. result = result.string
  94. except AttributeError:
  95. # it already is a string
  96. pass
  97. # keep directory until next time
  98. self.options["initialdir"] = result
  99. self.directory = result # compatibility
  100. return result
  101. #
  102. # convenience stuff
  103. def askopenfilename(**options):
  104. "Ask for a filename to open"
  105. return Open(**options).show()
  106. def asksaveasfilename(**options):
  107. "Ask for a filename to save as"
  108. return SaveAs(**options).show()
  109. def askopenfilenames(**options):
  110. """Ask for multiple filenames to open
  111. Returns a list of filenames or empty list if
  112. cancel button selected
  113. """
  114. options["multiple"]=1
  115. return Open(**options).show()
  116. # FIXME: are the following perhaps a bit too convenient?
  117. def askopenfile(mode = "r", **options):
  118. "Ask for a filename to open, and returned the opened file"
  119. filename = Open(**options).show()
  120. if filename:
  121. return open(filename, mode)
  122. return None
  123. def askopenfiles(mode = "r", **options):
  124. """Ask for multiple filenames and return the open file
  125. objects
  126. returns a list of open file objects or an empty list if
  127. cancel selected
  128. """
  129. files = askopenfilenames(**options)
  130. if files:
  131. ofiles=[]
  132. for filename in files:
  133. ofiles.append(open(filename, mode))
  134. files=ofiles
  135. return files
  136. def asksaveasfile(mode = "w", **options):
  137. "Ask for a filename to save as, and returned the opened file"
  138. filename = SaveAs(**options).show()
  139. if filename:
  140. return open(filename, mode)
  141. return None
  142. def askdirectory (**options):
  143. "Ask for a directory, and return the file name"
  144. return Directory(**options).show()
  145. # --------------------------------------------------------------------
  146. # test stuff
  147. if __name__ == "__main__":
  148. # Since the file name may contain non-ASCII characters, we need
  149. # to find an encoding that likely supports the file name, and
  150. # displays correctly on the terminal.
  151. # Start off with UTF-8
  152. enc = "utf-8"
  153. import sys
  154. # See whether CODESET is defined
  155. try:
  156. import locale
  157. locale.setlocale(locale.LC_ALL,'')
  158. enc = locale.nl_langinfo(locale.CODESET)
  159. except (ImportError, AttributeError):
  160. pass
  161. # dialog for openening files
  162. openfilename=askopenfilename(filetypes=[("all files", "*")])
  163. try:
  164. fp=open(openfilename,"r")
  165. fp.close()
  166. except:
  167. print "Could not open File: "
  168. print sys.exc_info()[1]
  169. print "open", openfilename.encode(enc)
  170. # dialog for saving files
  171. saveasfilename=asksaveasfilename()
  172. print "saveas", saveasfilename.encode(enc)