我在pyqt5中创建了一个GUI项目,它允许我们在文本输入字段中输入一个国家的名称,然后从新冠肺炎API中获取特定国家的数据。我添加了一个特性(按钮),它使我们可以用统计数据将matplotlib的绘图从API保存到我的文件夹"stats“。假设我进入美国,下载pdf。没问题的。然后我进入德国,下载pdf。没关系,我在/stats/中获得了USA.pdf和Germany.pdf,但是如果我删除其中的两个并进入第三国,比如加拿大并点击下载按钮,它会再次创建Canada.pdf以及美国和德国。我不知道什么时候犯了错误,但我正在考虑将lambda函数作为一个参数传递给“单击”事件,这与此有关。以下是代码:
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()发布于 2021-01-28 09:09:16
您已经connect编辑了一个新的操作(下载新国家的pdf文件),而没有删除旧的操作(下载旧国家的pdf文件),因此单击它将触发所有的操作。这使得它可以创建所有三个文件。
您可以删除connect离子后,您完成了它,以解决该错误。
编辑:
您可以使用self.download_btn.disconnect()删除connect离子。
https://stackoverflow.com/questions/65933644
复制相似问题