【发布时间】:2021-11-15 19:01:30
【问题描述】:
-EDIT 我在这个问题中错误地使用了缩进这个词。我的意思是指新行的开始。
我正在使用 tkinter UI 库创建一个 python 天气应用程序,它可以工作,但使用 Open weather map API。用户将输入城市名称(CITY var)并使用预定义的链接主体,程序插入城市名称(CITY var)并使用该链接从开放的天气地图站点请求城市的天气数据。请求数据的整个过程都由这个函数处理
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")
当使用城市名称 new York 运行时,终端会输出类似这样的内容。 它干净而且有很好的缩进。但现在我需要将此信息放入应用程序文本框中。我使用此代码执行此操作。
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")
当代码在文本框中显示类似这样的内容时,问题就出现了。 它的信息正确,但缩进消失了。我的问题是我怎样才能恢复那个缩进,使它看起来和终端一样好?
【问题讨论】:
-
这看起来不像是缩进的问题,而是换行的问题。请务必在您插入的每一行的末尾添加
\n。例如,InfoBox.insert("1.0", (f"Temperature: {temperature}\n"))。
标签: python user-interface tkinter indentation