get函数添加了一个换行符,如何删除它?

2024-06-26 18:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在python中使用tkinter插件,我正在从文本小部件“.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显示我的工作(这样我就可以找到问题的根源,换句话说,在添加新行的地方),它们没有其他用途。你知道吗


Tags: textconfigappgetplacesurnamewidthbd
1条回答
网友
1楼 · 发布于 2024-06-26 18:05:57

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

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

相关问题 更多 >