我使用API
将一个单位转换为另一个单位。我试图通过"入口小部件"获得用户输入作为浮点数。这是我的代码。
import requests
import tkinter as tk
root = tk.Tk()
def pressMe():
out_entry.insert(1, f'{result}')
in_entry = tk.Entry(root)
in_entry.pack()
out_entry = tk.Entry(root)
out_entry.pack()
but = tk.Button(root, command=pressMe)
but.pack()
val = float(in_entry.get())
url1 = "https://measurement-unit-converter.p.rapidapi.com/length/units"
querystring = {"value":val,"from":"km","to":"m"}
headers = {
"X-RapidAPI-Key": "0760466864***********************4jsnb3eaeb63d084",
"X-RapidAPI-Host": "measurement-unit-converter.p.rapidapi.com"
}
response = requests.request("GET", url1, headers=headers, params=querystring)
data = response.json()
result = data['result']
root.mainloop()
在这里,我制作了第一个条目小部件in_entry
,我可以通过它输入,第二个是out_entry
来显示输出,一个按钮是这样做的。但是我得到了这个错误。
Traceback (most recent call last):
File "d:5ht projectcheck.py", line 290, in <module>
val = float(in_entry.get())
ValueError: could not convert string to float: ''
我知道这个问题是因为我试图将空字符串转换为浮点数,这是不可能的。但我找不到任何解决办法。是否有任何方法可以让我通过in_entry
从用户输入,然后我可以在API
中使用该值,它可以返回转换后的值,然后我可以将此转换后的值插入第二个条目小部件out_entry
。希望你明白我的问题。
这是API
我使用的链接。
https://rapidapi.com/me-Egq5JBzo4/api/measurement-unit-converter/
就像jasonharper说的:"你在条目创建后一毫秒左右才调用。get() -从物理上讲,用户还不可能输入任何东西!">
你能做什么:
import requests
import tkinter as tk
root = tk.Tk()
in_entry = tk.Entry(root)
in_entry.pack()
out_entry = tk.Entry(root)
out_entry.pack()
url1 = "https://measurement-unit-converter.p.rapidapi.com/length/units" #this is a constant, isn't it?
def pressMe(): # the in entry must be above because this function it will get the value
val = float(in_entry.get()) # you get the value here to make sure the user has clicked the button (then you know there is a number in the entry)
querystring = {"value":val,"from":"km","to":"m"}
headers = {
"X-RapidAPI-Key": "0760466864***********************4jsnb3eaeb63d084",
"X-RapidAPI-Host": "measurement-unit-converter.p.rapidapi.com"
} # maybe also a constant? you can this piece of code also place at the top of your program
response = requests.request("GET", url1, headers=headers, params=querystring)
data = response.json()
result = data['result'] #here i get an keyerror because i'm not subscribed
out_entry.insert(1, f'{result}')
but = tk.Button(root, command=pressMe) # the button is created here, because its command is pressme. for that, it's really important that it is below pressme
but.pack()
root.mainloop()
那么我不能进一步帮助你,因为我从你的url中得到的唯一东西是:
{'message': 'You are not subscribed to this API.'}