簡體   English   中英

如何在python tkinter ScrolledText小部件內的每一行的末尾刪除空白?

[英]How can I remove empty space at the end of each line inside python tkinter ScrolledText widget?

如何在tkinter Scrolledtext小部件內的每一行末尾刪除空白?

輸入

每行末尾沒有空格的txt文件。

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())

輸出值

插入文件內容后,在文本鍵盤中:

textPad = ScrolledText(root, width=100, height=30, undo=True)
textPad.pack()

我將在每行末尾看到一個空白區域。

注意

我已經嘗試了所有與Python字符串修剪相關的內容。

問題解決了。 我已經將obj“ tkFileDialog.askopenfile”替換為“ tkFileDialog.Open”。

要回答您的原始問題:我99%確信您正在Windows上運行,並且您的文本文件行以\\r\\n結尾。 當您以二進制模式打開時,您正在要求Python 不要\\r\\n代替\\r\\n \\n 但是,您需要更換。 Tk將\\n以外的控制字符顯示為空格。 這是我能想到的神奇地出現空白的唯一方法。

根據您對tkFileDialog的使用,我假設您正在使用2.x。 我不記得“ r”是不是行尾翻譯(我想可能是)還是您需要“ rU”。 無論如何,tk在讀取文件時都會進行翻譯。

重復刪除整個文件是無用且不必要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM