I'm using python3 to make a very simple ebook viewer, that will take a document and display it, and allow the user to navigate with page up/down keys. Along with this, I intend to have the audio transcript of that document playing along, with its speed adjusted so that it syncs with the user's reading pace.
What I'm having trouble with is displaying the file - the cursor goes right to the end every time, and to reach the top of the file, I need to scroll up. I looked at print() documentation, and there isn't anything helpful there. Can anyone tell me if there is any construct in python that allows you to display long text on terminal such that the text is displayed from the beginning?
1 Answer
You can do this in a terminal, using a library like pynput to read the key press events. But it's much easier to use a GUI library that already does most of the work for you. And a GUI allows you to choose the font and text colour, gives you automatic word-wrapping, if desired, etc. Here's a short demo using Tkinter's Text widget. This program gets the file name from the command line.
import sys
import tkinter as tk
# Open the main window & start the Tcl interpreter
root = tk.Tk()
# Make a Frame to hold the Text widget and its Scrollbar
frame = tk.Frame(root)
frame.pack()
# Add the Scrollbar first so that it doesn't
# disappear when the window width is small
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Add the Text widget
viewer = tk.Text(root, wrap="word", yscrollcommand=scrollbar.set)
viewer.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
# Connect the Scrollbar to the Text widget
scrollbar.config(command=viewer.yview)
# Get the file name from the command line
fname = sys.argv[1]
# Read the text file and add its contents to the Text widget
with open(fname) as f:
viewer.insert(tk.END, f.read())
root.mainloop()
You can navigate the file using the scroll bar, and if you click in the text you can also use the normal key commands like PageUp, PageDown, the arrow keys, Ctrl-Home & Ctrl-End to navigate.
However, the Text widget is editable. Hopefully, that's not a problem. And of course any changes made in the Text widget won't affect the original file (unless you save the Text data). You can disable editing, as discussed in Is there a way to make the Tkinter text widget read only? but the simple way to do that also disables all the key commands, and the ability to copy text.
print [:50]then on next button event,print[50:100]