class ManagerUI(object):
    def __init__(self, top, conn):
        self.top = top
        self.conn = conn

        self.initComponent()

        self.initTable()

        self.quitButton = Tkinter.Button(self.top,
                                         text='退出',
                                         command=self.top.quit)
        self.quitButton.pack()

    def initComponent(self):
        entryWidth = 40

        self.nameFm = Tkinter.Frame(self.top)
        self.name = Tkinter.StringVar(self.nameFm)
        self.nameLabel = Tkinter.Label(self.nameFm, text='姓名:')
        self.nameLabel.pack(side=Tkinter.LEFT)
        self.nameEntry = Tkinter.Entry(self.nameFm,
                                       width=entryWidth,
                                       textvariable=self.name)
        self.nameEntry.bind('<Return>', self.get)
        self.nameEntry.pack(side=Tkinter.LEFT)
        self.nameFm.pack()

        self.ageFm = Tkinter.Frame(self.top)
        self.age = Tkinter.StringVar(self.ageFm)
        self.ageLabel = Tkinter.Label(self.ageFm, text='年龄:')
        self.ageLabel.pack(side=Tkinter.LEFT)
        self.ageEntry = Tkinter.Entry(self.ageFm,
                                      width=entryWidth,
                                      textvariable=self.age)
        self.ageEntry.bind('<Return>', self.get)
        self.ageEntry.pack(side=Tkinter.LEFT)
        self.ageFm.pack()

        self.jointimeFm = Tkinter.Frame(self.top)
        self.jointime = Tkinter.StringVar(self.jointimeFm)
        self.jointimeLabel = Tkinter.Label(self.jointimeFm, text='加入时间:')
        self.jointimeLabel.pack(side=Tkinter.LEFT)
        self.jointimeEntry = Tkinter.Entry(self.jointimeFm,
                                           width=entryWidth,
                                           textvariable=self.jointime)
        self.jointimeEntry.bind('<Return>', self.get)
        self.jointimeEntry.pack(side=Tkinter.LEFT)
        self.jointimeFm.pack()

        self.btnfm = Tkinter.Frame(self.top)
        self.refreshButton = Tkinter.Button(self.btnfm,
                                            text='刷新',
                                            command=self.refresh)
        self.addButton = Tkinter.Button(self.btnfm,
                                        text='添加',
                                        command=self.add)
        self.getButton = Tkinter.Button(self.btnfm,
                                        text='查询',
                                        command=self.get)
        self.deleteButton = Tkinter.Button(self.btnfm,
                                           text='删除',
                                           command=self.delete)
        self.resetButton = Tkinter.Button(self.btnfm,
                                          text='重置',
                                          command=self.reset)
        self.refreshButton.pack(side=Tkinter.LEFT)
        self.addButton.pack(side=Tkinter.LEFT)
        self.getButton.pack(side=Tkinter.LEFT)
        self.deleteButton.pack(side=Tkinter.LEFT)
        self.resetButton.pack(side=Tkinter.LEFT)
        self.btnfm.pack()

    def initTable(self):
        self.tabFm = Tkinter.Frame(self.top)
        self.tabFm.pack(expand=True, fill=Tkinter.BOTH)  # 后期修改
        self.top.geometry('920x700+200+100')

        self.model = TableModel(rows=0, columns=0)  # like HTML
        self.table = TableCanvas(self.tabFm,
                                 self.model,
                                 cellwidth=120,
                                 cellbackgr='#e3f698',
                                 thefont=('Arial', 12),
                                 rowheight=22,
                                 rowheaderwidth=30,
                                 rowselectedcolor='yellow',
                                 editable=False)  # like CSS
        self.table.createTableFrame()

        self.colnames = ('ID', '姓名', '年龄', '加入时间')
        for name in self.colnames:
            self.table.addColumn(name)

        self.refresh()

    def refresh(self, ev=None):
        try:
            rs = self.conn.execute('select * from person')
            rs = rs.fetchall()

            self.model.deleteRows()
            self.table.addRows(len(rs))
            self.table.redrawTable()

            for index, row in enumerate(rs):
                for i in range(len(self.colnames)):
                    if type(row[i]) == unicode:
                        self.model.data[index][self.colnames[i]] = (
                            '' + row[i]).encode('utf8')
                    elif type(row[i]) == datetime.date:
                        self.model.data[index][
                            self.colnames[i]] = row[i].strftime('%Y-%m-%d')
                    else:  # long or float
                        self.model.data[index][self.colnames[i]] = str(row[i])

            self.table.autoResizeColumns()
        except Exception as e:
            tkMessageBox.showinfo('提示', '刷新失败:%s' % e)

    def add(self, ev=None):
        try:
            self.conn.execute(
                'INSERT INTO person(NAME, AGE, JOINTIME) values("%s", %s, "%s")'
                % (self.name.get().encode('utf8'), self.age.get(),
                   self.jointime.get()))
            self.conn.commit()

            self.refresh()
        except Exception as e:
            tkMessageBox.showinfo('提示', '添加失败:%s' % e)

    def get(self, ev=None):
        try:
            sql = 'select * from person where 1=1'
            if self.name.get():
                sql = sql + ' AND name like "%%%s%%"' % self.name.get()
            if self.age.get():
                sql = sql + ' AND age = %s' % self.age.get()

            rs = self.conn.execute(sql)
            rs = rs.fetchall()

            self.model.deleteRows()
            self.table.addRows(len(rs))
            self.table.redrawTable()

            for index, row in enumerate(rs):
                for i in range(len(self.colnames)):
                    if type(row[i]) == unicode:
                        self.model.data[index][self.colnames[i]] = (
                            '' + row[i]).encode('utf8')
                    elif type(row[i]) == datetime.date:
                        self.model.data[index][
                            self.colnames[i]] = row[i].strftime('%Y-%m-%d')
                    else:  # long or float
                        self.model.data[index][self.colnames[i]] = str(row[i])

            self.table.autoResizeColumns()
        except Exception as e:
            tkMessageBox.showinfo('提示', '查询失败:%s' % e)

    def delete(self, ev=None):
        try:
            self.get()

            sql = 'DELETE FROM person where 1=1'
            if self.name.get():
                sql = sql + ' AND name like "%%%s%%"' % self.name.get()
            if self.age.get():
                sql = sql + ' AND age = %s' % self.age.get()

            if tkMessageBox.askyesnocancel('提示', '确认删除表中的记录?'):
                self.conn.execute(sql)
                self.conn.commit()
                self.refresh()
        except Exception as e:
            tkMessageBox.showinfo('提示', '删除失败:%s' % e)

    def reset(self, ev=None):
        self.name.set('')
        self.age.set('')
        self.jointime.set('')
