как обновить ярлыки в tkinter используя api? - PullRequest
0 голосов
/ 09 апреля 2020

Я пытаюсь обновить ярлыки при поиске книги, но они не обновляются. Я уже пробовал несколько разных способов, но ни один не работал

код:

# find books
def find_books():
    global book
    book = search_book.get()


# UI
text_describe = Label(root, text="Find a book", font=("Helvtica", 30), bg="#dbdbdb")
text_describe.pack(pady=10)

# search box
search_book = Entry(root, width=20, font=("Helvtica", 20), fg="#101010")
search_book.pack(pady=10)

# get books
response = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + book)
data = response.json()

# find books
find = Button(root, text="search", width=20, command=find_books)
find.pack(pady=10)


try:
    for item in data['items']:
        title = item['volumeInfo']['title']
        link = item['volumeInfo']['infoLink']
        thumb = item['volumeInfo']['imageLinks']['thumbnail']
        break

    # Book cover
    book_cover = urllib.request.urlopen(thumb)
    cover_image = PIL.Image.open(book_cover)
    image = PIL.ImageTk.PhotoImage(cover_image)
    cover_label = Label(root, image=image)
    cover_label.image = image  # better to keep a reference of the image
    cover_label.pack(pady=15)

    # Book Title
    title_label = Label(root, text="" + title, bg="#dbdbdb")
    title_label.pack(pady=10)

except KeyError:
    print('key error')

root.mainloop()

Я уже некоторое время пытаюсь сделать это, и я не могу заставить его работать должным образом, если вы можете Помоги мне. заранее спасибо:)

1 Ответ

1 голос
/ 09 апреля 2020

Вы должны поместить код получения данных из inte rnet в функцию find_books():

import tkinter as tk
import requests
from requests.exceptions import RequestException
from urllib.request import urlopen
from PIL import Image, ImageTk
#from io import BytesIO  # for using requests to fetch image

# find books
def find_books():
    book = search_book.get().strip()
    if book:
        try:
            # get books
            response = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + book)
            data = response.json()
            if data['totalItems'] > 0:
                for item in data['items']:
                    title = item['volumeInfo']['title']
                    link = item['volumeInfo']['infoLink']
                    thumb = item['volumeInfo']['imageLinks']['thumbnail']

                    # Book cover using urllib
                    book_cover = urlopen(thumb)
                    cover_image = Image.open(book_cover)
                    # or use requests
                    #response = requests.get(thumb)
                    #cover_image = Image.open(BytesIO(response.content))
                    image = ImageTk.PhotoImage(cover_image)
                    cover_label = tk.Label(root, image=image)
                    cover_label.image = image  # better to keep a reference of the image
                    cover_label.pack(pady=15)

                    # Book Title
                    title_label = tk.Label(root, text="" + title, bg="#dbdbdb")
                    title_label.pack(pady=10)

                    # only process one book as your original code
                    break
            else:
                tk.Label(root, text='No book found', fg='red').pack(pady=10)
        except KeyError:
            print('key error')
        except RequestException as e:
            print(e)

root = tk.Tk()

# UI
text_describe = tk.Label(root, text="Find a book", font=("Helvtica", 30), bg="#dbdbdb")
text_describe.pack(pady=10)

# search box
search_book = tk.Entry(root, width=20, font=("Helvtica", 20), fg="#101010")
search_book.pack(pady=10)

# find books
find = tk.Button(root, text="search", width=20, command=find_books)
find.pack(pady=10)

root.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...