自己动手丰衣足食,Python 40行代码制作一个专属于自己的记事本

2022-05-02科技224

今天我们使用Python制作一个简单的记事本,老规矩:废话不多说,直接上代码!

记事本界面

#! /usr/bin/env python

#coding=utf-8

from Tkinter import* #导入Tkinter库

from tkMessageBox import showinfo #导入消息提示库

import os #导入文件处理系统库

import sys

import tkFileDialog #导入存储路径选择库

reload(sys) #设置编码方式

sys.setdefaultencoding('utf8')

def saveClick(event): #定义存储函数

try:

filename = tkFileDialog.askopenfilename(initialdir='j:\date') #选择存储路径,默认为j:\date

lab=Label(root,text=filename,width=20) #实例化标签

lab.place(x=150,y=278) #绝对坐标定位

f=open(filename,'a') #建立流管道

f.write(text.get(1.6,'end')) #将文本内容写入文件

showinfo(title='存储提示:',message='保存成功!') #存储成功后提示消息

except Exception:

pass

存储成功界面

def win:

root=Tk #实例化Tkinter

global text,lab,root #声明text,lab,root为全局变量

root.minsize(600,310) #设置窗口大小

root.maxsize(600,310)

frame=Frame(root,width=300,height=300) #实例化Frame

frame.place(x=10,y=10) #绝对坐标定位 text=Text(frame,width=80,height=20) #实例化Text

text.insert(INSERT,请输入文字:) #为Text插入文字

text.pack #使Text显示

button=Button(root,text='save',relief='sunken') #实例化Button

button.bind('Button-1',saveClick) #为Button绑定单击事件

button.place(x=525,y=275) #绝对坐标定位

but=Button(root,text='选 择 路 径',width=15,relief='sunken') #实例化Button

but.place(x=10,y=275) #绝对坐标定位

root.mainloop #使窗口刷新显示if __name__=='__main__':

win

鉴于有读者朋友反应代码比较难懂,所以本次精心添加了注释;

新手上路,有错误之处请大神们多多包涵;喜欢的朋友可以点下关注,每天都有更新!

你可能想看:
分享给朋友: