Chris Aung
Chris Aung

Reputation: 9532

python text widget get method

I have a text widget in my python Tkinter script and i am trying to get the value that the user enter. My intention is to write the data from the text widget together with other values from the script(ie. x,y,z) to the txt file(faultlog.txt) as a single line with semi-column separated. This is what i tried.

...
text=Text(width=30,height=1)
text.place(x=15,y=75)
data=text.get(1.0,END)

lines=[]
lines.append('{};{};{};{} \n'.format(data,x,y,z))
faultlog=open("faultlog","a")
faultlog.writelines(lines)
faultlog.close()
...

Instead of giving me a single line output in the text file, python is writing this to the txt file (assuming the data that user enter is "abcdefgh")

abcdefgh
;x;y;z

just to make things clear, this is what i want

abcdefgh;x;y;z

What did i do wrong? I hope the question is clear enough, i am a beginner so please make the answer simple.

Upvotes: 1

Views: 5463

Answers (1)

A. Rodas
A. Rodas

Reputation: 20689

When you get all text of the widget, there is also included a "\n" at the end. You can remove this last character like this:

data=text.get(1.0,END)[:-1]

Note that this always works independently of the length of the text length:

>>> "\n"[:-1]
''
>>> ""[:-1]
''

Upvotes: 3

Related Questions