Spending Chart چالش 3 از جلسهی 13، سخت
قدم ۳: نمودار خرج هر دسته. chart = app.bar([], []) به صفحه اضافه شده. آخر show() با یک دیکشنری totals جمع خرج هر دسته را حساب کن (فقط ردیفهایی که kind آنها out است؛ دخل در نمودار نمیآید) و با chart.update(...) نمودار را تازه کن، به ترتیبی که دستهها اول بار آمدهاند. مثلاً دخل pocket ۵۰۰۰۰ و خرجهای snack ۱۲۰۰۰، fun ۸۰۰۰ و snack ۵۰۰۰ ← میلههای ۱۷۰۰۰ و ۸۰۰۰ با اسمهای snack و fun.
import app
items = []
GOAL = 100000
def add(kind):
cat = category.value.strip()
try:
amount = int(money.value)
except ValueError:
app.toast("Type a real amount")
return
if amount <= 0:
app.toast("Type a real amount")
return
if cat == "":
app.toast("Type a category")
return
items.append({"kind": kind, "cat": cat, "amount": amount})
money.value = ""
show()
def add_income():
add("in")
def add_spend():
add("out")
def show():
lines.clear()
balance = 0
for item in items:
if item["kind"] == "in":
lines.add(f"+{item['amount']} {item['cat']}")
balance = balance + item["amount"]
else:
lines.add(f"-{item['amount']} {item['cat']}")
balance = balance - item["amount"]
balance_text.value = f"Balance: {balance:,} toman"
if balance >= GOAL:
goal_text.value = "Goal reached!"
else:
goal_text.value = f"Left to goal: {GOAL - balance:,} toman"
# add up the spending of each category in a dictionary, then chart.update(...)
app.title("Pocket Money")
category = app.input("Category")
money = app.number("Amount")
app.button("Income", add_income)
app.button("Spend", add_spend)
balance_text = app.text("Balance: 0 toman")
goal_text = app.text("Left to goal: 100,000 toman")
chart = app.bar([], [])
lines = app.list()
app.run()
راهنما و جواب این چالش · برگشت به درس جلسهی 13: پروژه: پول توجیبی · چالش بعدی: Save and Load
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال