【问题标题】:How can I remove empty space at the end of each line inside python tkinter ScrolledText widget?如何删除 python tkinter ScrolledText 小部件内每行末尾的空白空间?
【发布时间】:2015-11-09 08:05:16
【问题描述】:

如何删除 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 字符串修剪相关的东西。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    问题解决了。 我已经用“tkFileDialog.Open”替换了 obj“tkFileDialog.askopenfile”。

    【讨论】:

      【解决方案2】:

      回答您最初的问题:我 99% 确定您在 Windows 上运行,并且您的文本文件行以 \r\n 结尾。当您以二进制模式打开时,您要求 Python 不要\r\n 替换为 \n。但是,您需要那个替换。 Tk 将除\n 之外的控制字符显示为空格。这是我能想到的让空白神奇地出现的唯一方法。

      根据您对tkFileDialog 的使用,我假设您使用的是 2.x。我不记得“r”是否为您提供行尾翻译(我认为可能)或者您是否需要“rU”。在任何情况下,tk 都会在 it 读取文件时进行翻译。

      您对整个文件的重复剥离是无用且不需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2020-01-19
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 2021-12-07
        • 2017-08-09
        相关资源
        最近更新 更多