-1

I'm new with Python, and am still experimenting a bit at the moment. I have a weather station at home that is linked to a JSON Web API. Via Python I would like to read the temperature on a screen.

The problem that i'm having is that the temperature is not updating itselfs. When the Python progrm starts its getting the correct temperature. But if the temperature changes, the python script. doesn't change.

import urllib.request
import json
from tkinter import *
import tkinter as tk


while True:
    key = "1234"
    method = "getTemp"
    data = json.load(urllib.request.urlopen('http://IP.COM/api/api.php?key=' + key + "&request=" + method))
    temp = (data[u'temp'])

    root = Tk()
    root.title("Temperature board")
    root.configure(background='#545454')

    cv = tk.Canvas(width=1000, height=1000, background='#545454')
    timeLabel = cv.create_text(200, 360, fill="white", text=temp, font=('Arial', 100))
    cv.pack()
    root.mainloop()

I tried to create a loop to solve the problem, but it didn't seem to work.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

1

root.mainloop() blocks, which means that when it is run, your program stops there. Because of this, your loop actually makes no difference. You could use on of the solutions described here to run a function to update the temperature.

Taking a solution from the top answer there, you could do the following:

# setup

def update():
  # update temperature
  root.after(millis between updates, update)

root.after(millis between updates, update)

root.mainloop()
internet_user
  • 3,149
  • 1
  • 20
  • 29
  • I would recommend against calling the method `update` since tkinter widgets all already have a method named `update`. Having a function of the same name that does something different might be confusing and lead to errors down the road. – Bryan Oakley Dec 02 '17 at 02:24