如何更新 pysimplegui 布局中的天气信息,并在每次在窗口中按“刷新”时显示?

如何解决如何更新 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 的选项来更新元素的内容。用于打开/关闭自动更新的额外按钮。

enter image description here

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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?