1

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.

4
  • You did nothing wrong, it seems that Text widget output its content with a trailing newline. You could use data.strip() that return a copy of the string without leading and trailing whitespaces. Commented Mar 22, 2013 at 9:16
  • If you only need a one line field, you might have a look at the Entry widget. Commented Mar 22, 2013 at 9:23
  • thanks a lot Fabien! it works perfectly..you should have used the answer feature so that i can accept your answer.. anyway.. thanks again! Commented Mar 22, 2013 at 9:25
  • it's gonna be more than one line.. and that's the reason why i use text widget. But ya.. thanks for reminding me. Commented Mar 22, 2013 at 9:26

1 Answer 1

3

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]
''
Sign up to request clarification or add additional context in comments.

3 Comments

The normal way to not get the automatic \n is to do text.get(1.0, END+"-1c") (or the slightly less complex "end-1c")
@BryanOakley I've used this since it is a common Python idiom and can be used with any string, while "end-1c" looks a Tkinter-specific solution.
how about using .rstrip()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.