如何在 tkinter 文本框中添加缩进?

How to add indentation inside tkinter text box?

-编辑我在这个问题中错误地使用了缩进这个词。我的意思是指新行的开始。


我正在使用 tkinter UI 库创建一个 python 天气应用程序,它可以工作,但使用 Open weather map API。用户将输入城市名称 (CITY var) 并使用预定义的 link 程序插入城市名称 (CITY var) 并使用 [=25= 从开放天气地图站点请求城市的天气数据].整个请求数据的过程都是由这个函数处理的

 def getData(CITY):
    BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
    API_KEY = "MY-API-KEY"

    #our url to send to
    URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY

    # HTTP request
    response = requests.get(URL)

    # checking the status code of the request
    if response.status_code == 200:
        # getting data in the json format
        data = response.json()
        # getting the main dict block
        main = data['main']
        # getting temperature
        temperature = main['temp']
        # getting the humidity
        humidity = main['humidity']
        # getting the pressure
        pressure = main['pressure']
        # weather report
        report = data['weather']
        # print info
        print(f"{CITY:-^30}")
        print(f"Temperature: {temperature}")
        print(f"Humidity: {humidity}")
        print(f"Pressure: {pressure}")
        print(f"Weather Report: {report[0]['description']}")



    else:
        # showing the error message
        print("Error in the HTTP request")

当 运行 城市名称为纽约时,终端输出如下内容。 它干净且有良好的凹痕。但现在我需要将此信息放入应用程序文本框。我使用此代码执行此操作。

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

当代码在文本框中显示类似内容时,就会出现此问题。 它是正确的信息,但缩进不见了。我的问题是如何恢复缩进,使其看起来和终端中一样好?

我没有发现缩进有问题。我看到的是您在插入一行文本时未能添加换行符。您还继续在开头插入而不是在末尾附加,这是不寻常的;不知道是不是故意的

要添加换行符,您的插入语句应如下所示:

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

关于标题中的问题,文本小部件通过 tabs 配置选项支持选项卡。默认情况下,制表位每 8 average-sized 个字符,但您可以完全控制制表位的位置,以及文本如何与这些制表位对齐(例如:左、中、右或数字)。