【发布时间】:2021-05-02 03:26:32
【问题描述】:
我在 pyqt5 中创建了一个 GUI 项目,它允许我们在文本输入字段中输入一个国家/地区的名称,然后我们从 CoVid-19 API 获取特定国家/地区的数据。我添加了一个功能(按钮),它使我们可以将 matplotlib 的绘图与 API 中的统计数据保存到我的名为“stats”的文件夹中。假设我进入美国,下载 pdf。没关系。然后我进入德国,下载pdf。没关系,我在 /stats/ 中获得了 USA.pdf 和 Germany.pdf,但如果我删除其中 2 个并进入第三国,比如说加拿大并单击下载按钮,它会再次创建 Canada.pdf 以及 USA 和 Germany。我不知道我什么时候犯了错误,但我正在考虑将 lambda 函数作为参数传递给“clicked”事件,这与此有关。代码如下:
App.py
def create_download_btn(self, data):
self.download_btn.show()
self.download_btn.move(320, 30)
self.download_btn.resize(140, 40)
self.download_btn.setText('Download PDF')
self.download_btn.clicked.connect(lambda: self.create_pdf_plot(data))
self.download_btn.setStyleSheet('background-color: #fff;'
'color: #777;'
'border-style: outset;'
'border-width: 3px;'
'border-color: rgb(220, 20, 60);'
'border-radius: 5px;'
'font-size: 16px;'
'font-weight: bold;'
'padding: 5px;')
def create_pdf_plot(self, data):
export_to_pdf(data)
self.download_btn.hide()
self.create_download_label()
self.download_label.setText(f"You've downloaded the file successfully!\n "
f"Path: /stats/{data[-1]['Country']}.pdf")
create_pdf.py
def export_to_pdf(data):
"""
Creating and exporting plot to a PDF file basing on the given data.
:param data: Number of total cases, deaths, active cases, fetched from the API
:return: void
"""
days = np.array([])
confirmed_cases = np.array([])
deaths = np.array([])
active_cases = np.array([])
# Looping over every index of JSON data
for day, data_elem in enumerate(data):
days = np.append(days, day)
confirmed_cases = np.append(confirmed_cases, data_elem['Confirmed'])
deaths = np.append(deaths, data_elem['Deaths'])
active_cases = np.append(active_cases, data_elem['Active'])
# Creating a plot
plt.plot(days, confirmed_cases, color='black', label='Confirmed cases', linewidth=3)
plt.plot(days, deaths, color='red', label='Deaths', linewidth=3)
plt.plot(days, active_cases, color='green', label='Active cases', linewidth=3)
plt.title(f"{data[-1]['Country']} COVID-19 statistics")
# Creating and displaying table in a program's console using pandas
table = [['Numbers', confirmed_cases[-1], deaths[-1], active_cases[-1]]]
df_table = pd.DataFrame(table)
df_table.columns = (f"{data[-1]['Country']}", 'Confirmed cases', 'Deaths', 'Active cases')
print(df_table)
# Setting axis and saving the plot to a PDF file
plt.xlabel('Days since the first confirmed case')
plt.legend()
plt.savefig(f"./stats/{data[-1]['Country']}.pdf")
plt.clf()
【问题讨论】:
-
请将您的代码减少到显示问题的基本部分。也就是说,您可以摆脱大部分(如果不是全部)绘图代码(只需保存一个单行文本文件;它可能会遇到同样的问题)。然后,确保您的代码实际上是可执行的:目前,PyQT5 的启动代码和您的脚本通常都丢失了。参见例如stackoverflow.com/help/minimal-reproducible-example
-
我不确定,但您似乎
connected 了一个新动作(下载)而没有取消connecting 旧动作,因此单击它会创建所有三个文件。(我'将其发布为评论而不是答案,因为我不经常使用 PYQT5,而且我不是 100% 的 API。 -
@xkcdjerry 非常感谢。
self.download_btn.disconnect()在 create_pdf 函数的最后工作:) -
好的,如果它有效,我将把它作为答案发布 XD
标签: python python-3.x matplotlib pyqt5