textview.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Simple text browser for IDLE
  2. """
  3. from tkinter import Toplevel, Text, TclError,\
  4. HORIZONTAL, VERTICAL, NS, EW, NSEW, NONE, WORD, SUNKEN
  5. from tkinter.ttk import Frame, Scrollbar, Button
  6. from tkinter.messagebox import showerror
  7. from functools import update_wrapper
  8. from idlelib.colorizer import color_config
  9. class AutoHideScrollbar(Scrollbar):
  10. """A scrollbar that is automatically hidden when not needed.
  11. Only the grid geometry manager is supported.
  12. """
  13. def set(self, lo, hi):
  14. if float(lo) > 0.0 or float(hi) < 1.0:
  15. self.grid()
  16. else:
  17. self.grid_remove()
  18. super().set(lo, hi)
  19. def pack(self, **kwargs):
  20. raise TclError(f'{self.__class__.__name__} does not support "pack"')
  21. def place(self, **kwargs):
  22. raise TclError(f'{self.__class__.__name__} does not support "place"')
  23. class ScrollableTextFrame(Frame):
  24. """Display text with scrollbar(s)."""
  25. def __init__(self, master, wrap=NONE, **kwargs):
  26. """Create a frame for Textview.
  27. master - master widget for this frame
  28. wrap - type of text wrapping to use ('word', 'char' or 'none')
  29. All parameters except for 'wrap' are passed to Frame.__init__().
  30. The Text widget is accessible via the 'text' attribute.
  31. Note: Changing the wrapping mode of the text widget after
  32. instantiation is not supported.
  33. """
  34. super().__init__(master, **kwargs)
  35. text = self.text = Text(self, wrap=wrap)
  36. text.grid(row=0, column=0, sticky=NSEW)
  37. self.grid_rowconfigure(0, weight=1)
  38. self.grid_columnconfigure(0, weight=1)
  39. # vertical scrollbar
  40. self.yscroll = AutoHideScrollbar(self, orient=VERTICAL,
  41. takefocus=False,
  42. command=text.yview)
  43. self.yscroll.grid(row=0, column=1, sticky=NS)
  44. text['yscrollcommand'] = self.yscroll.set
  45. # horizontal scrollbar - only when wrap is set to NONE
  46. if wrap == NONE:
  47. self.xscroll = AutoHideScrollbar(self, orient=HORIZONTAL,
  48. takefocus=False,
  49. command=text.xview)
  50. self.xscroll.grid(row=1, column=0, sticky=EW)
  51. text['xscrollcommand'] = self.xscroll.set
  52. else:
  53. self.xscroll = None
  54. class ViewFrame(Frame):
  55. "Display TextFrame and Close button."
  56. def __init__(self, parent, contents, wrap='word'):
  57. """Create a frame for viewing text with a "Close" button.
  58. parent - parent widget for this frame
  59. contents - text to display
  60. wrap - type of text wrapping to use ('word', 'char' or 'none')
  61. The Text widget is accessible via the 'text' attribute.
  62. """
  63. super().__init__(parent)
  64. self.parent = parent
  65. self.bind('<Return>', self.ok)
  66. self.bind('<Escape>', self.ok)
  67. self.textframe = ScrollableTextFrame(self, relief=SUNKEN, height=700)
  68. text = self.text = self.textframe.text
  69. text.insert('1.0', contents)
  70. text.configure(wrap=wrap, highlightthickness=0, state='disabled')
  71. color_config(text)
  72. text.focus_set()
  73. self.button_ok = button_ok = Button(
  74. self, text='Close', command=self.ok, takefocus=False)
  75. self.textframe.pack(side='top', expand=True, fill='both')
  76. button_ok.pack(side='bottom')
  77. def ok(self, event=None):
  78. """Dismiss text viewer dialog."""
  79. self.parent.destroy()
  80. class ViewWindow(Toplevel):
  81. "A simple text viewer dialog for IDLE."
  82. def __init__(self, parent, title, contents, modal=True, wrap=WORD,
  83. *, _htest=False, _utest=False):
  84. """Show the given text in a scrollable window with a 'close' button.
  85. If modal is left True, users cannot interact with other windows
  86. until the textview window is closed.
  87. parent - parent of this dialog
  88. title - string which is title of popup dialog
  89. contents - text to display in dialog
  90. wrap - type of text wrapping to use ('word', 'char' or 'none')
  91. _htest - bool; change box location when running htest.
  92. _utest - bool; don't wait_window when running unittest.
  93. """
  94. super().__init__(parent)
  95. self['borderwidth'] = 5
  96. # Place dialog below parent if running htest.
  97. x = parent.winfo_rootx() + 10
  98. y = parent.winfo_rooty() + (10 if not _htest else 100)
  99. self.geometry(f'=750x500+{x}+{y}')
  100. self.title(title)
  101. self.viewframe = ViewFrame(self, contents, wrap=wrap)
  102. self.protocol("WM_DELETE_WINDOW", self.ok)
  103. self.button_ok = button_ok = Button(self, text='Close',
  104. command=self.ok, takefocus=False)
  105. self.viewframe.pack(side='top', expand=True, fill='both')
  106. self.is_modal = modal
  107. if self.is_modal:
  108. self.transient(parent)
  109. self.grab_set()
  110. if not _utest:
  111. self.wait_window()
  112. def ok(self, event=None):
  113. """Dismiss text viewer dialog."""
  114. if self.is_modal:
  115. self.grab_release()
  116. self.destroy()
  117. def view_text(parent, title, contents, modal=True, wrap='word', _utest=False):
  118. """Create text viewer for given text.
  119. parent - parent of this dialog
  120. title - string which is the title of popup dialog
  121. contents - text to display in this dialog
  122. wrap - type of text wrapping to use ('word', 'char' or 'none')
  123. modal - controls if users can interact with other windows while this
  124. dialog is displayed
  125. _utest - bool; controls wait_window on unittest
  126. """
  127. return ViewWindow(parent, title, contents, modal, wrap=wrap, _utest=_utest)
  128. def view_file(parent, title, filename, encoding, modal=True, wrap='word',
  129. _utest=False):
  130. """Create text viewer for text in filename.
  131. Return error message if file cannot be read. Otherwise calls view_text
  132. with contents of the file.
  133. """
  134. try:
  135. with open(filename, 'r', encoding=encoding) as file:
  136. contents = file.read()
  137. except OSError:
  138. showerror(title='File Load Error',
  139. message=f'Unable to load file {filename!r} .',
  140. parent=parent)
  141. except UnicodeDecodeError as err:
  142. showerror(title='Unicode Decode Error',
  143. message=str(err),
  144. parent=parent)
  145. else:
  146. return view_text(parent, title, contents, modal, wrap=wrap,
  147. _utest=_utest)
  148. return None
  149. if __name__ == '__main__':
  150. from unittest import main
  151. main('idlelib.idle_test.test_textview', verbosity=2, exit=False)
  152. from idlelib.idle_test.htest import run
  153. run(ViewWindow)