【问题标题】:Cannot add text to tkinter canvas correctly无法正确地将文本添加到 tkinter 画布
【发布时间】:2021-03-13 19:34:15
【问题描述】:

我正在尝试使用 python 为学校项目开发一个简单的天气应用程序。我正在尝试使用 tkinter canvas 在 python 上完成这一切,但事实证明这非常困难。我将附上我的代码和我的窗口的样子。本质上,我正在尝试单击其中一个按钮并将结果填充在我创建的白框顶部,但现在它如何在画布下弹出并且不知道如何修复。

from tkinter import *
import tkinter as tk
import requests
import json
from tkinter import messagebox

root = Tk()
root.title('Weather App')
canvas = Canvas(root, width =600, height=600)



canvas.create_rectangle(10,150,590,225, outline="black", fill="white", width='4')

def AirQuality ():
    api_request = requests.get("https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=33174&distance=25&API_KEY=04208BA7-7F60-4FB3-B24B-E03FAE01E2A5")
    api = json.loads(api_request.content)
    city = api[0]['ReportingArea']
    quality = api[0]['AQI']
    category = api[0]['Category']['Name']
    myLabel = Label(root, text = city + " Air Quality " + str(quality) + " " + category, font=("Times new Roman", 20))
    myLabel.pack()
    


b = Button(canvas,text="Air Quality", command=AirQuality, height=1, width=20, compound=LEFT)
b.place(x = 50, y = 250)
   
  

canvas.pack()
root.mainloop()

enter image description here

【问题讨论】:

  • 是给出错误信息还是什么都不做?
  • 请将其缩减为minimal reproducible example。我认为我们不需要几十个椭圆、四个函数和四个按钮来重现这个问题。专注于提供足够的代码来重现问题,仅此而已。
  • 会做的,很抱歉第一次使用该网站,对python还不是很熟悉。

标签: python tkinter canvas tkinter-canvas tkinter-entry


【解决方案1】:

您可以在画布上创建另一个文本对象,而不是标签,并使用天气数据对其进行更新:

# set up output text
result = canvas.create_text(10, 170,font = ("Times New Roman" , 20), anchor='w')

def AirQuality ():
    api_request = requests.get("https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=33174&distance=25&API_KEY=04208BA7-7F60-4FB3-B24B-E03FAE01E2A5")
    api = json.loads(api_request.content)
    city = api[0]['ReportingArea']
    quality = api[0]['AQI']
    category = api[0]['Category']['Name']
    canvas.itemconfig(result, text = city + " Air Quality " + str(quality) + " " + category)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多