tkinter的text控件,绑定事件后不能编辑了

tkinter的text控件,又有新的问题

DateCtrl.py

from tkinter import *

import tkinter.font as tkFont
import calendar
from datetime import date
from tkinter import filedialog

class DateCtrl(Frame):

def __init__ (self, master=None, cnf={}, **kw):
    Frame.__init__( self, bg='lightgray')
    self.master = master
    self.changed = False
    #self.master.size = (800,1200)
    #self.master.resizable(False, False)
    self.master.resizable(True, True)
    self.date = date.today()
   
    self.master.title('我的日历')
    self.master.rowconfigure( 0, weight = 1 )
    self.master.columnconfigure( 0, weight = 1 )
    self.grid( sticky = W+E+N+W )
    self.dayid = []
    self.noteid = []
    self.notefile='NoteData.csv'
    self.NoteData = self.ReadNoteFile()
    self.UpdateUI()
def SetDate(self,date):
    self.date = date
    self.UpdateUI()
def GetDate(self):
    return self.date
    
def ReadNoteFile(self):
    data = []
    # 读取csv文件方式1
    try:
        csvFile = open(self.notefile, "r")
        reader = csv.reader(csvFile) # 返回的是迭代类型
        for item in reader:
            data.append(item)
        csvFile.close()
    
    except IOError: 
        #找不到文件时提示文件不存在
        print("文件不存在!")
    return data
    
def deldata(self,today):
    line=self.GetItem_day(today)
    if line>0:
        del self.NoteData[line]
    
def exitsave(self):
    self.WriteNoteFile()
    root.destroy()
def WriteNoteFile(self):
    self.UpdateData()
    csvFile2 = open(self.notefile,'w', newline='') # 设置newline,否则两行之间会空一行
    writer = csv.writer(csvFile2)
    m = len(self.NoteData)
    for i in range(m):
        writer.writerow(self.NoteData[i])
    csvFile2.close()
    
def UpdateData(self):
    '''calendar.monthrange(2018, 10)
    (0, 31)第一个元素,数字0是这个月的第一天是星期天(上一个月的最后一天为星期几(0-6)),星期天为0;
    第二个元素,数字31是这个月的天数;
    '''
    ds=calendar.monthrange(self.date.year,self.date.month)[1]
    print(self.date.year,self.date.month,ds)
    for i in range(ds):
        today=date(self.date.year,self.date.month,i+1).strftime('%Y-%m-%d')
        self.deldata(today)
        txt=self.noteid[i].get(0.0, self.noteid[i].END)
        if len(txt)>0:
            self.NoteData.append(list(today,txt))

def GetItem_day(self,today):
    line = -1
    m = len(self.NoteData)
    for i in range(m):
        if self.NoteData[i][0]==today:
            line=i
            break
    return line
def GetItem_day2(self,y, m, d):
    today=date(y, m, d).strftime('%Y-%m-%d')
    return self.GetItem_day(today)
    
def FileAdd (self):
    pass
    #file_path = filedialog.askopenfilename()
    self.UpdateUI()
def FileDel (self):
    pass
    self.UpdateUI()
def NoteChanged (self):
    self.changed = True
    print(self.note.get(1.0,END))
    
def MonthBack (self):
    self.UpdateData()
    if date == date.min:
        return
    if self.date.month == 1:
        self.date = self.date.replace(year=self.date.year-1, month=12)
    else:
        if self.date.day > calendar.monthrange(self.date.year,self.date.month-1)[1]:
            self.date = self.date.replace(month=self.date.month-1,day=calendar.monthrange(self.date.year,self.date.month-1)[1])
        else:
            self.date = self.date.replace(month=self.date.month-1)
    self.UpdateUI()
def MonthFoeward (self):
    self.UpdateData()
    if date == date.max:
        return
    if self.date.month == 12:
        self.date = self.date.replace(year=self.date.year+1,month=1)
    else:
        if self.date.day > calendar.monthrange(self.date.year,self.date.month+1)[1]:
            self.date = self.date.replace(month=self.date.month+1,day=calendar.monthrange(self.date.year,self.date.month+1)[1])
        else:
            self.date = self.date.replace(month=self.date.month+1)
    self.UpdateUI()
