我正在制作一个简单的天气应用程序,以实践tkinter.在这个过程中,我遇到了一个重大问题,我得到的图像可以使用请求获取,并在一个新的tkinter窗口中显示它是一个很大的问题.该程序仍然不完整,但它工作正常,除了图像无法显示.
在disp_weather()中,你可以看到我创建了一个新窗口来显示详细信息,fw.get_icon()获取PNG图像的URL,例如“//cdn.weatherapi.com/weather/64x64/day/176.png“,错误出现了
raceback (most recent call last):
File "C:\Users\Abhishek\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Users\Abhishek\Desktop\OIBSIP\proj3_weather\Init.py", line 23, in disp_weather
imag.pack()
^^^^^^^^^
字符串
该方案:
import fetch_weather as fw
from tkinter import *
import os
from PIL import Image, ImageTk
import requests
from io import BytesIO
def disp_weather():
location=e1.get()
unit=v.get()
url=fw.get_icon()
url="https:"+url
new_window = Toplevel(root)
new_window.geometry("300x200")
new_window.title("New Window")
response = requests.get(url)
img_data = BytesIO(response.content)
img = Image.open(img_data)
wImg = ImageTk.PhotoImage(img)
imag = Label(new_window, image=wImg) #Here is where the problem starts
imag.photo = wImg
imag.pack()
script_dir = os.path.dirname(os.path.abspath(__file__))
icon_path = os.path.join(script_dir, "weather.ico")
icon_path=icon_path.replace("\\", "/")
root = Tk()
root.title("Weather")
root.iconbitmap(default=icon_path)
root.geometry("400x300")
Label(root, text='Enter the Location:').grid(row=0, column=0, pady=4, sticky=W)
e1 = Entry(root)
e1.grid(row=0, column=1, pady=5, sticky=W)
v = IntVar()
Label(root,text='Choose a unit:').grid(row=1,column=0,pady=5,sticky=W)
Radiobutton(root, text='Celsius', variable=v, value=1).grid(row=1, column=1, pady=4, sticky=W)
Radiobutton(root, text='Fahrenheit', variable=v, value=2).grid(row=1, column=2, pady=4, sticky=W)
fetch_button = Button(root, text="Find", command=disp_weather)
fetch_button.grid(row=3, column=0, pady=10, columnspan=3)
mainloop()
型
1条答案
按热度按时间hfyxw5xn1#
我建议调试你的程序(例如,从服务器返回的
response
实际上是什么?)。将URL替换为"https://cdn.weatherapi.com/weather/64x64/day/176.png"
,我得到了正确的结果:字符串
下载并正确显示图像:
的数据