class EmailList(BaseWidget): def __init__(self): BaseWidget.__init__(self, 'Email List') self._list_of_emails = list() self._emailList = ControlList( 'Emails', item_selection_changed_event=self.__get_body) self._emailList.horizontal_headers = ['Sender', 'Date', 'Subject'] self._emailList.readonly = True self._emailList.select_entire_row = True self._email = '*****@*****.**' self._pass = '******' self._panel = EmailWindow() self._panel.parent = self # Get a connection to your email account try: include_seen = True self._myCon = MyCon(self._email, self._pass) self._myCon._con.select('inbox') self._email_ids = self._myCon.get_email_ids(include_seen) self._email_index = 0 # initialize index to first element except ValueError as e: print(e) index = 0 for email in self._email_ids: sender, date, subject, body = self._myCon.extract_info(email) mail = Email(index, sender, date, subject, body) self._list_of_emails.append(mail) self._emailList.__add__( [mail.get_sender(), mail.get_date(), mail.get_subject()]) self._emailList.resize_rows_contents() def __get_body(self): index = self._emailList.selected_row_index if index is not None: self._panel._bodyText.value = self._list_of_emails[index].get_body( ) self._panel.show()
class NotificationsWidget(Notifications, BaseWidget): def __init__(self, user = None, connection = None): Notifications.__init__(self) BaseWidget.__init__(self) self._user = user self._connection = connection self._refresh_button = ControlToolButton('Refresh', maxheight= 50, maxwidth= 100) self._notifCache=None self._notifList = ControlList('Notifications', select_entire_row = True) self._notifList.readonly = True self._notifList.cell_double_clicked_event = self.__onDouble #self._notifList.item_selection_changed_event = self.__softSelect self._notifList.horizontal_headers = [ 'Timestamp', 'Symbol', 'Price', 'Message'] self._notifList.add_popup_menu_option('Edit', function_action= self.__popEdit) self._notifList.add_popup_menu_option('Delete', function_action= self.__deleteNotif) self._plusBtn = ControlButton('New Notification') self._plusBtn.value= self.__addNotifBtnAction if self._user!=None and self._connection!=None: self._refresh_button.value= self._refresh self._retreive_existing() def _refresh(self): self._notifList.clear() self._retreive_existing() if self.parent!=None: self.parent.persist_login() def _retreive_existing(self): try: pull_list = pull_notifications(self._user, self._connection) self._notifCache=pull_list except ValueError as err: err= ErrorWin(err) err.parent = self err.show() return if pull_list: for i in pull_list: ts = pull_list[i]['timestamp'] datestring=datetime.fromtimestamp(ts/1e3).strftime('%Y-%m-%d %H:%M:%S') self._notifList.__add__([datestring, pull_list[i]['symbol'], pull_list[i]['price'], pull_list[i]['message']]) def __addNotifBtnAction(self): if self.parent!=None: self.parent.persist_login() win = NotificationWidget(self._user, self._connection, '', '', '', '', 'new') win.parent = self win.show() def __rmNotifBtnAction(self): self.__deleteNotif(self) def __onDouble(self, row, column): if self.parent!=None: self.parent.persist_login() timestamp = self._notifList.get_value(0, row) symbol = self._notifList.get_value(1, row) index = self._notifList.get_value(2, row) message = self._notifList.get_value(3, row) win = NotificationWidget(self._user, self._connection, timestamp, symbol, index, message, 'view') win.parent = self win.show() def __popEdit(self): row = self._notifList.selected_row_index timestamp = self._notifList.get_value(0, row) symbol = self._notifList.get_value(1, row) index = self._notifList.get_value(2, row) message = self._notifList.get_value(3, row) for i in self._notifCache: if self._notifCache[i]['message']== message: key = i #print("popedit key found: " + key) win = NotificationWidget(self._user, self._connection, timestamp, symbol, index, message, "edit", key) win.parent = self win.show() def __softSelect(self, row, column): self._notifList.form.get_value(row, column) def __deleteNotif(self): row = self._notifList.selected_row_index message = self._notifList.get_value(3, row) for i in self._notifCache: if self._notifCache[i]['message']== message: key= i try: del_notification(self._user, self._connection, key) self._notifList.__sub__(row) except ValueError as error: err= ErrorWin(error) err.parent = self err.show() return
class AdminWidget(BaseWidget): def __init__(self, user=None, connection=None): BaseWidget.__init__(self) self._admin = user self._connection = connection self._add_user_button = ControlButton('New User') self._refresh_button = ControlButton('Refresh List') self._add_user_button.value= self.__add_User_btnAction self._refresh_button.value= self.__refresh self._userList = ControlList('Users',select_entire_row=True) self._userList.readonly=True self._userList.cell_double_clicked_event = self.__onSelect self._userList.horizontal_headers=['Admin', 'Name', 'Email'] self._userList.add_popup_menu_option('Toggle Admin Status', function_action=self.__admin_power) self._userList.add_popup_menu_option('Edit', function_action=self.__popEdit) if self._admin!=None and self._connection!=None: self.__retreive_users() def __refresh(self): self._userList.clear() self.__retreive_users() if self.parent!=None: self.parent.persist_login() def __retreive_users(self): try: self._user_pull= pull_users(self._admin, self._connection) except ValueError as err: err=ErrorWin(err) err.parent=self err.show() return if self._user_pull!=None: admins = self._connection['Database'].child('admins').shallow().get(self._admin['idToken']) for user in self._user_pull: check = False if user in admins.val(): check = True self._userList.__add__([check, self._user_pull[user]['name'], self._user_pull[user]['email']]) def __onSelect(self, row, column): if self.parent!=None: self.parent.persist_login() name = self._userList.get_value(1, row) email = self._userList.get_value(2, row) for i in self._user_pull: if self._user_pull[i]['email'] == email: uid = i try: services = self._user_pull[i]['services'] except: services = {"notifications" : False, "analysis": False, "newsletter" : False} win = UserWidget(self._admin, self._connection, 'edit', uid, email, name, services) win.parent = self win.show() def _refresh(self): self._userList.clear() self._user_pull= pull_users(self._admin, self._connection) if self._user_pull!=None: for user in self._user_pull: self._userList.__add__([self._user_pull[user]['name'], self._user_pull[user]['email']]) def __popEdit(self): row = self._userList.selected_row_index name = self._userList.get_value(1, row) email = self._userList.get_value(2, row) print(email) for i in self._user_pull: if self._user_pull[i]['email'] == email: uid = i try: services = self._user_pull[i]['services'] except: services = {"notifications" : False, "analysis": False, "newsletter" : False} win = UserWidget(self._admin, self._connection,'edit', uid, email, name, services) win.parent = self win.show() def __add_User_btnAction(self): if self.parent!=None: self.parent.persist_login() win = UserWidget(self._admin, self._connection, 'new') win.parent = self win.show() def _add_User(self, user): pass def _update_user(self, account): self._connection['Database'].child("users").child(account._uid).update({"name": account.name, "email": account.email, "services": account.services}) def __admin_power(self): if self.parent!=None: self.parent.persist_login() row = self._userList.selected_row_index email = self._userList.get_value(2, row) for i in self._user_pull: if self._user_pull[i]['email'] == email: self._selected_uid = i if self._selected_uid == self._admin['localId']: err = ErrorWin('Action not allowed - Cannot remove self as admin.') err.parent= self err.show() return if self._userList.get_value(0, row)== 'true':#already admin conf= ConfirmWin('Are you sure you want to remove this admin?', self._userList.get_value(1, row)) conf.parent = self conf.show() return else: conf= ConfirmWin('Are you sure you want to make this account admin?', self._userList.get_value(1, row)) conf.parent = self conf.show() return def _admin_toggle(self): toggle_admin(self._admin, self._connection, self._selected_uid) self._selected_uid='' self.__refresh()
class LibMaster(BaseWidget): def __init__(self, title='LibMaster'): super(LibMaster, self).__init__(title) self.debug = False #Import controls self._openImportFile = None self._openImportDir = None self._importPathText = ControlText() self._openFileButton = ControlButton('Open a file') self._openDirButton = ControlButton('Open a directory') self._importButton = ControlButton('Import') self._importTextArea = ControlTextArea() #Configure controls self._configCombo = ControlCombo('Library') self._configNameText = ControlText('Loop name') self._configPageNumber = ControlNumber('Start page', default=1, min=1, max=20000) self._configDict = {} self._configList = ControlList('Application Plan', add_function=self.__buttonAction_Add, remove_function=self.__buttonAction_Del) self._configLoadButton = ControlButton('Load') self._configAddButton = ControlButton('Add') self._configDelButton = ControlButton('Delete') self._configClearButton = ControlButton('Clear') self._configSaveButton = ControlButton('Save') self._configGenButton = ControlButton('Generate') self._configTextArea = ControlTextArea() #Combine controls self._openDBFile = ControlFileOpen('Choose the database file: ', opened_file_type='txt') self._openArgFile = ControlFileOpen('Choose the argument file: ', opened_file_type='xlsx') self._combineButton = ControlButton('Combine') self._combineTextArea = ControlTextArea() #setup all controls self.formset = [{ ' 1. Import ': [ '', ('', '_importPathText', ''), ('', '_openFileButton', '', '_openDirButton', ''), (' ', '_importButton', ' '), '', ('', '_importTextArea', ''), '' ], ' 2. Configure ': [ '', ('', '_configCombo', '', '_configNameText', '', '_configPageNumber', ''), ('', '_configList', ''), ('', '_configAddButton', '', '_configDelButton', '', '_configClearButton', ''), ('', '_configLoadButton', '', '_configSaveButton', '', '_configGenButton', ''), '', ('', '_configTextArea', ''), '' ], ' 3. Combine ': [ '', ('', '_openDBFile', ''), ('', '_openArgFile', ''), (' ', '_combineButton', ' '), '', ('', '_combineTextArea', ''), '' ] }] #Button Actions self._openFileButton.value = self.__buttonAction_OpenFile self._openDirButton.value = self.__buttonAction_OpenDir self._importButton.value = self.__buttonAction_Import self._configLoadButton.value = self.__buttonAction_Load self._configAddButton.value = self.__buttonAction_Add self._configDelButton.value = self.__buttonAction_Del self._configClearButton.value = self.__buttonAction_Clear self._configSaveButton.value = self.__buttonAction_Save self._configGenButton.value = self.__buttonAction_Gen self._combineButton.value = self.__buttonAction_Combine #set all text area to read only self._importTextArea.readonly = True self._configTextArea.readonly = True self._combineTextArea.readonly = True #Combo box lists correct library files in './Library' directory self._configCombo += 'Select library' if not os.path.exists('Library'): os.mkdir('Library') else: file_lst = os.listdir('Library') for file in file_lst: if file[-4:] == '.txt' and (file[:-4] + '.xlsx') in file_lst: self._configCombo += file[:-4] else: pass #set configuration list property headers = [] headers.append(' ' * 10 + 'Library' + ' ' * 10) headers.append(' ' * 10 + 'Loop Name' + ' ' * 10) headers.append(' Start Page ') headers.append(' End Page ') self._configList.horizontal_headers = headers self._configList.select_entire_row = True self._configList.readonly = True def __buttonAction_OpenFile(self): try: self._openImportFile = ControlFileOpen('Choose library file:', opened_file_type='txt') self._openImportFile.click() self._importPathText.value = self._openImportFile.value except Exception as err: self._importTextArea.__add__('Open file error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __buttonAction_OpenDir(self): try: self._openImportDir = ControlDir('Choose directory:') self._openImportDir.click() self._importPathText.value = self._openImportDir.value except Exception as err: self._importTextArea.__add__('Open file error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __buttonAction_Import(self): try: #import a file, using main import function from 'Import.py' if self._openImportFile is not None and self._openImportFile.value == self._importPathText.value: addedFiles = Import([self._openImportFile.value], self._importTextArea.__add__) self._importTextArea.__add__( 'Import finish. Libraries are exported under \'./Library\' directory.' ) for add_file in addedFiles: self._configCombo += addedFiles[0][:-4] #import a directory, find valid files in directory before calling Import elif self._openImportDir is not None and self._openImportDir.value == self._importPathText.value: files = [] dirs = os.listdir(self._openImportDir.value) for file in dirs: if file[-4:] == '.txt': files.append(self._openImportDir.value + '/' + file) else: pass if len(files) > 0: addedFiles = Import(files, self._importTextArea.__add__) self._importTextArea.__add__( 'Import finish. Libraries are exported under \'./Library\' directory.' ) for add_file in addedFiles: self._configCombo += add_file[:-4] else: self._importTextArea.__add__( 'No valid file in the directory.') #no file selected else: self._importTextArea.__add__('No file or directory selected.') except Exception as err: self._importTextArea.__add__('Error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __helper_Add2Dict(self, lst): combo, name, pageNum = lst[0], lst[1], int(lst[2]) if name in self._configDict.values(): raise Exception('Loop name conflict.') else: pass wb = load_workbook('./Library/' + combo + '.xlsx') ws = wb['Info'] for row in list(ws.rows): if row[0].value == 'Page count': pageCount = row[1].value else: pass for i in range(pageCount): if pageNum + i in self._configDict: raise Exception('Page conflict.') else: pass lst[3] = pageNum + pageCount - 1 for i in range(pageCount): self._configDict[pageNum + i] = name def __buttonAction_Load(self): try: self._loadConfigFile = ControlFileOpen(opened_file_type='json') self._loadConfigFile.click() if self._loadConfigFile.value != '': with open(self._loadConfigFile.value, 'r') as f: jstr = json.load(f) table = jstr['value'] self._configDict.clear() for row in table: self.__helper_Add2Dict(row) self._configList.load_form(jstr, None) else: raise Exception('No file selected.') self._configTextArea.__add__('List loaded from ' + self._loadConfigFile.value) except Exception as err: self._configTextArea.__add__('\'Load\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Add(self): try: nameText = '__' + self._configCombo.text if self._configNameText.value == '' else self._configNameText.value lst = [ self._configCombo.text, nameText, self._configPageNumber.value, 0 ] self.__helper_Add2Dict(lst) self._configList.__add__(lst) self._configList.resizecolumns = False except Exception as err: self._configTextArea.__add__('\'Add\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Del(self): try: if self._configList.selected_row_index is None: raise Exception('No row selected.') for i in range(int(self._configList.get_currentrow_value()[2]), int(self._configList.get_currentrow_value()[3]) + 1): del self._configDict[i] self._configList.__sub__(self._configList.selected_row_index) except Exception as err: self._configTextArea.__add__('\'Delete\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Clear(self): try: self._configDict.clear() self._configList.clear() except Exception as err: self._configTextArea.__add__('\'Clear\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Save(self): try: self._saveConfigFile = ControlFileSave(saved_file_type='json') self._saveConfigFile.click() if self._saveConfigFile.value != '': with open(self._saveConfigFile.value, 'w') as f: json.dump(self._configList.save_form({}, None), f) else: raise Exception('File not specified.') self._configTextArea.__add__('List saved to ' + self._saveConfigFile.value) except Exception as err: self._configTextArea.__add__('\'Save\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Gen(self): try: table = self._configList.value for i in range(len(table)): table[i][0] += '.txt' table.insert(0, ['Library', 'Loop Name', 'Start Page', 'End Page']) self._saveArgFile = ControlFileSave(saved_file_type='xlsx') self._saveArgFile.click() Config(table, self._saveArgFile.value) self._configTextArea.__add__('Arguments file is generated.') self._openArgFile.value = self._saveArgFile.value except Exception as err: self._configTextArea.__add__('\'Generate\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Combine(self): try: self._saveDPUFile = ControlFileSave(saved_file_type='txt') self._saveDPUFile.click() Combine(self._openDBFile.value, self._saveDPUFile.value, self._openArgFile.value) self._combineTextArea.__add__('New DPU file is generated.') except Exception as err: self._combineTextArea.__add__('Error: ' + repr(err)) if self.debug: self._combineTextArea.__add__(traceback.format_exc())
class UserWidget(User, BaseWidget): def __init__(self, admin=None, connection=None, flag='', uid='', email='', name='', services={}): super(UserWidget, self).__init__(uid, email, name, services) BaseWidget.__init__(self, 'User') self._admin = admin self._connection = connection self._flag = flag self.changes = [] #0 is name change, 1 is services change if flag == 'edit': self._editBtn = ControlButton('Edit') self._editBtn.value = self._edit elif flag == 'new': self._editBtn = ControlButton('Save') self._editBtn.value = self._save else: self._closeBtn = ControlButton('Close') self._closeBtn.value = self._close if uid != '': self._uid_field = ControlText('User_Key') self._uid_field.value = uid self._email_field = ControlText('Email') self._email_field.readonly = True if email != '': self._email_field.value = email self._name_field = ControlText('Name') self._name_field.readonly = True if name != '': self._name_field.value = name self._services = services self._services_field = ControlList('Services') self._services_field.readonly = True self._services_field.horizontal_headers = ['Service', 'Value'] #self._services_field.cell_double_clicked_event = None if services != {}: for i in services: self._services_field.__add__([i, services[i]]) def _edit(self): self._editBtn.label = 'Save' self._editBtn.value = self._save self._email_field.readonly = False self._name_field.readonly = False self._services_field.readonly = False self._services_field.cell_double_clicked_event = self._toggle def _save(self): if self.parent != None: self.name = self._name_field.value self.email = self._email_field.value self.services = self._services self.uid = self._uid_field.value if self._flag == 'edit': self.parent._update_user(self) elif self._flag == 'new': self.parent._add_User(self) self._close() def _toggle(self, row, column): val = self._services_field.get_value(column, row) if val == True: self._services_field.set_value(column, row, False) self._services[self._services_field.get_value(0, row)] = False else: self._services_field.set_value(column, row, True) self._services[self._services_field.get_value(0, row)] = True def _close(self): close_win(self)
class SimpleExample1(BaseWidget): def __init__(self): super(SimpleExample1, self).__init__(' Thực Tập Cơ Sở ') #main menu self.mainmenu = [{ 'File': [{ 'Open Excel': self.__open, 'icon': 'img/folder_open.png' }, '-', { 'Import': self.__import, 'icon': 'img/import_icon.png' }] }] #tkinler for messagebox root = tk.Tk() root.withdraw() #list self._list = ControlList('Danh sách') self._list.readonly = True #1.open file excel và heap sort self._file = ControlFile('Chọn file Excel') self._butheapsort = ControlButton('Heap Sort') self._butheapsort.icon = 'img/sort_icon.png' self._butheapsort.value = self.__heapsort self._butloadexcel = ControlButton('Load') self._butloadexcel.icon = 'img/load_icon.png' self._butloadexcel.value = self.__load self._butremoveloadexcel = ControlButton('Hủy bỏ') self._butremoveloadexcel.icon = 'img/remove_icon.png' self._butremoveloadexcel.value = self.__removeloadexcel #2.thêm thửa đất self._diachi = ControlText('Địa chỉ') self._dientich = ControlText('Diện tích') self._chusohuuhientai = ControlText('Chủ sở hữu hiện tại') self._loainha = ControlText('Loại nhà') self._mucdichsudung = ControlText('Mục đích Sử dụng') self._giatien = ControlText('Giá tiền') self._but1 = ControlButton('Thêm thửa đất') self._but1.value = self.__add self._but1.icon = 'img/add_icon.png' #3.tìm kiếm thử đất và xóa #tìm kiếm self._butsearch = ControlButton('Tìm kiếm') self._butsearch.icon = 'img/search_icon.png' self._butsearch.value = self.__search self._timkiem = ControlText('Tìm Kiếm') self._checklisttimkiem = ControlCheckBoxList('Chọn tiêu chí tìm kiếm:') self._checklisttimkiem.hide() self._buttonhideshowtimkiem = ControlButton('Hiển thị tiêu chí') self._buttonhideshowtimkiem.value = self._buthideshowtimkiem self._buttonhideshowtimkiem.icon = 'img/show.png' self._buthuybo = ControlButton('Hủy bỏ') self._buthuybo.icon = 'img/remove_icon.png' self._buthuybo.value = self._huybo #xóa self._textxoa = ControlText('Nhập nội dung cần xóa') self._butxoa = ControlButton('Xoá') self._butxoa.icon = 'img/delete_icon.png' self._butxoa.value = self.__xoa self._checklistxoa = ControlCheckBoxList('Chọn tiêu chí xóa:') self._checklistxoa.hide() self._buttonhideshowxoa = ControlButton('Hiển thị tiêu chí') self._buttonhideshowxoa.value = self._buthideshowxoa self._buttonhideshowxoa.icon = 'img/show.png' #4.xuất self._directory = ControlDir('Chọn chỗ xuất file excel') self._tenfilexuat = ControlText('Tên file xuất') self._butxuat = ControlButton('Xuất') self._butxuat.icon = 'img/export_icon.png' self._butxuat.value = self.__xuat #5.merge self._filemerge = ControlFile('Chọn file Excel cần merge') self._butimport = ControlButton('Import') self._butimport.icon = 'img/import2_icon.png' self._butimport.value = self._import self._butmerge = ControlButton('Gộp') self._butmerge.icon = 'img/merge_icon' self._butmerge.value = self._merge self._butmerge.hide() self._listmerge = ControlList('Danh sách import') self._listmerge.readonly = True self._buttonhideshow = ControlButton('Hiển thị tùy chọn') self._buttonhideshow.value = self._buthideshow self._buttonhideshow.hide() self._buttonhideshow.icon = 'img/show.png' self._checklist = ControlCheckBoxList( 'Chọn tiêu chí giữ trong danh sách import:') self._checklist.hide() self._buttonremovemerge = ControlButton('Hủy bỏ') self._buttonremovemerge.value = self._remove self._buttonremovemerge.icon = 'img/remove_icon.png' self._buttonremovemerge.hide() #formset as layout self.formset = [{ '1.Mở File và Heap Sort': [ ' ', '_file', ' ', (' ', '_butloadexcel', '_butremoveloadexcel', '_butheapsort', ' '), ' ' ], '2.Thêm': [ ' ', '_diachi', '_dientich', '_chusohuuhientai', '_loainha', '_mucdichsudung', '_giatien', ' ', (' ', '_but1', ' '), ' ' ], '3.Tìm kiếm và Xóa': [ ' ', '_textxoa', ' ', (' ', '_butxoa', '_buttonhideshowxoa', '_checklistxoa', ' '), ' ', '_timkiem', ' ', (' ', '_butsearch', '_buttonhideshowtimkiem', '_checklisttimkiem', '_buthuybo', ' '), ' ' ], '4.Xuất': [ ' ', '_directory', ' ', '_tenfilexuat', ' ', (' ', '_butxuat', ' '), ' ' ], '5.Merge danh sách': [ '_filemerge', (' ', '_butimport', '_butmerge', '_buttonremovemerge', '_buttonhideshow', '_checklist', ' '), '_listmerge' ], }, '', '', '_list'] #event for mainmenu def __open(self): self._file.click() def __import(self): self._filemerge.click() #event tab 1 #event for _butremoveloadexcel def __removeloadexcel(self): if not values: messagebox.showwarning("Warning", "Không có thông tin cần loại bỏ") else: values.clear() fsqc.clear() self._refresh() #event for _butheapsort def __heapsort(self): if self._list.rows_count <= 1: messagebox.showwarning("Warning", "không có list để sort") else: heap_sort() self._refresh() #event for load button def __load(self): if not self._file.value: tk.messagebox.showwarning("Warning", "Đường dẫn trống") else: try: if self._file.value != '': path = self._file.value read(path) self._list.value = [values_name] n = 0 for i in range(int(len(values) / numberofcols[0])): self._list.__add__(values[n:n + numberofcols[0]]) n = n + numberofcols[0] if self._checklistxoa.count < 1: for s in range(0, len(values_name)): self._checklistxoa.__add__((values_name[s])) if self._checklisttimkiem.count < 1: for s in range(0, len(values_name)): self._checklisttimkiem.__add__((values_name[s])) except: tk.messagebox.showwarning( "Warning", "Không thể đọc file khác excel hoặc đường dẫn không đúng") #event tab 2 #event for thêm button def __add(self): var = str(self._diachi.value).strip().split(',') var2 = var[0].split('/') var3 = var2[0] if self._list.rows_count < 1: messagebox.showwarning("Warning", "Không có list để thêm vào") elif len(var3) == 0 \ or (not var3[0].isdigit() and len(var3) == 1 ) \ or ( not var3[0:(len(var3) -1 )].isdigit() and len(var3) > 1 ) : messagebox.showwarning("Warning", "Địa chỉ không hợp lệ") elif not str(self._dientich.value).strip().isnumeric(): messagebox.showwarning("Warning", "Diện tích không hợp lệ") elif not str(self._chusohuuhientai.value).strip(): messagebox.showwarning("Warning", "Chủ sở hữu trống") elif not str(self._loainha.value).strip(): messagebox.showwarning("Warning", "loại nhà trống") elif not str(self._mucdichsudung.value).strip(): messagebox.showwarning("Warning", "mục đích sử dụng trống") elif not str(self._giatien.value).strip(): messagebox.showwarning("Warning", "giá tiền trống") else: index = self._list.rows_count values.append(index) values.append(str(self._diachi.value)) values.append(str(self._dientich.value)) values.append(str(self._chusohuuhientai.value)) values.append(str(self._loainha.value)) values.append(str(self._mucdichsudung.value)) values.append(str(self._giatien.value)) if var3.isdigit(): fsqc.append(int(var3[0:(len(var3))])) else: fsqc.append(int(var3[0:(len(var3) - 1)])) heap_sort() self._refresh() #event tab 3 #search : def __search(self): if self._list.rows_count <= 1: messagebox.showwarning("Warning", "Danh sách rỗng") elif not self._timkiem.value: messagebox.showwarning("Warning", "Vui lòng nhập nội dung tìm kiếm") elif self._checklisttimkiem.selected_row_index == -1: messagebox.showwarning("Warning", "Vui lòng chọn tiêu chí cần xóa") self._checklisttimkiem.show() self._buttonhideshowtimkiem.icon = 'img/hide_icon.png' self._buttonhideshowtimkiem.label = 'Ẩn tiêu chí' else: self._refresh() s = 1 while s < self._list.rows_count: if not (str(self._timkiem.value).strip()) in str( self._list.get_value( self._checklisttimkiem.selected_row_index, s)): self._list.__sub__(s) s = s - 1 s = s + 1 def _huybo(self): self._refresh() def _buthideshowtimkiem(self): if not values_name: tk.messagebox.showwarning("Warning", "Không có list để chọn tiêu chí") elif str(self._buttonhideshowtimkiem.label) == 'Ẩn tiêu chí': self._checklisttimkiem.hide() self._buttonhideshowtimkiem.icon = 'img/show.png' self._buttonhideshowtimkiem.label = 'Hiển thị tiêu chí' elif str(self._buttonhideshowtimkiem.label) == 'Hiển thị tiêu chí': self._checklisttimkiem.show() self._buttonhideshowtimkiem.icon = 'img/hide_icon.png' self._buttonhideshowtimkiem.label = 'Ẩn tiêu chí' #delete def __xoa(self): if self._list.rows_count <= 1: messagebox.showwarning("Warning", "Danh sách rỗng") elif not self._textxoa.value: messagebox.showwarning("Warning", "Vui lòng nhập nội dung cần xóa") elif self._checklistxoa.selected_row_index == -1: messagebox.showwarning("Warning", "Vui lòng chọn tiêu chí cần xóa") self._checklistxoa.show() self._buttonhideshowxoa.icon = 'img/hide_icon.png' self._buttonhideshowxoa.label = 'Ẩn tiêu chí' else: result = messagebox.askokcancel('Warning', 'Bạn có chắc muốn xóa?') startvaluescount = len(values) if result == 1: s = 1 while s < len(values): if (str(self._textxoa.value).strip()) in str( values[s + self._checklistxoa.selected_row_index - 1]): del fsqc[s // 7] del values[(s - 1):(s + 6)] s = s - 7 s = s + 7 self._refresh() if startvaluescount > len(values): messagebox.showinfo("Sucess!!", "Đã xóa dữ liệu thành công") self._checklistxoa.hide() self._buttonhideshowxoa.icon = 'img/show.png' self._buttonhideshowxoa.label = 'Hiển thị tiêu chí' else: messagebox.showinfo( "Opps", "Nội dung cần xóa không có trong cột tiêu chí trong danh sách" ) def _buthideshowxoa(self): if not values_name: tk.messagebox.showwarning("Warning", "Không có list để chọn tiêu chí") elif str(self._buttonhideshowxoa.label) == 'Ẩn tiêu chí': self._checklistxoa.hide() self._buttonhideshowxoa.icon = 'img/show.png' self._buttonhideshowxoa.label = 'Hiển thị tiêu chí' elif str(self._buttonhideshowxoa.label) == 'Hiển thị tiêu chí': self._checklistxoa.show() self._buttonhideshowxoa.icon = 'img/hide_icon.png' self._buttonhideshowxoa.label = 'Ẩn tiêu chí' #event tab 4 #event _butxuat def __xuat(self): # kiểm tra đường dẫn if not os.path.isdir(self._directory.value): messagebox.showwarning("Warning", "đường dẫn ko có") elif not self._tenfilexuat.value: messagebox.showwarning("Warning", "tên file rỗng") elif not values and not values_name: messagebox.showwarning("Warning", "không có dữ liệu để xuất") else: try: os.makedirs(self._tenfilexuat.value) os.rmdir(self._tenfilexuat.value) if os.path.isfile(self._directory.value + '/' + self._tenfilexuat.value + '.xls'): result = messagebox.askokcancel( 'Warning', 'File đã tồn tại bạn có muốn ghi đè lên ?') if result == 1: write(self._directory.value, self._tenfilexuat.value) myfile = Path(self._directory.value + '/' + self._tenfilexuat.value + '.xls') if myfile.is_file(): messagebox.showinfo("Sucess!!", "Đã xuất file thành công") else: result = messagebox.askokcancel('Warning', 'Bạn có chắc muốn xuất?') if result == 1: write(self._directory.value, self._tenfilexuat.value) myfile = Path(self._directory.value + '/' + self._tenfilexuat.value + '.xls') if myfile.is_file(): messagebox.showinfo("Sucess!!", "Đã xuất file thành công") except OSError: messagebox.showwarning( "Warning", "Tên file không hợp lệ hoặc đang được mở bởi ứng dụng khác" ) #event tab 5 #event _butmerge def _merge(self): if self._list.rows_count < 1: messagebox.showwarning("Warning", "Danh sách rỗng") else: result = messagebox.askokcancel('Warning', 'Bạn có chắc muốn gộp?') if result == 1: for i in range(1, len(valuesimport), 7): n = False for s in range(1, len(values), 7): if valuesimport[i] == values[s]: f = self._checklist.checked_indexes for c in range(0, len(f), 1): values[s + int(f[c]) - 1] = valuesimport[i + int(f[c]) - 1] n = True if not n: fsqc.append(fsqcimport[int(i / 7)]) for s in range(i - 1, i + 6): values.append(valuesimport[s]) self._refresh() for i in range(0, self._listmerge.rows_count): self._listmerge.__sub__(i) for j in range(0, self._listmerge.rows_count): self._listmerge.__sub__(j) self._clearimportdata() self._checklist.hide() self._buttonhideshow.icon = 'img/show.png' self._buttonhideshow.label = 'Hiển thị tùy chọn' self._buttonremovemerge.hide() self._butmerge.hide() self._buttonhideshow.hide() tk.messagebox.showinfo("Success", "Đã merge thành công") #event _buttonremovemerge def _remove(self): if self._listmerge.rows_count < 1: tk.messagebox.showwarning("Warning", "Đã xóa hết!") else: for i in range(0, self._listmerge.rows_count): self._listmerge.__sub__(i) for j in range(0, self._listmerge.rows_count): self._listmerge.__sub__(j) self._clearimportdata() self._checklist.clear() self._buttonremovemerge.hide() self._buttonhideshow.hide() self._checklist.hide() self._butmerge.hide() #event _buttonhideshow def _buthideshow(self): if str(self._buttonhideshow.label) == 'Ẩn tùy chọn': self._checklist.hide() self._buttonhideshow.icon = 'img/show.png' self._buttonhideshow.label = 'Hiển thị tùy chọn' elif str(self._buttonhideshow.label) == 'Hiển thị tùy chọn': self._checklist.show() self._buttonhideshow.icon = 'img/hide_icon.png' self._buttonhideshow.label = 'Ẩn tùy chọn' #event _buttonimport def _import(self): if not self._filemerge.value: tk.messagebox.showwarning("Warning", "Đường dẫn trống") else: path = self._filemerge.value try: importexcel(path) self._listmerge.value = [values_nameimport] n = 0 for i in range(int(len(valuesimport) / numberofcolsimport[0])): self._listmerge.__add__( valuesimport[n:n + numberofcolsimport[0]]) n = n + numberofcolsimport[0] if self._checklist.count < 1: for s in range(0, len(values_nameimport)): self._checklist.__add__((values_nameimport[s], True)) if self._listmerge and not self._buttonhideshow.visible: if str(self._buttonhideshow.label) == 'Ẩn tùy chọn': self._buttonhideshow.icon = 'img/show.png' self._buttonhideshow.label = 'Hiển thị tùy chọn' self._buttonhideshow.show() self._buttonremovemerge.show() self._butmerge.show() except: tk.messagebox.showwarning( "Warning", "Không thể đọc file khác excel hoặc đường dẫn không đúng") #reusable function def _refresh(self): for i in range(1, self._list.rows_count): self._list.__sub__(i) for j in range(1, self._list.rows_count): self._list.__sub__(j) n = 0 for i in range(int(len(values) / numberofcols[0])): self._list.__add__(values[n:n + numberofcols[0]]) n = n + numberofcols[0] # update STT for s in range(1, self._list.rows_count): values[(s - 1) * 7] = s self._list.set_value(0, s, s) def _clearimportdata(self): fsqcimport.clear() valuesimport.clear() sqcimport.clear() numberofcolsimport.clear() values_nameimport.clear() self._checklist.clear()