Можно ли получить результат API в текстовом виджете в графическом интерфейсе? - PullRequest
0 голосов
/ 02 ноября 2019

Для школьного проекта нам нужно создать графический интерфейс, пользователь вводит имя кода станции, а затем графический интерфейс возвращает список отправлений. Это просто не работает. Мы получаем вылеты в Python, но не в самом графическом интерфейсе.

Код ниже - это то, что мы пробовали (и тысячи других способов, но это единственный код, который приближается к результату, который мы хотим получить)

import http.client, urllib.parse, json
from tkinter import *


def show_application():
    root = Tk()

    frame_start = Frame(master=root, pady=30, padx=30)
    frame_departures = create_departures_frame(root, frame_start)

    frame_start.grid(column=0, row=0, sticky="nsew")
    frame_departures.grid(column=0, row=0, sticky="nsew")

    btn_show_departures = Button(master=frame_start, text='Toon Vertrektijden', command=frame_departures.tkraise)
    btn_show_departures.pack()

    frame_start.tkraise()
    root.mainloop()


def create_departures_frame(root, frame_previous):
    frame_departures = Frame(master=root, pady=40, padx=40)

    label = Label(master=frame_departures, text='Bijspijker Miniproject - Groep 4', height=2)
    label.pack()

    entry = Entry(master=frame_departures)
    entry.pack(padx=25, pady=25)

    button = Button(master=frame_departures, text='Vertrektijden laden')
    button.pack(pady=25)

    btn_show = Button(master=frame_departures,
                      text='Toon text',
                      command=lambda: set_text(entry, text)
                      )
    btn_show.pack(pady=10)

    text = Text(master=frame_departures, height=25, width=25)
    # text.insert(INSERT, 'test')
    # text.delete(1.0, END)
    # text.insert(INSERT, 'Hoi')
    text.pack()

    button = Button(master=frame_departures, text='Terug naar Hoofdscherm', command=frame_previous.tkraise)
    button.pack(pady=25)

    return frame_departures


def set_text(entry, text):
    text.delete('1.0', END)
    text.insert(INSERT, entry.get())


def show_departures(txt_output, departure):
    """This functone fills the Text-widget.
    The function has two parameters:
        txt_output: the widget where the departures need to come out
        departure: string for the stationscode which is needed to get the departures.
The function below is needed to get a list of departures, this list needs to retun in the text widget. 

    """
    pass


def load_departures_NS(station):
    key = {'Ocp-Apim-Subscription-Key': '851bfd5308774ecea20e1280c759716a'}
    params = urllib.parse.urlencode({'station': station})

    try:
        conn = http.client.HTTPSConnection('gateway.apiportal.ns.nl')
        conn.request("GET", "/public-reisinformatie/api/v2/departures?" + params, headers=key)

        response = conn.getresponse()
        responsetext = response.read()
        conn.close()

        data = json.loads(responsetext)
        payloadObject = data['payload']
        departuresList = payloadObject['departures']

        return departuresList
    except Exception as e:
        print("Fout: {} {}".format(e.errno, e.strerror))


result = load_departures_NS('UT')
print(type(result))
for i in result:
    print(i['direction'], i['plannedDateTime'], sep=':\t')


print(result)
show_application()
...