Search code examples
pythontkintercanvastkinter-canvastkinter-entry

Cannot add text to tkinter canvas correctly


I am trying to develop a simple weather app using python for a school project. I am trying to make it all on python using tkinter canvas but it is proving to be extremely difficult. I will attach my code and what my window looks like. Essentially I am trying to click one of the buttons and have the result populate on top of the white box I created but how it is now it pops up under the canvas and not sure how to fix.

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


Solution

  • Instead of a label, you could make another text object on the canvas and update that with the weather data:

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