python3.2 写的一个日记本

这是我费了一个晚上辛辛苦苦写的,希望对大家学习python有帮助

你可以更改其内容重新发布

本程序使用的sqlite3存储数据,还没有查找功能,待日后在写

源码如下:(保存为MyNote.pyw)

from tkinter import * #Frame,Menu,Tk,Entry
from tkinter.scrolledtext import ScrolledText
from tkinter import ttk
import os
import time

import sqlite3
class MSqlite3:
    def __init__ (self, path):
        self.path = path
        if not os.path.isfile(path):
            self.CreateDB()
        else:
            self.conn = sqlite3.connect(path)
    def CreateDB (self):
        self.conn = sqlite3.connect(self.path)
        c = self.conn.cursor()
        c.execute('''create table MyNote(
Title text,
Note text,
date datetime
)''')
        c.close()
    def InsertData (self, data):
        #print ('插入数据',data)
        c = self.conn.cursor()
        for t in data:
            c.execute('insert into MyNote values (?,?,?);', t)
        self.conn.commit()
        c.close()
    def SelectData (self, ResultForm='Title,Note,date', Condition=''):#Condition="date='2011-4-11 0:13:53'"  ResultForm,Condition都是str
        c = self.conn.cursor()
        strsql = 'select '+ResultForm+' from MyNote '
        if len(Condition)>0:
            strsql += 'where '+Condition
        c.execute(strsql)
        #print('选择数据语句',strsql)
        data = []
        for row in c:
            data.append(row)
        c.close()
        return data
    def UpdateData(self, DataCondition): # DataCondition格式(Title,Note,date,Title)
        c = self.conn.cursor()
        c.execute('update MyNote set Title=?,Note=?,date=? where Title=?', DataCondition)
        #print('更新数据:', c.rowcount)
        self.conn.commit()
        c.close()
    def DeleteData(self, Condition):
        c = self.conn.cursor()
        c.execute("delete from MyNote where Title=?",(Condition,))
        #print('删除数据:', c.rowcount)
        self.conn.commit()
        c.close()
    def __del__ (self):
        self.conn.close()

class MyNote(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        self.master = master
        self.master.title('日记本')
        self.combo = ttk.Combobox(master)
        self.combo.pack(side=TOP, fill = 'x', expand = False)
        width = self.combo.winfo_width()
        self.combo.event_generate('<ButtonPress-1>', x=width - 5, y=5)
        self.combo.event_generate('<ButtonRelease-1>', x=width - 5, y=5)
        self.combo.update_idletasks()
       
        self.text = ScrolledText(master)
        self.text.pack(side = BOTTOM, fill = 'both', expand = True)
        self.text.bind("<ButtonPress-3>", self.popup_event)
       
        self.menu = None
        self.db = MSqlite3('./DB.dat')
       
        self.combo.bind('<<ComboboxSelected>>',self.SelectCombobox)
        self.combo.bind('<ButtonPress-1>',self.ListDown)
    def ListDown(self, event):
        #print('鼠标下')
        self.FullCombobox()
    def FullCombobox(self):
        rtdata = self.db.SelectData(ResultForm='Title')
        comlist = []
        for row in rtdata:
            comlist.append(row[0])
        self.combo['values'] = comlist
    def SelectCombobox(self,event):
        rtdata = self.db.SelectData(Condition="Title='"+self.combo.get()+"'")
        #print('文件中:',self.text.get(0.0,END))
        for (title,note,date) in rtdata:
            #print('数据库中note',note)
            self.text.delete(0.0,len(self.text.get(0.0,END))-1.0)
            self.text.insert(0.0,note)
            self.master.title('日记本-'+date)
    def popup_event(self, event):
        if not self.menu:
            self.menu = Menu(self.text, tearoff=0)
            self.menu.add_command(label='复制',command=self.menucopy)
            self.menu.add_command(label='剪切',command=self.menucut)
            self.menu.add_command(label='粘贴',command=self.menupaste)
            self.menu.add_separator()
            self.menu.add_command(label="保存",command=self.Save)
           
        self.menu.tk_popup(event.x_root, event.y_root)
    def menucopy(self):
        if not self.text.tag_ranges("sel"):
            # There is no selection, so do nothing and maybe interrupt.
            return
        self.text.event_generate("<<Copy>>")
    def menucut(self):
        self.text.event_generate("<<Cut>>")
    def menupaste(self):
        self.text.event_generate("<<Paste>>")
        self.text.see("insert")
    def Save (self):
        #Title Note date
        titl = self.combo.get()
        note = self.text.get(1.0, END)
        dtime = time.strftime('%Y-%m-%d %H:%M:%S')
        self.master.title('日记本-'+dtime)
        #print('文件内容',len(note),note)
        if len(note.replace('/n',''))==0:
            self.db.DeleteData(titl)
            return
        rtdata = self.db.SelectData(ResultForm='Title' ,Condition="Title='"+titl+"'")
        if len(rtdata)>0:
            self.db.UpdateData((titl,note,
                            dtime,titl))
            #print('updata', rtdata)
        else:
            data = [(titl,note,dtime)]
            #print('Save', data)
            self.db.InsertData(data)       
    def __del__ (self):
        #self.Save()
        print('MyNote析构')
       
if __name__ == "__main__":
    root = Tk()
    note = MyNote(root)
    note.text.insert(1.0,"""这是一个简单的日记本,
右键菜单<保存>:
如果日记名不存在会保存,
如果日记名已存在会更新,
如果文件日记内容为空会删除日记.""")
    root.mainloop()
   

 

你可能感兴趣的:(Date,python,sqlite,command,Path,import)