下午好。我對 Python 很陌生。我現在正在嘗試學習 tkinter 以及如何使用 API。我有一個呼叫 API 并在視窗中顯示隨機無用事實的代碼。我有以下問題:我希望按鈕“下一步”再次呼叫 API 以顯示另一個事實,但它不起作用。我沒有收到任何錯誤。你能向我解釋什么是錯的以及如何使它正確嗎?非常感謝!
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()
uj5u.com熱心網友回復:
只需清除并將新事實添加到 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()
uj5u.com熱心網友回復:
像這樣的東西(驗證你真的有這個事實)
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/357562.html
上一篇:如何將檔案夾上傳到數字海洋空間?
