Home > database >  how to get new API result in a tkinter button
how to get new API result in a tkinter button

Time:11-17

Good afternoon. I am very new to Python. I am just now trying to learn tkinter and how to work with API. I have a code that calls API and displays random useless fact in a window. I have the following problem: I want the button "Next" to call API again to display another fact but it is not working. I am not getting any error. Can you please explain to me what is wrong and how to make it right? Thanks a lot!

import tkinter as tk
from tkinter import *
import requests
import json

root = Tk()
root.geometry("400x300")
root.title("API random useless fact")

T = Text(root, height = 10, width = 40)

l = Label(root, text = "Fact")
l.config(font = ("Courier", 14))

api_url = "https://uselessfacts.jsph.pl//random.json?language=en"
response = requests.get(api_url).text
response_info = json.loads(response)
Fact = response_info["text"]

def get_fact():
    response = requests.get(api_url).text
    response_info = json.loads(response)
    Fact = response_info["text"]

# Next not working
b1 = Button(root, text = "Next", command = get_fact)
b2 = Button(root, text = "Exit", command = root.destroy)

l.pack()
T.pack()
b1.pack()
b2.pack()

T.insert(tk.END, Fact)

tk.mainloop()

CodePudding user response:

Something like this (validate you really have the fact)

def get_fact(api_url):
    r = requests.get(api_url)
    if r.status_code == 200:
      data = r.json()
      fact = data['text']
    else:
      fact = f' Failed to read fact data. status code is : {r.status_code}'
    T.delete('1.0', tk.END)
    T.insert(tk.END, fact)

CodePudding user response:

Just clear and add the new fact to the textbox in the get_fact()

import tkinter as tk
from tkinter import *
import requests
import json

root = Tk()
root.geometry("400x300")
root.title("API random useless fact")

T = Text(root, height = 10, width = 40)

l = Label(root, text = "Fact")
l.config(font = ("Courier", 14))

api_url = "https://uselessfacts.jsph.pl//random.json?language=en"

def get_fact():
    response = requests.get(api_url).text
    response_info = json.loads(response)
    Fact = response_info["text"]
    T.delete('1.0', tk.END)
    T.insert(tk.END, Fact)

# Next not working
b1 = Button(root, text = "Next", command = get_fact)
b2 = Button(root, text = "Exit", command = root.destroy)

l.pack()
T.pack()
b1.pack()
b2.pack()

get_fact()

tk.mainloop()
  • Related