2个学妹看见都惊呆的 Python 小项目,快快拿去!
1、计算器
1)案例介绍
本例利用 Python 开发一个可以进行简单的四则运算的图形化计算器,会用到 Tkinter 图形组件进行开发。主要知识点:Python Tkinter 界面编程;计算器逻辑运算实现。本例难度为初级,适合具有 Python 基础和 Tkinter 组件编程知识的用户学习。
2)设计原理
从结构上来说,一个简单的图形界面,需要由界面组件、组件的事件监听器(响应各类事件的逻辑)和具体的事件处理逻辑组成。界面实现的主要工作是创建各个界面组件对象,对其进行初始化,以及控制各组件之间的层次关系和布局。
3)示例效果
👉点击领取:最全Python资料合集
4)示例源码
import tkinterimport mathimport tkinter.messageboxclass Calculator(object):# 界面布局方法def __init__(self):# 创建主界面,并且保存到成员属性中self.root = tkinter.Tk()self.root.minsize(280, 450)self.root.maxsize(280, 470)self.root.title('计算器')# 设置显式面板的变量self.result = tkinter.StringVar()self.result.set(0)# 设置一个全局变量 运算数字和f符号的列表self.lists = []# 添加一个用于判断是否按下运算符号的标志self.ispresssign = False# 界面布局self.menus()self.layout()self.root.mainloop()# 计算器菜单界面摆放def menus(self):# 添加菜单# 创建总菜单allmenu = tkinter.Menu(self.root)# 添加子菜单filemenu = tkinter.Menu(allmenu, tearoff=0)# 添加选项卡filemenu.add_command(label='标准型(T) Alt+1', command=self.myfunc)filemenu.add_command(label='科学型(S) Alt+2', command=self.myfunc)filemenu.add_command(label='程序员(P) Alt+3', command=self.myfunc)filemenu.add_command(label='统计信息(A) Alt+4', command=self.myfunc)# 添加分割线filemenu.add_separator()# 添加选项卡filemenu.add_command(label='历史记录(Y) Ctrl+H', command=self.myfunc)filemenu.add_command(label='数字分组(I)', command=self.myfunc)# 添加分割线filemenu.add_separator()# 添加选项卡filemenu.add_command(label='基本(B) Ctrl+F4', command=self.myfunc)filemenu.add_command(label='单位转换(U) Ctrl+U', command=self.myfunc)filemenu.add_command(label='日期计算(D) Ctrl+E', command=self.myfunc)menu1 = tkinter.Menu(filemenu, tearoff=0)menu1.add_command(label='抵押(M)', command=self.myfunc)menu1.add_command(label='汽车租赁(V)', command=self.myfunc)menu1.add_command(label='油耗(mpg)(F)', command=self.myfunc)menu1.add_command(label='油耗(l/100km)(U)', command=self.myfunc)filemenu.add_cascade(label='工作表(W)', menu=menu1)allmenu.add_cascade(label='查看(V)', menu=filemenu)# 添加子菜单2editmenu = tkinter.Menu(allmenu, tearoff=0)# 添加选项卡editmenu.add_command(label='复制(C) Ctrl+C', command=self.myfunc)editmenu.add_command(label='粘贴(V) Ctrl+V', command=self.myfunc)# 添加分割线editmenu.add_separator()# 添加选项卡menu2 = tkinter.Menu(filemenu, tearoff=0)menu2.add_command(label='复制历史记录(I)', command=self.myfunc)menu2.add_command(label='编辑(E) F2', command=self.myfunc)menu2.add_command(label='取消编辑(N) Esc', command=self.myfunc)menu2.add_command(label='清除(L) Ctrl+Shift+D', command=self.myfunc)editmenu.add_cascade(label='历史记录(H)', menu=menu2)allmenu.add_cascade(label='编辑(E)', menu=editmenu)# 添加子菜单3helpmenu = tkinter.Menu(allmenu, tearoff=0)# 添加选项卡helpmenu.add_command(label='查看帮助(V) F1', command=self.myfunc)# 添加分割线helpmenu.add_separator()# 添加选项卡helpmenu.add_command(label='关于计算器(A)', command=self.myfunc)allmenu.add_cascade(label='帮助(H)', menu=helpmenu)self.root.config(menu=allmenu)# 计算器主界面摆放def layout(self):# 显示屏result = tkinter.StringVar()result.set(0)show_label = tkinter.Label(self.root, bd=3, bg='white', font=('宋体', 30), anchor='e', textvariable=self.result)show_label.place(x=5, y=20, width=270, height=70)# 功能按钮MCbutton_mc = tkinter.Button(self.root, text='MC', command=self.wait)button_mc.place(x=5, y=95, width=50, height=50)# 功能按钮MRbutton_mr = tkinter.Button(self.root, text='MR', command=self.wait)button_mr.place(x=60, y=95, width=50, height=50)# 功能按钮MSbutton_ms = tkinter.Button(self.root, text='MS', command=self.wait)button_ms.place(x=115, y=95, width=50, height=50)# 功能按钮M+button_mjia = tkinter.Button(self.root, text='M+', command=self.wait)button_mjia.place(x=170, y=95, width=50, height=50)# 功能按钮M-button_mjian = tkinter.Button(self.root, text='M-', command=self.wait)button_mjian.place(x=225, y=95, width=50, height=50)# 功能按钮←button_zuo = tkinter.Button(self.root, text='←', command=self.dele_one)button_zuo.place(x=5, y=150, width=50, height=50)# 功能按钮CEbutton_ce = tkinter.Button(self.root, text='CE', command=lambda: self.result.set(0))button_ce.place(x=60, y=150, width=50, height=50)# 功能按钮Cbutton_c = tkinter.Button(self.root, text='C', command=self.sweeppress)button_c.place(x=115, y=150, width=50, height=50)# 功能按钮±button_zf = tkinter.Button(self.root, text='±', command=self.zf)button_zf.place(x=170, y=150, width=50, height=50)# 功能按钮√button_kpf = tkinter.Button(self.root, text='√', command=self.kpf)button_kpf.place(x=225, y=150, width=50, height=50)# 数字按钮7button_7 = tkinter.Button(self.root, text='7', command=lambda: self.pressnum('7'))button_7.place(x=5, y=205, width=50, height=50)# 数字按钮8button_8 = tkinter.Button(self.root, text='8', command=lambda: self.pressnum('8'))button_8.place(x=60, y=205, width=50, height=50)# 数字按钮9button_9 = tkinter.Button(self.root, text='9', command=lambda: self.pressnum('9'))button_9.place(x=115, y=205, width=50, height=50)# 功能按钮/button_division = tkinter.Button(self.root, text='/', command=lambda: self.presscalculate('/'))button_division.place(x=170, y=205, width=50, height=50)# 功能按钮%button_remainder = tkinter.Button(self.root, text='//', command=lambda: self.presscalculate('//'))button_remainder.place(x=225, y=205, width=50, height=50)# 数字按钮4button_4 = tkinter.Button(self.root, text='4', command=lambda: self.pressnum('4'))button_4.place(x=5, y=260, width=50, height=50)# 数字按钮5button_5 = tkinter.Button(self.root, text='5', command=lambda: self.pressnum('5'))button_5.place(x=60, y=260, width=50, height=50)# 数字按钮6button_6 = tkinter.Button(self.root, text='6', command=lambda: self.pressnum('6'))button_6.place(x=115, y=260, width=50, height=50)# 功能按钮*button_multiplication = tkinter.Button(self.root, text='*', command=lambda: self.presscalculate('*'))button_multiplication.place(x=170, y=260, width=50, height=50)# 功能按钮1/xbutton_reciprocal = tkinter.Button(self.root, text='1/x', command=self.ds)button_reciprocal.place(x=225, y=260, width=50, height=50)# 数字按钮1button_1 = tkinter.Button(self.root, text='1', command=lambda: self.pressnum('1'))button_1.place(x=5, y=315, width=50, height=50)# 数字按钮2button_2 = tkinter.Button(self.root, text='2', command=lambda: self.pressnum('2'))button_2.place(x=60, y=315, width=50, height=50)# 数字按钮3button_3 = tkinter.Button(self.root, text='3', command=lambda: self.pressnum('3'))button_3.place(x=115, y=315, width=50, height=50)# 功能按钮-button_subtraction = tkinter.Button(self.root, text='-', command=lambda: self.presscalculate('-'))button_subtraction.place(x=170, y=315, width=50, height=50)# 功能按钮=button_equal = tkinter.Button(self.root, text='=', command=lambda: self.pressequal())button_equal.place(x=225, y=315, width=50, height=105)# 数字按钮0button_0 = tkinter.Button(self.root, text='0', command=lambda: self.pressnum('0'))button_0.place(x=5, y=370, width=105, height=50)# 功能按钮.button_point = tkinter.Button(self.root, text='.', command=lambda: self.pressnum('.'))button_point.place(x=115, y=370, width=50, height=50)# 功能按钮+button_plus = tkinter.Button(self.root, text='+', command=lambda: self.presscalculate('+'))button_plus.place(x=170, y=370, width=50, height=50)# 计算器菜单功能def myfunc(self):tkinter.messagebox.showinfo('', '预留接口,学成之后,你是不是有冲动添加该功能.')# 数字方法def pressnum(self, num):# 全局化变量# 判断是否按下了运算符号if self.ispresssign == False:passelse:self.result.set(0)# 重置运算符号的状态self.ispresssign = Falseif num == '.':num = '0.'# 获取面板中的原有数字oldnum = self.result.get()# 判断界面数字是否为0if oldnum == '0':self.result.set(num)else:# 连接上新按下的数字newnum = oldnum + num# 将按下的数字写到面板中self.result.set(newnum)# 运算函数def presscalculate(self, sign):# 保存已经按下的数字和运算符号# 获取界面数字num = self.result.get()self.lists.append(num)# 保存按下的操作符号self.lists.append(sign)# 设置运算符号为按下状态self.ispresssign = True# 获取运算结果def pressequal(self):# 获取所有的列表中的内容(之前的数字和操作)# 获取当前界面上的数字curnum = self.result.get()# 将当前界面的数字存入列表self.lists.append(curnum)# 将列表转化为字符串calculatestr = ''.join(self.lists)# 使用eval执行字符串中的运算即可endnum = eval(calculatestr)# 将运算结果显示在界面中self.result.set(str(endnum)[:10])if self.lists != 0:self.ispresssign = True# 清空运算列表self.lists.clear()# 暂未开发说明def wait(self):tkinter.messagebox.showinfo('', '更新中......')# ←按键功能def dele_one(self):if self.result.get() == '' or self.result.get() == '0':self.result.set('0')returnelse:num = len(self.result.get())if num > 1:strnum = self.result.get()strnum = strnum[0:num - 1]self.result.set(strnum)else:self.result.set('0')# ±按键功能def zf(self):strnum = self.result.get()if strnum[0] == '-':self.result.set(strnum[1:])elif strnum[0] != '-' and strnum != '0':self.result.set('-' + strnum)# 1/x按键功能def ds(self):dsnum = 1 / int(self.result.get())self.result.set(str(dsnum)[:10])if self.lists != 0:self.ispresssign = True# 清空运算列表self.lists.clear()# C按键功能def sweeppress(self):self.lists.clear()self.result.set(0)# √按键功能def kpf(self):strnum = float(self.result.get())endnum = math.sqrt(strnum)if str(endnum)[-1] == '0':self.result.set(str(endnum)[:-2])else:self.result.set(str(endnum)[:10])if self.lists != 0:self.ispresssign = True# 清空运算列表self.lists.clear()# 实例化对象my_calculator = Calculator()
2、记事本
1)案例介绍
tkinter 是 Python下面向 tk 的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter 的优点是简单易用、与 Python 的结合度好。tkinter 在 Python 3.x 下默认集成,不需要额外的安装操作;不足之处为缺少合适的可视化界面设计工具,需要通过代码来完成窗口设计和元素布局。
本例采用的 Python 版本为 3.8,如果想在 python 2.x下使用 tkinter,请先进行安装。需要注意的是,不同 Python 版本下的 tkinter 使用方式可能略有不同,建议采用 Python3.x 版本。本例难度为中级,适合具有 Python 基础和 Tkinter 组件编程知识的用户学习。
2)示例效果
3)示例源码
from tkinter import *from tkinter.filedialog import *from tkinter.messagebox import *import osfilename = ""def author():showinfo(title="作者", message="Python")def power():showinfo(title="版权信息", message="课堂练习")def mynew():global top, filename, textPadtop.title("未命名文件")filename = NonetextPad.delete(1.0, END)def myopen():global filenamefilename = askopenfilename(defaultextension=".txt")if filename == "":filename = Noneelse:top.title("记事本" + os.path.basename(filename))textPad.delete(1.0, END)f = open(filename, 'r')textPad.insert(1.0, f.read())f.close()def mysave():global filenametry:f = open(filename, 'w')msg = textPad.get(1.0, 'end')f.write(msg)f.close()except:mysaveas()def mysaveas():global filenamef = asksaveasfilename(initialfile="未命名.txt", defaultextension=".txt")filename = ffh = open(f, 'w')msg = textPad.get(1.0, END)fh.write(msg)fh.close()top.title("记事本 " + os.path.basename(f))def cut():global textPadtextPad.event_generate("<<Cut>>")def copy():global textPadtextPad.event_generate("<<Copy>>")def paste():global textPadtextPad.event_generate("<<Paste>>")def undo():global textPadtextPad.event_generate("<<Undo>>")def redo():global textPadtextPad.event_generate("<<Redo>>")def select_all():global textPad# textPad.event_generate("<<Cut>>")textPad.tag_add("sel", "1.0", "end")def find():t = Toplevel(top)t.title("查找")t.geometry("260x60+200+250")t.transient(top)Label(t, text="查找:").grid(row=0, column=0, sticky="e")v = StringVar()e = Entry(t, width=20, textvariable=v)e.grid(row=0, column=1, padx=2, pady=2, sticky="we")e.focus_set()c = IntVar()Checkbutton(t, text="不区分大小写", variable=c).grid(row=1, column=1, sticky='e')Button(t, text="查找所有", command=lambda: search(v.get(), c.get(),textPad, t, e)).grid(row=0, column=2, sticky="e" + "w", padx=2,pady=2)def close_search():textPad.tag_remove("match", "1.0", END)t.destroy()t.protocol("WM_DELETE_WINDOW", close_search)def mypopup(event):# global editmenueditmenu.tk_popup(event.x_root, event.y_root)def search(needle, cssnstv, textPad, t, e):textPad.tag_remove("match", "1.0", END)count = 0if needle:pos = "1.0"while True:pos = textPad.search(needle, pos, nocase=cssnstv, stopindex=END)if not pos:breaklastpos = pos + str(len(needle))textPad.tag_add("match", pos, lastpos)count += 1pos = lastpostextPad.tag_config('match', fg='yellow', bg="green")e.focus_set()t.title(str(count) + "个被匹配")top = Tk()top.title("记事本")top.geometry("600x400+100+50")menubar = Menu(top)# 文件功能filemenu = Menu(top)filemenu.add_command(label="新建", accelerator="Ctrl+N", command=mynew)filemenu.add_command(label="打开", accelerator="Ctrl+O", command=myopen)filemenu.add_command(label="保存", accelerator="Ctrl+S", command=mysave)filemenu.add_command(label="另存为", accelerator="Ctrl+shift+s", command=mysaveas)menubar.add_cascade(label="文件", menu=filemenu)# 编辑功能editmenu = Menu(top)editmenu.add_command(label="撤销", accelerator="Ctrl+Z", command=undo)editmenu.add_command(label="重做", accelerator="Ctrl+Y", command=redo)editmenu.add_separator()editmenu.add_command(label="剪切", accelerator="Ctrl+X", command=cut)editmenu.add_command(label="复制", accelerator="Ctrl+C", command=copy)editmenu.add_command(label="粘贴", accelerator="Ctrl+V", command=paste)editmenu.add_separator()editmenu.add_command(label="查找", accelerator="Ctrl+F", command=find)editmenu.add_command(label="全选", accelerator="Ctrl+A", command=select_all)menubar.add_cascade(label="编辑", menu=editmenu)# 关于 功能aboutmenu = Menu(top)aboutmenu.add_command(label="作者", command=author)aboutmenu.add_command(label="版权", command=power)menubar.add_cascade(label="关于", menu=aboutmenu)top['menu'] = menubar# shortcutbar = Frame(top, height=25, bg='light sea green')# shortcutbar.pack(expand=NO, fill=X)# Inlabe = Label(top, width=2, bg='antique white')# Inlabe.pack(side=LEFT, anchor='nw', fill=Y)textPad = Text(top, undo=True)textPad.pack(expand=YES, fill=BOTH)scroll = Scrollbar(textPad)textPad.config(yscrollcommand=scroll.set)scroll.config(command=textPad.yview)scroll.pack(side=RIGHT, fill=Y)# 热键绑定textPad.bind("<Control-N>", mynew)textPad.bind("<Control-n>", mynew)textPad.bind("<Control-O>", myopen)textPad.bind("<Control-o>", myopen)textPad.bind("<Control-S>", mysave)textPad.bind("<Control-s>", mysave)textPad.bind("<Control-A>", select_all)textPad.bind("<Control-a>", select_all)textPad.bind("<Control-F>", find)textPad.bind("<Control-f>", find)textPad.bind("<Button-3>", mypopup)top.mainloop()1 热门推荐