如何解决如何更新 pysimplegui 布局中的天气信息,并在每次在窗口中按“刷新”时显示?
我正在尝试将“刷新”按钮连接到我的列/布局,以便每次按下按钮时都能生成更新的天气结果。我也很难通过更新这些结果来创建函数,因为我的代码似乎总是“无法访问”函数中的内容。这是我的代码:
from bs4 import BeautifulSoup as Soup
from urllib.request import urlopen as uReq
import PySimpleGUI as sg
import requests
import os
import time
my_url = 'https://forecast.weather.gov/MapClick.PHP?lat=41.279&lon=-72.8717'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_Soup = Soup(page_html,'html.parser')
days = page_Soup.findAll("li",{"class": "forecast-tombstone"})
sg.theme('DarkBlue1')
day_titles = [day.img['title'].split(':')[0] for day in days]
day_imgs = [day.img['src'] for day in days]
os.chdir(r'C:\Users\Konrad\PycharmProjects\pythonProject\weather')
weather_images = []
for day in day_imgs:
image = 'https://forecast.weather.gov/{}'.format(day) file_name = str(image.split('.gov/'[1].replace('/','').replace('?','').replace('&','').replace('=',''))
weather_images.append(file_name)
r = requests.get(image)
with open(file_name,'wb') as f:
f.write(r.content)
day_shorts = [str(day.find('p',{'class': 'short-desc'}))
.replace('<p class="short-desc">','')
.replace('<br/>',' ')
.rstrip('</p>') for day in days]
day_temps = [str(day.find('p',{'class': 'temp temp-high'}) or
day.find('p',{'class': 'temp temp-low'}))
.replace('<p class="temp temp-low">','')
.replace('<p class="temp temp-high">','')
.replace('<span style="color: #000000; font-weight:normal;">','')
.replace('</span>','')
.rstrip('</p>') for day in days]
columns = [
[sg.Text(day_title,size=(10,0),pad=(7,justification='c') for day_title in day_titles],[sg.Image(r'C:\Users\Konrad\PycharmProjects\pythonProject\weather\{}'.format(file_name),key='day_image-') for file_name in weather_images],[sg.Text(day_short,justification='c') for day_short in day_shorts],[sg.Text(day_temp,justification='c') for day_temp in day_temps]
]
columns += [[sg.Button('Refresh',key='-REFRESH-',bind_return_key=True),sg.Button('Exit',key='Exit-')]]
window = sg.Window('Weather',columns,alpha_channel=.8,no_titlebar=True,grab_anywhere=True,finalize=True,location=(3000,450))
while True:
event,values = window.read()
if event is None or event == '-Exit-':
break
if event == '-REFRESH-':
event,values = window.read()
window.close()
解决方法
对于简单的,在这里为你演示代码。
只需使用元素的方法 update
的选项来更新元素的内容。用于打开/关闭自动更新的额外按钮。
from random import choice
import PySimpleGUI as sg
# Get Emoji image and string
def get_data():
name = choice(names)
index = names.index(name)
return name,sg.EMOJI_BASE64_LIST[index]
dictionary = {value:key for key,value in sg.__dict__.items()
if key.startswith("EMOJI_BASE64") and type(value) != list}
names = [dictionary[key] for key in sg.EMOJI_BASE64_LIST]
size = (max(map(len,names)),1)
# GUI start
sg.theme('DarkBlue1')
name,data = get_data()
layout = [
[sg.Text(name,size=size,justification='center',key='TEXT')],[sg.Image(data=data,key='IMAGE')],[sg.Button('Refresh'),sg.Button('Auto ON/OFF',key='Auto')],]
window = sg.Window('Title',layout,size=(300,150),finalize=True)
text,image,refresh = window['TEXT'],window['IMAGE'],window['Refresh']
# Set elements extend on x direction
text.expand(expand_x=True)
image.expand(expand_x=True)
refresh.expand(expand_x=True)
timeout = None
while True:
event,values = window.read(timeout=timeout)
if event is None or event == '-Exit-':
break
elif event in ('Refresh','__TIMEOUT__'):
# Updata element
name,data = get_data()
text.update(value=name)
image.update(data=data)
elif event == 'Auto':
# Set timeout to 0.5s for timeout event,or None for no timeout
timeout = 500 if timeout is None else None
window.close()
如果从网站获取数据需要很长时间,多线程是首选,并在线程完成时使用 window.write_event_value(...)
将键值元组添加到线程用于与窗口。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。