python .get函数添加换行符,如何删除它?

时间:2015-10-19 09:08:54

标签: python csv tkinter

我在python中使用tkinter add,我是“.get”来自文本小部件的输入文本,

当我这样做时,它决定添加换行符。

我不想要这个换行符,因为它与我的CSV保存文件混淆,意味着我无法从python中正确读取我的CSV文件。

我如何摆脱“\ n”?

我试过“.rstrip”和“.splitlines”都不行。

This is what is displayed by the code...

如何摆脱换行符“\ n”?

纯粹代码:

TextIDNumber = Text(App, height = "1", width = "25", bd = "4")
TextIDNumber.place(x = 550, y = 250)
TextIDNumber.config(font =("bold", 20))
TextSurname = Text(App, height = "1", width = "25", bd = "4")
TextSurname.place(x = 550, y = 350)
TextSurname.config(font =("bold", 20))



def CheckInputUI():
    IDNumber = TextIDNumber.get("1.0", END)
    Surname = TextSurname.get("1.0", END)
    print (Surname, IDNumber)
    print ("")
    print (Surname + IDNumber)

重现问题的最短代码,我们可以在自己的机器上运行:

from tkinter import *


App = Tk()

#This maximises the window
w = App.winfo_screenwidth()
h = App.winfo_screenheight()

App.geometry("%dx%d+0+0" % ((w-10), (h-30)))

TextIDNumber = Text(App, height = "1", width = "25", bd = "4")
TextIDNumber.place(x = 550, y = 250)
TextIDNumber.config(font =("bold", 20))
TextSurname = Text(App, height = "1", width = "25", bd = "4")
TextSurname.place(x = 550, y = 350)
TextSurname.config(font =("bold", 20))

def PrintInfo():
    IDNumber = TextIDNumber.get("1.0", END)
    Surname = TextSurname.get("1.0", END)
    print (Surname, IDNumber)
    print ("")
    print (Surname + IDNumber)

DoneButton = Button(App, text = " Done ", font = ("bold", 18), command = PrintInfo).place(x = 400,y = 800)

我使用打印件只显示我的工作到shell(所以我可以找到问题的根源,换句话说,添加新行的地方),它们没有其他用途。

1 个答案:

答案 0 :(得分:0)

文本小部件保证最后总会有换行符,即使实际数据中没有换行符也是如此。要从小部件中获取除此特殊换行符之外的所有数据,请在获取数据时使用"end-1c"(结束减去一个字符):

IDNumber = TextIDNumber.get("1.0", "end-1c")
Surname = TextSurname.get("1.0", "end-1c")

如果有可能将空行添加到数据中,您可以使用strip删除所有尾随空格:

IDNumber = TextIDNumber.get("1.0", END).rstrip()
Surname = TextSurname.get("1.0", END).rstrip()