textview.py 6.6 KB

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