【发布时间】:2017-12-14 23:22:24
【问题描述】:
我一直在努力为全世界制作一个货币转换器。我面临的众多问题之一是我的货币转换器无法计算出汇率本身。你不得不。但当然,我想通了。
但我的问题是:我得到了欧元的汇率,但它是一个列表,我需要它是一个浮点数来进行计算。我该怎么做?
这是我尝试过的:
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
######################################################################
euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange)
################################################################
euro_exchange = float(tree.xpath('//div[@class="price"]/text()')
你得到了模式。当我尝试euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()'))) 时,它说(我正在使用 TkInter,顺便说一句):
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
ValueError: could not convert string to float: "['1.1394']"
当我尝试euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange) 时,我得到了相同的结果。
当我尝试euro_exchange = float(tree.xpath('//div[@class="price"]/text()'):
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(tree.xpath('//div[@class="price"]/text()'))
TypeError: float() argument must be a string or a number, not 'list'
这里是源代码:
import tkinter as tk
from lxml import html
import requests
window = tk.Tk()
window.title("Currency Converter")
window.geometry("500x500")
window.configure(bg="#900C3F")
# window.wm_iconbitmap("penny.ico")
page = requests.get('https://www.bloomberg.com/quote/EURUSD:CUR')
tree = html.fromstring(page.content)
def usd_callback():
usd_amount = float(ent_usd.get())
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
euro_amount = usd_amount / euro_exchange
lbl_euros.config(text="Euro Amount: %.2f€" % euro_amount)
lbl_usd = tk.Label(window, text="Enter the USD ($) here:", bg="#900C3F", font="#FFFFFF")
ent_usd = tk.Entry(window)
btn_usd = tk.Button(window, text="Convert", command=usd_callback, bg="#FFFFFF", font="#FFFFFF")
lbl_euros = tk.Label(window)
lbl_usd.pack()
ent_usd.pack()
btn_usd.pack()
window.mainloop()
任何帮助将不胜感激!谢谢!!
【问题讨论】:
-
不阅读整个代码,但根据错误猜测,您可以这样做
float(yourlist[0]) -
抱歉,错过了!它应该可以工作。如果
euro_exchange是一个只有一个条目的列表。尝试打印euro_exchange[0] -
@JBoyAdvance 这意味着您的变量是列表列表,您可能需要先将其展平,当您执行 euro_exchange[0][0] 时会得到什么
-
@Apaws 这就是我的意思,只是想让他自己意识到这一点 =)
-
@The_Cthulhu_Kid 然后不应该 [0] 返回字符串本身而不是列表值?
标签: python python-3.x tkinter converter currency