How can I remove empty space at the end of each line inside tkinter Scrolledtext widget ?
INPUT
txt files that do not have empty space at the end of each line.
CODE
def openCommand():
ftypes = [('Text files', '*.txt')] # allow only txt files
filePath = tkFileDialog.askopenfile(parent=root,mode='rb',title=' Select a file', filetypes = ftypes)
if filePath != None:
contents = str(filePath.read()).strip()
contents = contents.rstrip()
contents = contents.lstrip()
textPad.insert('1.0',contents.strip())
OUTPUT
Upon insert the file contents, in textpad:
textPad = ScrolledText(root, width=100, height=30, undo=True)
textPad.pack()
I will see an empty space at the end of each line.
NOTE
I have tried all related to Python string trimming.
problem solved. I've replaced the obj "tkFileDialog.askopenfile" with "tkFileDialog.Open".
To answer your original question: I am 99% sure you are running on Windows and that your text file lines end with \\r\\n
. When you open in binary mode, you are asking Python to not replace \\r\\n
with \\n
. However, you need that replacement. Tk displays control chars other than \\n
as blank spaces. This is the only way I can think of to have blanks magically appear.
From your use of tkFileDialog
, I assume you are using 2.x. I don't remember if 'r' gets you the line ending translation (I think it may) or if you need 'rU'. In any case, tk does the translations when it reads the file.
Your repeated stripping of the entire file is useless and unneeded.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.