Ejemplo n.º 2
0
class ManagerUI(object):
	
	def __init__(self, top_, manager_):
		
		self.top = top_
		self.manager = manager_
		
		self.initComponent()
		self.initTable()
		self.quitButton = Tkinter.Button(self.top, text = '退出', command = self.top.quit)
		self.quitButton.pack()
		
		
	def initComponent(self, ev = None):
		# 弄个列表来管理?
		# 注销、标签
	
		entryWidth = 40
		
		#这6个横着摆?
		self.ISBN = Tkinter.StringVar(self.top)
		self.ISBNEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.ISBN)
		self.ISBNEntry.bind('<Return>', self.getBook)
		self.ISBNEntry.pack()
		
		self.bookname = Tkinter.StringVar(self.top)
		self.booknameEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.bookname)
		self.booknameEntry.pack()
		
		self.authorname = Tkinter.StringVar(self.top)
		self.authornameEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.authorname)
		self.authornameEntry.pack()
		
		self.publisher = Tkinter.StringVar(self.top)
		self.publisherEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.publisher)
		self.publisherEntry.pack()
		
		self.publishtime = Tkinter.StringVar(self.top)
		self.publishtimeEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.publishtime)
		self.publishtimeEntry.pack()
		
		self.price = Tkinter.StringVar(self.top)
		self.priceEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.price)
		self.priceEntry.pack()
		
		self.bfm = Tkinter.Frame(self.top)
		# TODO: 按钮加图片(扁平化)
		self.addBookButton = Tkinter.Button(self.bfm, text = '添加', command = self.addBook)
		# 可选TODO:撤销刚刚进行的操作
		self.getBookButton = Tkinter.Button(self.bfm, text = '获取', command = self.getBook)
		self.deleteButton = Tkinter.Button(self.bfm, text = '删除', command = self.deleteBook)
		self.clearTableButton = Tkinter.Button(self.bfm, text = '清空文本', command = self.clearTable)
		
		self.addBookButton.pack(side = Tkinter.LEFT)
		self.getBookButton.pack(side = Tkinter.LEFT)
		self.deleteButton.pack(side = Tkinter.LEFT)
		self.clearTableButton.pack(side = Tkinter.LEFT)
		self.bfm.pack()
	
	
	def initTable(self, ev = None):
		self.tableFrame = Tkinter.Frame(self.top)
		self.tableFrame.pack(expand = True, fill = Tkinter.BOTH) # 后期修改
		self.top.geometry('920x700+200+100')
		
		self.model = TableModel(rows = 0, columns = 0) # like HTML
		self.bookTable = TableCanvas(self.tableFrame, self.model, cellwidth=120, cellbackgr='#e3f698',
                        thefont=('Arial',12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS
		self.bookTable.createTableFrame()
		
		self.colnames = ('ISBN', '书名', '作者', '出版社', '出版时间', '价格')
		for name in self.colnames:
			self.bookTable.addColumn(name)
		self.bookTable.addRows(1)
		self.bookTable.autoResizeColumns()
		
		
	def addBook(self, ev = None):
		# TODO: 防止 SQL 注入
		try:
			self.manager.query('insert into book values(%s,\'%s\',\'%s\',\'%s\',\'%s\',%s)' %
			(self.ISBN.get(),
			self.bookname.get().encode('utf8'),
			self.authorname.get().encode('utf8'),
			self.publisher.get().encode('utf8'),
			self.publishtime.get(),
			self.price.get()))
			self.manager.commit()
		except MySQLdb.IntegrityError, err:
			# TODO 已经存在此书
			print u'已经存在此书'