【发布时间】:2025-12-26 05:25:15
【问题描述】:
我设置了一个天气应用程序。我创建了两个Threads,第一个Thread1 抓取天气状况,第二个Thread2 设置背景图像,但是当我单击按钮时tkinter 小部件消失,悬停后它会出现。我认为thread 存在一些问题。我能理解吗?
我的代码:
import requests
from tkinter import *
from bs4 import BeautifulSoup
from threading import Thread
from io import BytesIO
from PIL import ImageTk, Image
class gui(Tk):
def __init__(self):
super().__init__()
self.call_weather_True = False
self.icon_link = ''
self.text = ''
self.weather = ''
self.icon_set = ''
self.back_icon = ''
# title of app
self.title('AccWeather')
self.geometry('700x500')
# API
self.api = 'vvfhMQuqmjOgcq1ctGqgmH55bqMPVH3c'
# main canvas with image
self.main = Label(self)
self.main.place(relx=0, rely=0, relwidth=1, relheight=1)
# button and input
self.button_frame = Frame(self.main)
self.button_frame.place(relx=.1, rely=.1, relwidth=.8)
self.city = Entry(self.button_frame, bd=0, font=3, fg='black', width=50)
self.city.pack(side=LEFT)
Button(self.button_frame, text='Get Weather', bg='DodgerBlue', font=5, bd=1, command=self.get_weather_call).pack(side=RIGHT)
self.put_out = Label(self.main, font=20, anchor='nw', bg='white', justify='left', bd=5) # border = bd
self.put_out.place(relx=.1, rely=.4, relwidth=.5, relheight=.5)
def get_weather_call(self):
self.call_weather_True = True
city = self.city.get()
url = 'https://images.unsplash.com/photo-1451154488477-d20dee2a4e46?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=753&q=80'
thread_background_img = Thread(target=self.background_icon, args=(url,))
thread2 = Thread(target=self.get_weather_call, args=[city])
thread2.start()
thread_background_img.start()
def get_weather(self, city):
# autocomplete location
try:
auto_url = f"http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey={self.api}&q=" + city
data = requests.get(auto_url).json()
check = ''
for i in data:
for a in i:
if a=='ServiceUnavailable':
check = True
if check:
self.put_out['text'] = 'Error: '+data['Message']
else:
try:
key = data[0]['Key']
city_name = ', '.join([data[0]['LocalizedName'], data[0]['Country']['LocalizedName']])
api = requests.get(f"http://dataservice.accuweather.com/currentconditions/v1/{key}?apikey={self.api}").json()
self.icon_link = api[0]['Link']
temp = api[0]['Temperature']['Metric']['Value']
self.text = api[0]['WeatherText']
self.weather = f'City: {city_name}\nTemperature (c): {int(temp)}\nCondition: {self.text}'
self.put_out['text'] = self.weather
except Exception as e:
self.put_out['text'] = e
except Exception as e:
print(e)
def background_icon(self, url):
img_data = requests.get(url).content
self.back_icon = ImageTk.PhotoImage(Image.open(BytesIO(img_data)))
self.main['image'] = self.back_icon
if __name__ == '__main__':
start = gui()
start.mainloop()
我花了一天时间想通了,但我发现了。为什么tkinter button,entry 消失了?
【问题讨论】:
-
当我在终端/控制台中运行代码时,我看到了不同的错误,因为它获取了没有域
/textinputassistant/tia.png的图像 url,所以requests.get(img)无法加载此图像。 -
但我在 tkinter 中的中心位置获取此图像。
-
你输入天气位置点击按钮就知道了
-
谷歌似乎在不同的地区/国家给出了不同的结果。
-
我也收到了
Thread错误。
标签: python python-3.x multithreading tkinter tkinter-canvas