简体   繁体   English

如何在python中的tkinter中编辑背景图像?

[英]How to edit a background image in tkinter in python?

I try to edit the background image of the tkinter code but i cannot even if i rename a different picture with "landscape.png" regardless of the different picture being larger or smaller. 我尝试编辑tkinter代码的背景图片,但是即使我将不同的图片重命名为“ landscape.png”,我也无法做到,无论其他图片变大还是变小。 I do not know what i can do to improve this problem, Its like this code only works with one type of picture and i dont know why. 我不知道我能做些什么来改善这个问题,就像这样的代码仅适用于一种类型的图片,我不知道为什么。 I am trying to deal with this issue for 3 days now and this is my last help resort 我现在正尝试处理此问题3天,这是我的最后帮助手段

I have tried the above 我已经尝试了上面

import tkinter as tk
import requests

HEIGHT = 500
WIDTH = 600

def test_function(entry):
    print("This is the entry:", entry)

# api.openweathermap.org/data/2.5/forecast?q={city name},{country code}
# a4aa5e3d83ffefaba8c00284de6ef7c3

def format_response(weather):
    try:
        name = weather['name']
        desc = weather['weather'][0]['description']
        temp = weather['main']['temp']

        final_str = 'City: %s \nConditions: %s \nTemperature (°F): %s' % (name, desc, temp)
    except:
        final_str = 'There was a problem retrieving that information'

    return final_str

def get_weather(city):
    weather_key = 'a4aa5e3d83ffefaba8c00284de6ef7c3'
    url = 'https://api.openweathermap.org/data/2.5/weather'
    params = {'APPID': weather_key, 'q': city, 'units': 'imperial'}
    response = requests.get(url, params=params)
    weather = response.json()

    label['text'] = format_response(weather)



root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

background_image = tk.PhotoImage(file='landscape.png')
background_label = tk.Label(root, image=background_image)
background_label.place(relwidth=1, relheight=1)

frame = tk.Frame(root, bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')

entry = tk.Entry(frame, font=40)
entry.place(relwidth=0.65, relheight=1)

button = tk.Button(frame, text="Get Weather", font=40, command=lambda: get_weather(entry.get()))
button.place(relx=0.7, relheight=1, relwidth=0.3)

lower_frame = tk.Frame(root, bg='#80c1ff', bd=10)
lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')

label = tk.Label(lower_frame)
label.place(relwidth=1, relheight=1)

root.mainloop()

I expected another image to show but instead i get this error: 我希望显示另一张图像,但出现此错误:

Traceback (most recent call last):


    File "/Users/michal/Desktop/GUI-master/WeatherApp.py", line 41, in <module>
        background_image = tk.PhotoImage(file='landscape.png')
      File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3545, in __init__
        Image.__init__(self, 'photo', name, cnf, master, **kw)
      File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3501, in __init__
        self.tk.call(('image', 'create', imgtype, name,) + options)
    _tkinter.TclError: couldn't recognize data in image file "landscape.png"
    >>>

The PhotoImage class can read GIF and PGM/PPM images from files: PhotoImage类可以从文件读取GIFPGM/PPM图像:

photo = PhotoImage(file="image.gif")

photo = PhotoImage(file="image.pgm")

If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects: 如果您需要使用其他文件格式,则Python Imaging Library (PIL)包含一些类,这些类使您可以加载30多种格式的图像,并将其转换为Tkinter兼容的图像对象:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)

You can use a PhotoImage instance everywhere Tkinter accepts an image object. 您可以在Tkinter接受图像对象的任何地方使用PhotoImage实例。

An example: 一个例子:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

in your code: 在您的代码中:

from PIL import Image, ImageTk

background_image = Image.open(image_path)
background_photo = ImageTk.PhotoImage(background_image)

background_label = tk.Label(root, image = background_photo)
background_label.image = background_photo
background_label.place(relwidth=1, relheight=1)

NOTE: if you doesn't have installed PIL, just install it from cmd : 注意:如果您尚未安装PIL,只需从cmd安装它:

pip install Pillow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM