python tkinter案例教学: 小账本+简易计算机

本文详细介绍了如何在Python中使用Tkinter库进行基础操作,包括文本框显示、文件读写、CSV数据处理以及按钮事件的响应。代码展示了如何实现实时消费记录和总消费计算功能。
摘要由CSDN通过智能技术生成

目标 

python Tkinter详细基础教学案例,在学习完之后,可以看看怎么将tk进行实战结合

效果图

代码部分

from tkinter import *
from tkinter import messagebox
import csv
import datetime
import re
import os


def is_number(num):
    try:
        float(num)
        return True
    except ValueError:
        pass


def init_file():
    if os.path.exists('add'):
        print('')
    else:
        with open('add', 'w', newline='') as f:
            f.write('0')


def init_opertion():
    with open('and', 'r') as fi:
        content2 = fi.read()
        text1.insert('insert', '当前总消费:')
        text1.insert('end', f'\n\n{content2}元')
    try:
        row_list2 = []
        with open('spend-records.csv', 'r') as ee:
            reader = csv.reader(ee, delimiter=',')
            for row in reader:
                row_list2.append(row[0])
        row_list2.reverse()
        for rows in row_list2:
            text2.insert('end', rows + '\n')
    except:
        print('')


def read_file():
    text2.delete(0.0, 'end')

    row_list = []
    with open('spend-records.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            # print(row)
            row_list.append(row[0])
    # print(row_list)
    row_list.reverse()
    for rows in row_list:
        # print(rows)
        text2.insert('end', rows + '\n')


def time_day():
    current_datetime = datetime.datetime.now()
    month = current_datetime.month
    day = current_datetime.day
    hour = current_datetime.hour
    minute = current_datetime.minute
    return f'{month}月{day}日{hour}:{minute}'


def and_money(sq):
    with open('and', 'r') as f:
        content = f.read()
        add_spend_he = float(content) + sq
        print('add_spend_he:', add_spend_he)
    return add_spend_he


def and_file(mh):
    with open('and', 'w', newline='') as f:
        f.write(mh)


def write_file(ss):
    with open('spend-records.csv', 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([ss])


def get_value1():
    global sw_spend
    spend = e1.get()
    sw_spend = spend
    da_tx1 = time_day() + f'--消费{spend}元'
    if float(spend) < 0:
        return '!'
    if is_number(spend):
        write_file(da_tx1)  # 存储操作

    money_he = and_money(sq=float(spend))
    money_he = round(money_he, 2)
    and_file(mh=str(money_he))
    with open('and', 'r') as f:
        add_content = f.read()

    text1.delete(0.0, 'end')
    text1.insert('insert', '当前总消费:')
    text1.insert('end', f'\n\n{add_content}元')
    read_file()
    e1.delete(0, END)


def get_value2():
    with open('spend-records.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        last_row = list(reader)[-1]
        # print(last_row)
        value_re = re.findall('--消费(.*?)元', last_row[0])[0]
        # print(type(value_re), value_re)
        with open('and', 'r') as file:
            content = file.read()
            add_spend_he = float(content) - float(value_re)
            # print(content)
            if add_spend_he >= 0:
                add_spend_he = round(add_spend_he, 2)
                and_file(mh=str(add_spend_he))

    with open('and', 'r') as fi:
        content2 = fi.read()
        text1.delete(0.0, 'end')
        text1.insert('insert', '当前总消费:')
        text1.insert('end', f'\n\n{content2}元')
    row_list2 = []
    with open('spend-records.csv', 'r') as ee:
        reader = csv.reader(ee, delimiter=',')
        for row in reader:
            row_list2.append(row[0])
    del row_list2[-1]

    row_list2.reverse()
    text2.delete(0.0, 'end')

    for rows in row_list2:
        # print('rows: ', rows)
        text2.insert('end', rows + '\n')
    row_list2.reverse()

    with open('spend-records.csv', 'w', newline='') as fe:
        writer = csv.writer(fe)
        for rows2 in row_list2:
            # print('rows2:', rows2)
            writer.writerow([rows2])


def quit_destroy():
    root.destroy()


root = Tk()
root.geometry('400x400+300+200')
root.resizable(False, False)
root.iconbitmap("atlantikdesigner.ico")
root.title('每日小账本')

l1 = Label(text='今日消费:', bd=1, relief=SUNKEN, font=('楷体', 15))  # 今日消费
l1.place(x=10, y=30)
# l2 = Label(text='总消费纠正:', bd=1, relief=SUNKEN, font=('楷体', 10))  # 总消费纠正
# l2.place(x=10, y=380)

e1 = Entry(root, bd=3, width=5, font=('楷体', 13))
e1.place(x=115, y=30)
# e2 = Entry(root, bd=3, width=7, font=('楷体', 10))
# e2.place(x=105, y=380)

button1 = Button(text='提交', bg='#f0a732', command=get_value1, fg='#f2f7fb', width=3, height=1, bd=4)  # 提交1
button1.place(x=190, y=25)
button2 = Button(text='撤回', bg='#f0a732', command=get_value2, fg='#f2f7fb', width=8, height=1, bd=4)  # 撤回
button2.place(x=100, y=360)
button3 = Button(text='退出', bg='#1a95e2', command=quit_destroy, fg='#f2f6fb', width=4, height=1, bd=4)  # 提交1
button3.place(x=350, y=5)

text1 = Text(root, fg='#1490e2', bg='#2f3439', font=('宋体', '15'), width=12, height=6, bd=1)  # 总花费
text1.place(x=15, y=100)
text2 = Text(root, fg='#f0f0f0', bg='#8c8c8c', font=('宋体', '11'), width=25, height=18, bd=1)  # 花费记录
text2.place(x=190, y=80)
init_opertion()
root.mainloop()


注意:此代码的存储方式为文件格式,因此在使用时需要先创建文件 add 与 spend-records.csv

效果图

代码部分

from tkinter import *

root = Tk()
root.geometry('500x500+400+200')
root.title('胖兔always----计算机')


def calculate():
    num1 = float(entry1.get())
    num2 = float(entry2.get())
    operator = operator_var.get()

    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 != 0:
            result = num1 / num2
        else:
            result = "错误:除以零"

    result_label.config(text="结果: " + str(result))


Label(root, text="输入第一个数字:").grid(row=0, column=0)
entry1 = Entry(root)
entry1.grid(row=0, column=1)

Label(root, text="输入第二个数字:").grid(row=1, column=0)
entry2 = Entry(root)
entry2.grid(row=1, column=1)

operator_var = StringVar()
operator_var.set("+")
operator_label = Label(root, text="选择运算符:")
operator_label.grid(row=2, column=0)
operator_options = ["+", "-", "*", "/"]
operator_menu = OptionMenu(root, operator_var, *operator_options)
operator_menu.grid(row=2, column=1)

calculate_button = Button(root, text="计算", command=calculate)
calculate_button.grid(row=3, column=0, columnspan=2)

result_label = Label(root, text="结果:")
result_label.grid(row=4, column=0, columnspan=2)

root.mainloop()

注意: 此代码简陋,无任何渲染,可以利用所学自行进行渲染

有问题的可以私信博主或者在评论区下面提出哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值