Я пытаюсь создать интерактивную систему управления расходами в Jupyter Notebook, используя ipywidgets для интерфейса и pandas для манипулирования данными. Я настроил интерфейс с кнопками добавления, удаления и отображения расходов. Однако когда я нажимаю кнопку «Добавить расход», ничего не происходит. Расходы не добавляются в набор данных, и сообщения об ошибках отсутствуют. То же самое и с другими кнопками.
import pandas as pd
import ipywidgets as widgets
from IPython.display import display
from matplotlib import pyplot as plt
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
file_path = 'витрати_10000.csv'
data = pd.read_csv(file_path)
print(data.head())
class ExpenseManager:
def __init__(self, data):
self.data = data
def add_expense(self, date, category, amount):
new_expense = pd.DataFrame({"Date": [date], "Category": [category], "Amount": [amount]})
self.data = pd.concat([self.data, new_expense], ignore_index=True)
def remove_expense(self, index):
if index in self.data.index:
self.data = self.data.drop(index)
else:
print("Expense not found.")
def analyze_expenses(self, period='Month'):
if period == 'Day':
return self.data.groupby(self.data['Date']).sum()
elif period == 'Week':
self.data['Week'] = pd.to_datetime(self.data['Date']).dt.isocalendar().week
return self.data.groupby('Week').sum()
elif period == 'Month':
self.data['Month'] = pd.to_datetime(self.data['Date']).dt.to_period('M')
return self.data.groupby('Month').sum()
else:
print("Invalid period.")
em = ExpenseManager(data)
date_input = widgets.DatePicker(description='Date:')
category_input = widgets.Text(description='Category:')
amount_input = widgets.FloatText(description='Amount:')
add_button = widgets.Button(description='Add Expense')
remove_index_input = widgets.IntText(description='Index:')
remove_button = widgets.Button(description='Remove Expense')
display_button = widgets.Button(description='Display Data')
def add_expense(b):
em.add_expense(date_input.value, category_input.value, amount_input.value)
print(f"Added expense: {date_input.value}, {category_input.value}, {amount_input.value}")
def remove_expense(b):
em.remove_expense(remove_index_input.value)
print(f"Removed expense at index: {remove_index_input.value}")
def display_data(b):
display(em.data)
add_button.on_click(add_expense)
remove_button.on_click(remove_expense)
display_button.on_click(display_data)
display(date_input, category_input, amount_input, add_button, remove_index_input, remove_button, display_button)
period_input = widgets.Dropdown(options=['Day', 'Week', 'Month'], description='Period:')
analyze_button = widgets.Button(description='Analyze Expenses')
def analyze_expenses(b):
period = period_input.value
analysis = em.analyze_expenses(period)
display(analysis)
analysis.plot(kind='bar')
plt.show()
analyze_button.on_click(analyze_expenses)
display(period_input, analyze_button)
def generate_pdf_report(data, filename='expense_report.pdf'):
c = canvas.Canvas(filename, pagesize=letter)
width, height = letter
c.drawString(30, height - 40, "Expense Report")
y = height - 80
for i, row in data.iterrows():
c.drawString(30, y, f"{row['Date']} - {row['Category']} - ${row['Amount']}")
y -= 20
if y < 40:
c.showPage()
y = height - 40
c.save()
pdf_button = widgets.Button(description='Generate PDF Report')
def create_pdf_report(b):
generate_pdf_report(em.data)
print("PDF report generated.")
pdf_button.on_click(create_pdf_report)
display(pdf_button)```
I tried to add ```print()``` to handle the function call, but I guess that they are not even calling.
Подробнее здесь: https://stackoverflow.com/questions/785 ... responding
Кнопки ipywidgets не отвечают ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение