Home > Back-end >  How to add indentation inside tkinter text box?
How to add indentation inside tkinter text box?

Time:11-16

-EDIT I used the word indentation incorrectly in this question. I meant to to refer to the starting of new lines.


I'm creating a python weather app with the tkinter UI library, It works but using the output in terminal Its clean and has good indents. But now I need to put this info into the apps text box's. I do this using this code.

City.set(CITY)

#add the citys name to a list of all citys 
History.tag_configure("right", justify='right')
History.insert("1.0", f"{CITY:-^30}")
History.tag_add("right", "1.0", "end")

#adds info to main textbox
InfoBox.tag_configure("right", justify='right')
InfoBox.delete('1.0', END)
InfoBox.insert("1.0", (f"{CITY:-^30}"))
InfoBox.insert("1.0", (f"Temperature: {temperature}"))
InfoBox.insert("1.0", (f"Humidity: {humidity}"))
InfoBox.insert("1.0", (f"Pressure: {pressure}"))
InfoBox.insert("1.0", (f"Weather Report: {report[0]['description']}"))
InfoBox.tag_add("right", "1.0", "end")

#add city info to our info box with all previous citys info
CityUpdate.tag_configure("right", justify='right')
CityUpdate.insert("1.0", (f"{CITY:-^30}"))
CityUpdate.insert("1.0", (f"Temperature: {temperature}"))
CityUpdate.insert("1.0", (f"Humidity: {humidity}"))
CityUpdate.insert("1.0", (f"Pressure: {pressure}"))
CityUpdate.insert("1.0", (f"Weather Report: {report[0]['description']}"))
CityUpdate.tag_add("right", "1.0", "end")

The issue comes up here when the code shows something like this in the text boxes. output in app Its the correct information but the indentation is gone. My question is how can I get that indentation back so it looks as good as it was in the terminal?

CodePudding user response:

I don't see a problem with the indentation. What I see is that you're failing to add a newline when inserting a line of text. You also keep inserting at the start instead of appending at the end which is unusual; I don't know whether or not that is intentional.

To add a newline, your insert statement should look something like this:

InfoBox.insert("1.0", (f"{CITY:-^30}\n"))

As to the question in the title, the text widget supports tabs via the tabs configuration option. By default tab stops are every 8 average-sized characters but you have complete control over the placement of tabstops, as well as how text is aligned to those tab stops (eg: left, center, right, or numeric).

  • Related