2017-11-11 1 views
0

제목에서 tkinter gui의 레이블에있는 값을 업데이트하려고합니다. 값은 pyown을 사용하는 OpenWeatherMap API에서 가져온 것이며 가입 수준에서는 분당 60 회의 통화 만 할 수 있습니다. 많은 전화를 할 예정이므로, 1 분 또는 5 분마다 내 gui를 업데이트하고 싶습니다. 지난 며칠 동안 비슷한 질문을 읽은 후 업데이트를 지연시키기 위해 수면 기능이 필요하다는 것을 알아 냈습니다. 어떤 사람들은 내가 잠시 반복하고 싶은 것을 넣었다고 제안했다. 무한 루프가 반복되지만, 창을 닫을 때 gui 만 업데이트되고 업데이트 사이의 시간을 제어 할 수 없었다. 다른 사람들은 .after 함수를 사용하도록 제안했지만, 이렇게하면 프로그램이 컴파일되지만 gui는 절대로 팝업되지 않습니다. 나는이 솔루션 중 하나가 내 코드에서 어떻게 작동 하는지를 보여줄 사람을 찾고 있는데, 내 코드를 더 잘 활용할 수있는 세 번째 솔루션이 있다면, 어떻게 보이는지 보도록하겠습니다. 뒤죽박죽이다.pyown 및 tkinter를 사용하여 GUI에서 텍스트 변수를 업데이트하는 방법

import tkinter as tk 
import pyowm 
from datetime import datetime, timedelta 

class WeatherInfo(tk.Tk): 

    def __init__(self): 

     tk.Tk.__init__(self) 
     self.wm_title('Forecast') 
     self.currentTime = tk.StringVar(self, value='') 
     self.d2temp_7 = tk.StringVar(self,value='') 

     self.owm = pyowm.OWM('*INSERT YOUR OWM KEY HERE*') 

     self.headLabel = tk.Label(self, text='5-Day Forecast of Cayce, US.') 
     self.headLabel.pack() 
     self.footLabel = tk.Label(self, textvariable=self.currentTime) 
     self.footLabel.pack(side=tk.BOTTOM) 

     self.day2Frame = tk.LabelFrame(self, text='D2') 
     self.day2Frame.pack(fill='both', expand='yes', side=tk.LEFT) 
     tk.Label(self.day2Frame, text="Temperature:").pack() 
     tk.Label(self.day2Frame, textvariable=self.d2temp_7).pack() 

     self.search() 

    def search(self): 
     fc = self.owm.three_hours_forecast_at_id(4573888) 
     try: 
      self.currentTime.set(datetime.today()) 
      self.d2temp_7.set("7am: " + str(fc.get_weather_at((datetime.today().replace(hour=13, minute=00) + timedelta(days=1)) 
           .strftime ('%Y-%m-%d %H:%M:%S+00')).get_temperature('fahrenheit')['temp'])) 
     except: 
      self.temp.set('Pick a city to display weather.') 

    def _quit(self): 
     self.quit() 
     self.destroy() 

if __name__== "__main__": 
    app = WeatherInfo() 
    app.mainloop() 

내가 시도 무엇에 더 :

while True: 
    def __init__ 
    def search 

그러나이 대답은 지적으로, other answer, 나는 내 동안의 root.mainloop 앞에 진정한 변경 사항을 볼 수 없습니다

()

이 질문은 root.after (밀리 초, 결과)를 사용하여 내 답변에 가깝지만이 답변을 구현할 때 내 GUI에는 표시되지 않았습니다. infinitely update

답장을 보내 주신 분께 고맙습니다.

편집 : 권장 사항에 따라 코드를 더 짧게 만들었습니다.

+0

이 너무 많은 코드입니다. [mcve] –

+0

브라이언에게 추천 해 주셔서 감사합니다. 코드 예제를 상당히 짧게 만들었습니다. 좋은 방법 연결. – Purin

+0

'.after' 구현이 정확히 어떻게 작동하지 않습니까? 또한 [this] (https://stackoverflow.com/a/11505034/7032856)을 확인하십시오. – Nae

답변

1

this을 바탕으로 다음과 같은 기능, forecast_update을 가질 수 있습니다

import tkinter as tk 

#these two needed only for API update simulation 
import random 
import string 

root = tk.Tk() 

forecast = tk.Label(text="Forecast will be updated in 60 seconds...") 
forecast.pack() 

# returns a string with 7 random characters, each time it is called, in order to simulate API 
def update_request_from_api(): 
    return ''.join(random.choice(string.ascii_lowercase) for x in range(7)) 


# Your function to update the label 
def forecast_update(): 
    forecast.configure(text=update_request_from_api()) 
    forecast.after(60000, forecast_update) # 60000 ms = 1 minute 


# calling the update function once 
forecast_update() 
root.mainloop() 
+0

감사합니다. 전화가 잘못 주문되었습니다. – Purin

+0

Return 함수는 한 가지만 반환합니다. 내 질문에 언급했듯이, 나는 한 번에 (~ 40 주위에) 많은 전화를 할 것입니다. 이것이 내가 각자 새로운 데프를 만들 필요가 있다는 것을 의미합니까? 확실히 더 좋은 방법이 있습니다 ... – Purin

+1

함수에서 여러 값을 반환 할 수 있습니다. [this] (https://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python)을 확인하십시오. – Nae

관련 문제