def UpdateUI (self):
    lendayid = len(self.dayid)
    for i in range(lendayid):
        self.noteid[lendayid-i-1].destroy()
        del(self.noteid[lendayid-i-1])
        self.dayid[lendayid-i-1].destroy()
        del(self.dayid[lendayid-i-1])
        
    '''
    self.note.destroy()
    del(self.note)
    self.fileAddBt.destroy()
    del(self.fileAddBt)
    '''
    
    boldFont = tkFont.Font (size = 20, weight = "bold")
    self.backwardBt = Button(text='<',command=self.MonthBack,font = boldFont).grid(row=0, column=0, sticky=W+E+N+S)
    self.YMBtn = Button(text='%d-%d'%(self.date.year,self.date.month),command=lambda sf=self:print(sf.date),font = boldFont).grid(row=0, column=1,columnspan = 2, sticky=W+E+N+S)
    self.forwardBt = Button(text='>',command=self.MonthFoeward,font = boldFont).grid(row=0, column=3, sticky=W+E+N+S)
    
    self.fileAddBt = Button(text='document',command=self.FileAdd,font = boldFont).grid(row=0, column=4, sticky=W+E+N+S)
    self.ClearBt = Button(text='FileDel',command=self.FileDel,font = boldFont).grid(row=0, column=5, sticky=W+E+N+S)
    #self.exit = Button(text='exit',command=lambda : root.destroy(),font = boldFont).grid(row=0, column=6, sticky=W+E+N+S)
    self.exit = Button(text='exit',command=self.exitsave,font = boldFont).grid(row=0, column=6, sticky=W+E+N+S)
    
    col = 0
    for wk in ['一','二','三','四','五','六','日']:
        Label(text=wk).grid(row=1,column=col,sticky=W+E+N+S)
        col += 1
    row = 2
    col = 0
    today = date.today()
    tttday = date.today().day
    '''calendar.monthrange(2018, 10)
    (0, 31)第一个元素,数字0是这个月的第一天是星期天(上一个月的最后一天为星期几(0-6)),星期天为0;
    第二个元素,数字31是这个月的天数;
    '''
    for weekday in calendar.monthcalendar(self.date.year,self.date.month):
        for dayt in weekday:
            if dayt == 0:
                col+=1
                continue
            bkcolour = 'lightgray'
            '''
            if col == 5:
                bkcolour = 'red'
            if col == 6:
                bkcolour = 'yellow'
            '''
            if dayt == self.date.day:
                bkcolour = 'yellow'
            if dayt == today.day and self.date.month==today.month and self.date.year==today.year:
                bkcolour = 'red'
            tdrelief = FLAT
            if dayt == today.day and self.date.month==today.month and self.date.year==today.year:
                tdrelief = GROOVE
            #bt = Button(self.master,text='%d'%dayt,relief=tdrelief,bg=bkcolour,command=lambda sf=self,dt=dayt:sf.rpday(dt))
            lf=LabelFrame(height=100, width=200, text='%d'%dayt,bg=bkcolour)
            lf.grid(row=row, column=col, sticky=W+E+N+S)
            t_2 =Text(lf, height=3)
            #t_2.bind("<FocusIn>",lambda sf=self,dt=dayt:sf.rpday(dt)) # 绑定光标焦点事件
            # 通过中介函数handlerAdaptor进行事件绑定
            t_2.bind("<FocusIn>", self.handlerAdaptor(self.handler, dt=dayt))
            
            t_2.pack(side=TOP,expand=YES,fill=BOTH)
            lab_2 =Label(lf,text="  ").pack(side=BOTTOM,expand=YES,fill=BOTH)
            #self.dayid.append(t_2)
            self.dayid.append(lf)
            self.noteid.append(t_2)
            line=self.GetItem_day2(self.date.year,self.date.month,dayt)
            if line>=0:
                t_2.insert (1.0,self.NoteData[line][1])

            col+=1
        row+=1
        col=0
    #print(str(dayt))
    print(self.date.strftime( '%Y-%m-%d' ))

def handler(self,event, dt):
    '''事件处理函数'''
    self.date=self.date.replace(day=dt)
    #self.UpdateUI()
 
def handlerAdaptor(self,fun, **kwds):
    return lambda event,fun=fun,kwds=kwds: fun(event, **kwds)


def rpday(self,dt):
    self.date=self.date.replace(day=dt)
    self.UpdateUI()

if name == '__main__':

print(date(2019,11,12).strftime('%Y-%m-%d'))
root = Tk()
root.geometry('1100x800+200+100')
#root.minsize(800, 480)
for i in range(2,8) :
    root.rowconfigure(i, weight=1)
for i in range(7) :
    root.columnconfigure(i, weight=1)
mainfram = DateCtrl(root)
tdt = date.today()
mainfram.SetDate(tdt.replace())#试试重置日期
root.mainloop()
阅读 2.3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题