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 __init__(self, master=None): self._kspelement = None Treeview.__init__(self, master) self.pack(expand=1, fill='both') self['columns'] = self._columns self['show'] = 'headings' [self.heading(column, text=column) for column in self['columns']] self.bind('<Double-1>', self._callback)
def __init__(self, master, names): self.widget = Frame(master) self._tree = Treeview(self.widget, columns='name') self._tree.grid(row=0,column=0, sticky=(N,S,W,E)) self._tree.view = self self.widget.columnconfigure(0, weight=1) self.widget.rowconfigure(0,weight=1) self._tree.column('name', width=50) self._tree['show'] = 'tree' actions = {'edit': lambda e: self.edit(), 'search': lambda e: self.search(), 'focus_next': lambda e: self.focus_next(), 'focus_prev': lambda e: self.focus_prev(), 'select': lambda e: self._tree.selection_toggle(self._tree.focus()), 'clear_selection': lambda e: self._tree.selection_set([]) } kb.make_bindings(kb.tagview, actions, self._tree.bind) self._iids = dict() self._names = dict() logger.debug('Names: %s', names) self.widget.focus_set = self._tree.focus_set for name in sorted(names): iid = self._tree.insert('', 'end', text=name) self._names[iid] = name self._iids[name] = iid self._scroll = Scrollbar(self.widget, command=self._tree.yview) self._tree['yscrollcommand'] = self._scroll.set self._scroll.grid(row=0, column=1, sticky=(N, S)) self.widget.columnconfigure(1, weight=0)
def __init__(self, master, **args): super().__init__(master) # Parse Treeview options for the Treeview opts = {x:args[x] for x in args if x in tree_options} # Create child controls self._vscroll = Scrollbar(self) self._hscroll = Scrollbar(self, orient=HORIZONTAL) opts['yscrollcommand'] = self._vscroll.set opts['xscrollcommand'] = self._hscroll.set self._tree = Treeview(self, **opts) # Setup the child controls self._init_controls() # Link some of the treeview's controls to this control self.item = self._tree.item self.tag_bind = self._tree.tag_bind self.tag_bind = self._tree.tag_configure self.insert = self._tree.insert self.delete = self._tree.delete self.detach = self._tree.detach self.heading = self._tree.heading # If a header argument was passed in, then use it self.set_headers(args.get('headers'))
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 __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 __init__(self,data,y,v='план'): w=Toplevel() w.wm_title('Доп') w.columnconfigure(0,weight=1) w.rowconfigure(0,weight=1) years=sorted(data.keys()) cols=data['2013']['degurs'] # ЗАГЛУШКА : список дежурных self.t=Treeview(w,columns=cols) for c in cols: self.t.heading(c,text=c) self.t.column(c,width=65,anchor='center') self.t.tag_configure('табель',background='green') self.t.tag_configure('ош',background='red') #self.t.tag_configure('табель',background='green') self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview) self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview) self.t['xscrollcommand']=self.scrX.set self.t['yscrollcommand']=self.scrY.set self.t.grid(row=0,column=0,sticky=N+S+E+W) self.scrX.grid(row=1,column=0,sticky=E+W) self.scrY.grid(row=0,column=1,sticky=N+S) for y in years: x=self.t.insert('','end',text=y) eeY=[] for m in ['01','02','03','04','05','06','07','08','09','10','11','12']: d0=data[y] if m not in d0: continue d=d0[m] rez=dict() tag='' if v=='авто': if 'табель' in d['degur']: vv='табель' tag=vv else: vv='план' elif v=='табель': if 'табель' not in d['degur']: vv='план' tag='ош' else: vv=v tag=vv else: vv=v for j,s in d['degur'][vv].items(): rez[j]=analyse2(s,d) NUL=(0,0,0,0,0,0,0) ee=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3]+rez.get(j,NUL)[4] for j in cols] eeY.append(ee) self.t.insert(x,'end',text=m,values=[x or '-' for x in ee],tag=tag) eeY=[sum(x) for x in zip(*eeY)] self.t.insert(x,'end',text='итого',values=eeY,tag='Y')
def __init__(self, controller): Treeview.__init__(self, controller) self.controller = controller self.recentFile = controller.recentFile self.browseInitialDir = controller.browseInitialDir self.maxRecentVideos = controller.maxRecentVideos self.initLastFile() self['height'] = 10 self['selectmode'] = 'browse' self['columns'] = ('lastOpen') self.column('#0', width=350, anchor='center') self.heading('#0', text='File') self.column('lastOpen', width=100, anchor='center') self.heading('lastOpen', text='Last play') self.bind("<Double-1>", self.playSelectedVideo) self.bind("<ButtonRelease-1>", self.selectVideo)
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 _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 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 CreateUI(self, classInstance): self.headers = [ "Customers", "Inter-arrival time", "Arrival time", "Service time", "Waiting time in queue", "Time when service begins", "Time when service ends", "Time customer spends in system", "Idle time of server" ] self.contents =[] # populates the table from other class to generate the tkinter table def compilelist(classInstance): self.contents.append(classInstance.intarrival()) self.contents.append(classInstance.arrival()) self.contents.append(classInstance.service()) self.contents.append(classInstance.queuewait()) self.contents.append(classInstance.servbegin()) self.contents.append(classInstance.servend()) self.contents.append(classInstance.custspend()) self.contents.append(classInstance.idle()) return self.contents # Calling the function compilelist(classInstance) self.rearrange = [] for row in zip(*self.contents): self.rearrange.append(row) self.headdata = [] for x in range(len(self.contents[0])): self.headdata.append(x+1) header_lists = [] tv = Treeview(self) tv['columns'] = (self.headers) for x in range(len(self.headers)): tv.heading("#%s"%x, text=self.headers[x], anchor='center') tv.column ("#%s"%x, anchor='center', width="150") tv.grid(sticky = (N,S,W,E)) self.treeview = tv self.grid_rowconfigure(0, weight = 1) self.grid_columnconfigure(0, weight = 1)
class DeviceToFrame(CopilotInnerFrame): def __init__(self, master, config, state): super(DeviceToFrame, self).__init__(master, config) self._state = state if self._state.action == 'copy': self._frame_lbl['text'] = 'Copy To Directory' elif self._state.action == 'delete': self._frame_lbl['text'] = 'Delete From Directory' self._next_btn['command'] = self._next_cmd self._tree = Treeview(self._master, columns=('size')) self._tree.heading('size', text='Size') self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew') self._tree.configure(yscrollcommand=self._sb.set) self._sb['command'] = self._tree.yview self._item_paths = {} self._populate_tree(self._state.to_device.part().mount()) def _next_cmd(self): cur_item = self._tree.focus() cur_path = self._item_paths.get(cur_item, '') if cur_path != '': self._state.device_to_path = cur_path self._new_state_window(CopyFileFrame, self._state) def _populate_tree(self, tree_root): self._item_paths = {} def insert_path(tree, path, parent_id): dirs = [e for e in scandir(path) if e.is_dir()] dirs.sort(key=lambda e: e.name) for d in dirs: dir_name = d.name dir_id = '{}-{}'.format(parent_id, dir_name) dir_path = os.path.join(path, dir_name) tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir')) self._item_paths[dir_id] = dir_path try: insert_path(tree, dir_path, dir_id) except: pass insert_path(self._tree, tree_root, '') tree = self._tree tree.tag_configure('dir', font=self._config.item_font) tree.tag_configure('file', font=self._config.item_font) tree.tag_configure('file_odd', background='light grey')
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)
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 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 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)
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 __init__(self, master, config, state): super(DeviceToFrame, self).__init__(master, config) self._state = state if self._state.action == 'copy': self._frame_lbl['text'] = 'Copy To Directory' elif self._state.action == 'delete': self._frame_lbl['text'] = 'Delete From Directory' self._next_btn['command'] = self._next_cmd self._tree = Treeview(self._master, columns=('size')) self._tree.heading('size', text='Size') self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew') self._tree.configure(yscrollcommand=self._sb.set) self._sb['command'] = self._tree.yview self._item_paths = {} self._populate_tree(self._state.to_device.part().mount())
def start(self): """Starts (opens) the commander window""" self.mainWin.geometry("800x600") txtText = Label(self.mainWin, textvariable=self.text) txtText.grid(row=0, column=0, sticky=W) txtInput = Entry(self.mainWin, textvariable=self.command, width=30) txtInput.grid(row=0, column=1, sticky=E + W) txtInput.bind("<Return>", self.doCommand) txtInput.bind("<Up>", self.recallCommand) button = Button(self.mainWin, text="Refresh", fg="blue", command=self.triggerFetchProbes) button.grid(row=1, column=0, sticky=N + S + E + W) txtStatus = Label(self.mainWin, textvariable=self.status, wraplength=600, justify=CENTER) txtStatus.grid(row=1, column=1, sticky=N + S + E + W) self.probesDisplay = Treeview(self.mainWin, columns=self.TREE_COLUMNS, show="headings") self.probesDisplay.grid(row=2, columnspan=2, sticky=N + S + E + W) for i in range(0, len(self.TREE_COLUMNS)): self.updateHeading(i, nProbes=0) self.result = Text(self.mainWin, textvariable=self.result, height=self.RESULT_DIPLAY_HEIGHT, wrap=WORD) self.result.configure(state=DISABLED) self.result.grid(row=3, columnspan=2, sticky=N + S + E + W) self.addResult("Awaiting results .... ") self.mainWin.grid_rowconfigure(2, weight=1) self.mainWin.grid_columnconfigure(1, weight=1) self.probeFetcherScheduler() self.thProbe.start() self.resultFetcherScheduler() self.thResults.start() self.logger.info("Commander : Starting main window") self.mainWin.mainloop() self.logger.debug("Commander : mainloop over")
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 __init__(self,root,data,SCRY=None): self.data=data self.columns=[x for x in range(1,8)]+['day'] root.rowconfigure(1,weight=1) root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1) root.columnconfigure(2,weight=1) f=Frame(root) f.columnconfigure(0,weight=1) f.rowconfigure(1,weight=1) self.v=Combobox(root) self.v.grid(row=0,column=0) self.v.bind('<<ComboboxSelected>>',self.select_ver) f.grid(row=1,column=0,columnspan=3,sticky=N+S) self.tree=Treeview(f, columns=self.columns, displaycolumns=['day']+self.columns[:-1], show='headings') #self.tree.tag_configure('odd',background='white') #self.tree.tag_configure('even',background='gray') self.tree.tag_configure('dif',foreground='brown') self.tree.tag_configure('work',background='white') self.tree.tag_configure('short',background='#F5EFE0') self.tree.tag_configure('rest',background='#E0B0B0') self.tree.tag_configure('holyday',background='#E7B7A4') for c in self.columns: self.tree.heading(c,text=c) self.tree.column(c,width=65,anchor='center') self.tree.column('day',width=30) scrX=Scrollbar(f,orient='horizontal',command=self.tree.xview) self.tree['xscrollcommand']=scrX.set if not SCRY: self.scrY=Scrollbar(f,orient='vertical',command=self.yview) self.tree['yscrollcommand']=self.scrY.set else: self.tree['yscrollcommand']=SCRY.set self.tree.grid(row=1,column=0,sticky=N+S) if not SCRY: self.scrY.grid(row=1,column=1,sticky=N+S) scrX.grid(row=2,column=0,sticky=E+W)
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)
def OnDoubleClick(self, tree, resturants, event): item = tree.identify('item', event.x, event.y) resturant_name = tree.item(item, "text") resturant_id = -1 for res in resturants: if (res[1] == resturant_name): resturant_id = res[0] # print (resturant_id) foods = mydb.showFoodsOfShop(resturant_id) self.menu_screen = Tk() self.menu_screen.title(resturant_name + " Menu") if (len(foods) != 0): Label(self.menu_screen, text="Resturant Menu", bg="red", width="300", height="2", font=("Calibri", 13)).pack() Label(text="").pack() tree = Treeview(self.menu_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four", "five") #set tree columns tree.column("#0", width=150, minwidth=150, stretch=tk.NO) tree.column("one", width=400, minwidth=200) tree.column("two", width=80, minwidth=50, stretch=tk.YES) tree.column("three", width=80, minwidth=50, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) tree.column("five", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Name", anchor=tk.W) tree.heading("one", text="Price", anchor=tk.W) tree.heading("two", text="About", anchor=tk.W) tree.heading("three", text="Category", anchor=tk.W) tree.heading("four", text="Image", anchor=tk.W) tree.heading("five", text="Discount", anchor=tk.W) tree.pack() for i in range(len(foods)): tree.insert("", i + 1, text=foods[i][3], values=(foods[i][1], foods[i][2], mydb.showCategoryName(foods[i][6])[0][0], foods[i][5], foods[i][4])) tree.bind("<Double-1>", partial(self.OnDoubleClickOnFood, tree, foods)) ###################################### ###################################### ###################################### #LAST FOOD FORM THIS RESTURANT ###################################### ###################################### ###################################### last_foods = mydb.showOrderByShop(self.user_id, resturant_id) last_foods = list(dict.fromkeys(last_foods)) # print (last_foods) Label(self.menu_screen, text="Last orders from this resturant", bg="red", width="300", height="2", font=("Calibri", 13)).pack() Label(text="").pack() tree = Treeview(self.menu_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four", "five") #set tree columns tree.column("#0", width=150, minwidth=150, stretch=tk.NO) tree.column("one", width=400, minwidth=200) tree.column("two", width=80, minwidth=50, stretch=tk.YES) tree.column("three", width=80, minwidth=50, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) tree.column("five", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Name", anchor=tk.W) tree.heading("one", text="Price", anchor=tk.W) tree.heading("two", text="About", anchor=tk.W) tree.heading("three", text="Category", anchor=tk.W) tree.heading("four", text="Image", anchor=tk.W) tree.heading("five", text="Discount", anchor=tk.W) tree.pack() for i in range(len(last_foods)): tree.insert("", i + 1, text=last_foods[i][3], values=(last_foods[i][1], last_foods[i][2], mydb.showCategoryName(last_foods[i][6])[0][0], last_foods[i][5], last_foods[i][4])) tree.bind("<Double-1>", partial(self.OnDoubleClickOnFood, tree, last_foods))
def showRestaurantsBySearch(self, city_combo, shop_name_entry, min_bill_entry): city_id = -1 if (city_combo.get() == "None"): city_id = None else: city_id = mydb.addCity(city_combo.get()) min_bill = min_bill_entry.get() if (min_bill_entry.get() == ""): min_bill = None shop_name = shop_name_entry.get() if (shop_name_entry.get() == ""): shop_name = None resturants = mydb.searchShop(city_id, shop_name, min_bill) # print (resturants) self.searched_resturant_screen = Tk() self.searched_resturant_screen.title("Results") tree = Treeview(self.searched_resturant_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four") #set tree columns tree.column("#0", width=270, minwidth=270, stretch=tk.NO) tree.column("one", width=150, minwidth=150, stretch=tk.NO) tree.column("two", width=400, minwidth=200) tree.column("three", width=80, minwidth=50, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Name", anchor=tk.W) tree.heading("one", text="About", anchor=tk.W) tree.heading("two", text="min bill value", anchor=tk.W) tree.heading("three", text="address", anchor=tk.W) tree.heading("four", text="Rate", anchor=tk.W) list_of_resturant_in_treeview = [] for i in range(len(resturants)): rate = mydb.calculateRate(resturants[i][0]) resturant_in_treeview = tree.insert( "", i + 1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], self.make_address_str(resturants[i][4]), "--" if rate[0][0] == None else rate[0][0])) list_of_resturant_in_treeview.append(resturant_in_treeview) # for resturant in list_of_resturant_in_treeview: # index = list_of_resturant_in_treeview.index(resturant) # shop_id = resturants[index][0] # shop_foods = mydb.showFoodsOfShop(shop_id) tree.pack(side=tk.TOP, fill=tk.X) tree.bind("<Double-1>", partial(self.OnDoubleClick, tree, resturants))
def showFoods(self, cat_cambo, price_l_entry, price_h_entry, food_name_entry, discount_entry): self.search_food_screen = Tk() self.search_food_screen.title("Foods") price_l = price_l_entry.get() if (price_l_entry.get() == ""): price_l = None price_h = price_h_entry.get() if (price_h_entry.get() == ""): price_h = None food_name = food_name_entry.get() if (food_name_entry.get() == ""): food_name = None discount = discount_entry.get() if (discount_entry.get() == ""): discount = None cat_id = -1 if (cat_cambo.get() == "None"): cat_id = None else: cat_id = cat_cambo.get()[0] print(price_l) print(price_h) print(food_name) print(discount) print(cat_id) foods = mydb.searchFood(price_l, price_h, food_name, discount, cat_id) if (len(foods) != 0): Label(self.search_food_screen, text="Result for your search", bg="red", width="300", height="2", font=("Calibri", 13)).pack() Label(text="").pack() tree = Treeview(self.search_food_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four", "five", "six") #set tree columns tree.column("#0", width=150, minwidth=150, stretch=tk.NO) tree.column("one", width=400, minwidth=200) tree.column("two", width=80, minwidth=50, stretch=tk.YES) tree.column("three", width=80, minwidth=50, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) tree.column("five", width=80, minwidth=50, stretch=tk.YES) tree.column("six", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Name", anchor=tk.W) tree.heading("one", text="Price", anchor=tk.W) tree.heading("two", text="About", anchor=tk.W) tree.heading("three", text="Category", anchor=tk.W) tree.heading("four", text="Image", anchor=tk.W) tree.heading("five", text="Discount", anchor=tk.W) tree.heading("six", text="Resturant", anchor=tk.W) tree.pack() for i in range(len(foods)): tree.insert("", i + 1, text=foods[i][1], values=(foods[i][2], foods[i][3], foods[i][5], 0, foods[i][4], foods[i][6])) tree.bind("<Double-1>", partial(self.OnDoubleClickOnFood, tree, foods))
def createChat(self, nom, enable=True): """Créer un nouveau chat pour un joueur donné. Arguments: nom - Le nom du joueur avec lequel l'utilisateur pourra parler avec ce chat Keyword Arguments: enable -- Est-ce que le chat doit être activer par défaut. (default: {True}) """ frame = tk.Frame(self.notebook) self.notebook.add(frame, text=nom) chat = Treeview(frame, height=15) chat['columns'] = ('Date') chat.heading("#0", text='Messages', anchor=tk.W) chat.heading('Date', text='Date', anchor=tk.W) chat.column('Date', anchor=tk.W, width=150) chat.grid(row=0, column=0, columnspan=2, rowspan=3, sticky=tk.NSEW) chat.tag_configure('even', background='#DAE5F4') chat.tag_configure('odd', background='#B8D1F3') chat.tag_configure('from_me', font=("Helvetica", 10, "bold")) chat.tag_configure('not_from_me', font=("Helvetica", 10)) messageEntry = tk.Entry(frame) messageEntry.grid(row=4, column=0, sticky=tk.S) messageButton = tk.Button(frame) messageButton["text"] = "Envoyer" if not enable: messageButton["state"] = tk.DISABLED messageButton["bg"] = "#1296EC" messageButton["activebackground"] = "#33A5EF" messageButton["fg"] = "#FFFFFF" messageButton["activeforeground"] = "#FFFFFF" messageButton["relief"] = tk.FLAT messageButton["bd"] = 0 messageButton["command"] = lambda: self.sendMessage(nom, messageEntry) messageButton.grid(row=4, column=1, sticky=tk.S) self.chats[nom] = [frame, chat, messageEntry, messageButton, 0]
def add_table(self): self.l1=Label(self.window,text="**Sales Details**",font="Courier 25 bold",bg="black",fg="white",width=61) self.l1.place(x=82,y=20) self.l1 = Label(self.window, text="Developed by : Muhammad Talha | NTU", font="Courier 10 bold") self.l1.place(x=470, y=610) self.l1 = Label(self.window, text="Enter Product Name:", font="courier 16 bold",bg="blue",fg="white") self.l1.place(x=280, y=90) self.Entry_reg = Entry(self.window, font="courior 14 bold") self.Entry_reg.place(x=550, y=90, height=30) self.b1 = Button(self.window, text="Search", font="Times 13 bold",fg="white",bg="blue",width=10) self.b1.place(x=790, y=90) self.b1.bind('<Button-1>', self.search_product) # for Style Table style = Style() style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('courier 12 bold'),rowheight=43) # Modify the font of the body style.configure("mystyle.Treeview.Heading", font=('Times 15 bold'),foreground="black") # Modify the font of the headings # style.layout("mystyle.Treeview", [('mystyle.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders # import TreeViewe self.tr=Treeview(self.window,columns=('A','B','C','D','E'),selectmode="extended",style='mystyle.Treeview') # heading key+text self.tr.heading("#0", text="Sr.No") self.tr.column("#0", minwidth=0, width=85, stretch=NO) self.tr.heading("#1",text="Product Name") self.tr.column("#1",minwidth=0,width=160,stretch=NO) self.tr.heading("#2", text="Product Catagory") self.tr.column("#2", minwidth=0, width=200, stretch=NO) self.tr.heading("#3", text="Quantity") self.tr.column("#3", minwidth=0, width=175, stretch=NO) self.tr.heading("#4", text="Price Per Product") self.tr.column("#4", minwidth=0, width=175, stretch=NO) self.tr.heading("#5", text="Sales Price") self.tr.column("#5", minwidth=0, width=160, stretch=NO) j=1 for i in Database.show_sales_details(): self.tr.insert('',index=j,text=j,values=(i[1],i[2],i[3],i[4],i[5])) j+=1 self.Entry_reg.bind('<KeyRelease>', self.remove) self.sb = Scrollbar(self.tr) self.sb.place(x=935,y=2,height=452,width=22,bordermode=OUTSIDE) self.sb.config(command=self.tr.yview) self.tr.config(yscrollcommand=self.sb.set) self.tr.place(x=170,y=150) # to excel file self.b1 = Button(self.window, text="Save to Excel", font="Times 12 bold",bg="blue",fg="white",width=20, ) self.b1.place(x=938, y=610) self.b1.bind('<Button-1>', self.excel) self.window.mainloop()
te.pack(pady=5) la1 = Label(root, text="Select the theme") la1.pack(pady=5) combo = Combobox(root, values=sorted(style.theme_names()), state='readonly') combo.set(style.theme_use()) combo.bind('<<ComboboxSelected>>', lambda _e: theme_changed(combo.get())) combo.pack(pady=5) out = theme_changed(style.theme_use()) te['width'] = out[0] te['height'] = out[1] dataCols = ('Name', 'hash') treeData = (('alice blue', '#F0F8FF'), ('azure', '#F0FFFF'), ('brown4', '#8B2323')) w = Treeview(root, columns=dataCols, show='headings') for col in dataCols: w.heading(col, text=col.title()) w.column(col, width=75) for ix, item in enumerate(treeData): w.insert('', 'end', values=item) w.pack(padx=5, pady=5) w2 = Treeview(root, columns=dataCols, show='headings', style='Custom.Treeview') #.Heading') for col in dataCols: w2.heading(col, text=col.title()) w2.column(col, width=75) for ix, item in enumerate(treeData): w2.insert('', 'end', values=item) w2.pack(padx=5, pady=5)
def showAllOrders(): self.all_orders_screen = Tk() self.all_orders_screen.title("All Orders") all_history = mydb.showAllHistory(self.user_id) print(all_history) Label(self.all_orders_screen, text="All your orders", bg="yellow", width="300", height="2", font=("Calibri", 13)).pack() Label(text="").pack() tree = Treeview(self.all_orders_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four") #set tree columns tree.column("#0", width=270, minwidth=270, stretch=tk.NO) tree.column("one", width=150, minwidth=150, stretch=tk.NO) tree.column("two", width=400, minwidth=200) tree.column("three", width=80, minwidth=50, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Order#", anchor=tk.W) tree.heading("one", text="Total Price", anchor=tk.W) tree.heading("two", text="Address", anchor=tk.W) tree.heading("three", text="Status", anchor=tk.W) tree.heading("four", text="Foods", anchor=tk.W) invoic_dict = {} print(all_history) for history in all_history: if ((history[0], history[1], history[2], history[4]) in invoic_dict.keys()): invoic_dict[(history[0], history[1], history[2], history[4])].append(history[3]) else: invoic_dict[(history[0], history[1], history[2], history[4])] = [] invoic_dict[(history[0], history[1], history[2], history[4])].append(history[3]) # print (type(list(invoic_dict.keys()))) print(invoic_dict) tree.pack(side=tk.TOP, fill=tk.X) orders_list = [] for key in invoic_dict.keys(): orders_list.append(key[0]) for i in range(len(list(invoic_dict.keys()))): address_id = list(invoic_dict.keys())[i][2] foods_list = invoic_dict[list(invoic_dict.keys())[i]] print(foods_list) tree.insert("", i + 1, text="Order#" + str(i + 1), values=(list(invoic_dict.keys())[i][1], self.make_address_str(address_id), list(invoic_dict.keys())[i][3], self.make_foods_str(foods_list)))
def show_dic_command(self): if self.dictionary_in_main_memory == False: messagebox.showwarning( "Error", "first, load dictionary to your main memory.\ndon't look at me like this! just do it with the Load Dictionary button\nif you have some time, you can also start the program and after it will be finished, you will be able to show dictionary" ) else: text_of_waiting = Label( self.bottomFrame, text= "Please Wait.. the dictionary will be shown in 10-20 seconds") text_of_waiting.grid(row=0, column=1) self.window.update() self.dictionaryWindow = Toplevel(self.window) self.dictionaryWindow.geometry("400x600") self.dictionaryWindow.title("Main Dictionary") self.dictionaryWindow.resizable(False, False) tree = Treeview(self.dictionaryWindow, selectmode="extended", columns=("term", "tf")) style = ttk.Style() style.configure("Treeview.Heading", background='lavender') tree.pack(expand=YES, fill=BOTH) tree['show'] = 'headings' tree.column("#0", minwidth=10, width=20, stretch=NO) tree.heading("term", text="Term") tree.column("term", minwidth=250, width=200, stretch=NO) tree.heading("tf", text="Frequency in corpus") tree.column("tf", minwidth=180, width=180, stretch=NO) scrollbar = ttk.Scrollbar(self.dictionaryWindow, orient="vertical", command=tree.yview) scrollbar.place(x=380, y=0, height=600) tree.configure(yscrollcommand=scrollbar.set) main_dictionary_pointer = Controller.getMainDictionaryFromIndexerToGUI( ) sorted_main_dictionary = dict( sorted(main_dictionary_pointer.items())) odd = 'odd' even = 'even' i = 0 for key in sorted_main_dictionary: term = key tf = str(sorted_main_dictionary[key].tf_in_corpus) if i % 2 == 0: tag = odd else: tag = even tree.insert('', 'end', values=(term, tf), tags=(tag, )) i = i + 1 tree.tag_configure(odd, background='gold') tree.tag_configure(even, background='deep sky blue') tree.pack() text_of_waiting.grid_remove()
def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False): if isinstance(parent, Cntlr): cntlr = parent parent = parent.parent # parent is cntlrWinMain else: # parent is a Toplevel dialog cntlr = parent.cntlr super(DialogOpenArchive, self).__init__(parent) self.parent = parent self.showAltViewButton = showAltViewButton parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) frame = Frame(self) treeFrame = Frame(frame, width=500) vScrollbar = Scrollbar(treeFrame, orient=VERTICAL) hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL) self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set) self.treeView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.treeView.xview hScrollbar.grid(row=1, column=0, sticky=(E, W)) vScrollbar["command"] = self.treeView.yview vScrollbar.grid(row=0, column=1, sticky=(N, S)) treeFrame.columnconfigure(0, weight=1) treeFrame.rowconfigure(0, weight=1) treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.treeView.focus_set() if openType not in (PLUGIN, PACKAGE): cntlr.showStatus(_("loading archive {0}").format(filesource.url)) self.filesource = filesource self.filenames = filenames self.selection = filesource.selection self.hasToolTip = False selectedNode = None if openType == ENTRY_POINTS: try: metadataFiles = filesource.taxonomyPackageMetadataFiles ''' take first for now if len(metadataFiles) != 1: raise IOError(_("Taxonomy package contained more than one metadata file: {0}.") .format(', '.join(metadataFiles))) ''' metadataFile = metadataFiles[0] metadata = filesource.url + os.sep + metadataFile self.metadataFilePrefix = os.sep.join( os.path.split(metadataFile)[:-1]) if self.metadataFilePrefix: self.metadataFilePrefix += "/" # zip contents have /, never \ file seps self.taxonomyPkgMetaInf = '{}/META-INF/'.format( os.path.splitext(os.path.basename(filesource.url))[0]) self.taxonomyPackage = parsePackage( cntlr, filesource, metadata, os.sep.join(os.path.split(metadata)[:-1]) + os.sep) if self.taxonomyPackage["entryPoints"]: # may have instance documents too self.packageContainedInstances = [] packageContentTypeCounts = {} for suffix in (".xhtml", ".htm", ".html"): for potentialInstance in filesource.dir: if potentialInstance.endswith(".xhtml"): _type = "Inline Instance" self.packageContainedInstances.append( [potentialInstance, _type]) packageContentTypeCounts[ potentialInstance] = packageContentTypeCounts.get( potentialInstance, 0) + 1 if self.packageContainedInstances: break if self.packageContainedInstances: # add sequences to any duplicated entry types for _type, count in packageContentTypeCounts.items(): if count > 1: _dupNo = 0 for i in range( len(self.packageContainedInstances)): if self.packageContainedInstances[i][ 0] == _type: _dupNo += 1 self.packageContainedInstances[i][ 0] = "{} {}".format(_type, _dupNo) else: # may be a catalog file with no entry oint names openType = ARCHIVE # no entry points to show, just archive self.showAltViewButton = False except Exception as e: self.close() err = _( "Failed to parse metadata; the underlying error was: {0}" ).format(e) messagebox.showerror(_("Malformed taxonomy package"), err) cntlr.addToLog(err) return if openType not in (PLUGIN, PACKAGE): cntlr.showStatus(None) if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE): y = 3 else: y = 1 okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3) cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3) if self.showAltViewButton: self.altViewButton = Button(frame, command=self.showAltView) self.altViewButton.grid(row=y, column=0, sticky=(S, W), pady=3, padx=3) self.loadTreeView(openType, colHeader, title) self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100)) frame.grid(row=0, column=0, sticky=(N, S, E, W)) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.toolTipText = StringVar() if self.hasToolTip: self.treeView.bind("<Motion>", self.motion, '+') self.treeView.bind("<Leave>", self.leave, '+') self.toolTipText = StringVar() self.toolTip = ToolTip(self.treeView, textvariable=self.toolTipText, wraplength=640, follow_mouse=True, state="disabled") self.toolTipRowId = None self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
def lang_command(self): if self.finished_program == False and self.loaded_index == False: messagebox.showwarning( "Error", "first, start indexing your corpus or load index files. then you'll be able to see the languages" ) else: self.lang_window = Toplevel(self.window) self.lang_window.geometry("200x400") self.lang_window.title("Languages List") self.lang_window.resizable(False, False) tree = Treeview(self.lang_window, selectmode="extended", columns=("lang")) tree.pack(expand=YES, fill=BOTH) tree['show'] = 'headings' tree.heading("lang", text="Language") tree.column("lang", minwidth=180, width=180, stretch=NO) scrollbar = ttk.Scrollbar(self.lang_window, orient="vertical", command=tree.yview) scrollbar.place(x=180, y=0, height=400) tree.configure(yscrollcommand=scrollbar.set) odd = 'odd' even = 'even' list_of_langs = Controller.getLangList() sorted_list_of_langs = sorted(list_of_langs) i = 0 for x in sorted_list_of_langs: if i % 2 == 0: tag = odd else: tag = even tree.insert('', 'end', values=(x), tags=(tag, )) i = i + 1 tree.tag_configure(odd, background='hot pink') tree.tag_configure(even, background='deep pink')
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='Users in Group: ', font='Arial 15 bold',fg='white', bg='#454b54') self.close_btn = Button(self.canvas, text="Close", font='Arial 15 bold', bg='#454b54', fg="#f7cc35", command=quit) self.add_btn = Button(self.canvas, text = "Add User to Group", font='Arial 15 bold', bg='#454b54', fg="#f7cc35") 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) db.cursor.execute("SELECT id FROM projects WHERE viewing = 'ON'") groupID = db.cursor.fetchone()[0] db.cursor.execute("SELECT A.username,email,reputation_score,user_type FROM users A\ JOIN group_membership B on A.username = B.username where B.group_id =%s",(groupID,)) for row in db.cursor.fetchall(): self.list.insert('', END, values=row) self.close_btn.place(x = 300, y = 354) self.add_btn.place(x = 380, y = 354) self.win.mainloop()
class GUIExample(master.Subscriber): def __init__(self): #jumbonet stuff self.net = master.Master() self.net.mainloop() self.output = {} # uuid -> list of lines of output self.processes = {} # uuid/iid -> remote object #the fugly tkinter stuff self.tk = Tk() self.input = StringVar() self.selection = (None, False, False ) #process/remote, is_process, is_remote self.tv = None # treeview self.dsp_global = None self.dsp_process = None def _setup(self): tk = self.tk tk.wm_title("Jumbonet GUI Example") tk.protocol("WM_DELETE_WINDOW", self.shutdown) height = 250 # center: treeview self.tv = Treeview(tk) tv = self.tv tv.config(height=height) # treeview configuration tv["columns"] = ("process", "status") tv.column("process", width=130) tv.column("status", width=70) tv.heading("process", text="Process UUID") tv.heading("status", text="Status") tv.bind("<ButtonRelease-1>", self.row_selected) # right: log windows r_frame = Frame(tk, height=height) scroll = Scrollbar(r_frame) #the global log (top) self.dsp_global = TextDisplay(r_frame, width=70, height=20) self.dsp_global.append("Global information") #the process log (bottom) self.dsp_process = TextDisplay(r_frame, width=70, height=25) self.dsp_process.append("This shows output of the selected process") #left: entry and buttons self.input.set("") l_frame = Frame(tk, width=200, height=height) l = Label(l_frame, text="Start process here") e = Entry(l_frame, textvariable=self.input) buttons = Frame(l_frame) # buttons button_add = Button(buttons, text="Start", command=self.start_process) button_kill = Button(buttons, text="Kill", command=self.kill_process) # packing all of it # frame on left l.pack(side=TOP, fill=X) e.pack(side=TOP, fill=X) button_add.pack(side=LEFT) button_kill.pack(side=LEFT) buttons.pack(side=TOP, fill=X) # applog frame on right scroll.pack(side=RIGHT, fill=Y) self.dsp_global.pack(side=TOP, fill=X) self.dsp_process.pack(side=TOP, fill=X) # top-level pack l_frame.pack(side=LEFT, fill=Y, expand=False) tv.pack(side=LEFT, fill=Y, expand=False) r_frame.pack(side=LEFT, fill=Y, expand=False) def shutdown(self): self.net.shutdown() sys.exit(0) def row_selected(self, a): iid = self.tv.focus() log.debug("Selected: {}".format(iid)) assert (iid is not None) # is it a remote? r = self.net.remotes.get(iid) if r is not None: self.selection = (r, False, True) return # is it a process? #the process we're already showing output from? if self.selection[1] and iid == self.selection[0].uuid: #nothing to do then return # is it another process? p = self.processes[iid] if p is not None: # clear the log and display whats happening on the selected process self.dsp_process.clear() lines = self.output.get(iid) self.dsp_process.append(lines) self.selection = (p, True, False) else: self.selection = (None, False, False) def start_process(self): log.debug("Selected: {}".format(self.selection)) if not self.selection[2]: return cmd = self.input.get() if cmd == "type shell command here ": self.dsp_global.append("\nPlease type a valid shell command") return cmdargs = cmd.split(" ") r = self.selection[0] p = r.popen(cmdargs, self, listen_output=True, listen_error=True, listen_status=True) self.output[p.uuid] = list() self.processes[p.uuid] = p self.tv.insert(parent=self.selection[0].name, index="end", iid=p.uuid, text=cmd, values=(p.uuid, "Running")) self.dsp_global.append("\nStart {} as {} to {}".format( cmd, p.uuid, self.selection)) def kill_process(self): if not self.selection[1]: return p = self.selection[0] if not p.alive: self.dsp_global.append("\nCannot kill {} has alread exited".format( p.uuid)) else: self.dsp_global.append("\nKilling {}".format(self.selection)) p.kill() def _update_process_display(self, remotename, uuid, args, lines): old_output = self.output.get(uuid) old_output.extend(lines) if not self.selection[1]: return # are we showing the same process already? then add them to the log if uuid == self.selection[0].uuid: self.dsp_process.append(lines) self.dsp_process.see(END) def receive_out(self, remotename, uuid, args, lines): self._update_process_display(remotename, uuid, args, lines) def receive_err(self, remotename, uuid, args, lines): self._update_process_display(remotename, uuid, args, lines) def receive_status(self, remotename, uuid, args, exitcode): self.dsp_global.append("\nExit {} aka {} with code".format( args, uuid, exitcode)) self.tv.item(uuid, values=(uuid, "Exited ".format(exitcode))) #### these could also be used to get a nicer output for debugging complex testcases def add_host(self, remote): self.tv.insert("", END, text=remote.name, iid=remote.name, values=[], open=True) def add_process(self, remote, process): self.processes[process.uuid] = remote self.tv.insert(remote.name, END, iid=process.uuid, text=" ".join(process.args), values=(process.uuid, "Running"))
def showRestaurants(self, all_variables, all_address): address_id = -1 for variable in all_variables: if (variable.get()): index = all_variables.index(variable) address_id = all_address[index][1] self.address_id = address_id resturants = mydb.searchShopByLocation(int(address_id), 100) # print (resturants) self.searched_resturant_screen = Tk() self.searched_resturant_screen.title("Results") tree = Treeview(self.searched_resturant_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three", "four") #set tree columns tree.column("#0", width=270, minwidth=270, stretch=tk.NO) tree.column("one", width=150, minwidth=150, stretch=tk.NO) tree.column("two", width=400, minwidth=200) tree.column("three", width=400, minwidth=200, stretch=tk.YES) tree.column("four", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Name", anchor=tk.W) tree.heading("one", text="About", anchor=tk.W) tree.heading("two", text="min bill value", anchor=tk.W) tree.heading("three", text="address", anchor=tk.W) tree.heading("four", text="rate", anchor=tk.W) list_of_resturant_in_treeview = [] for i in range(len(resturants)): rate = mydb.calculateRate(resturants[i][0])[0][0] resturant_in_treeview = tree.insert( "", i + 1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], self.make_address_str(resturants[i][4]), "-" if rate == None else rate)) list_of_resturant_in_treeview.append(resturant_in_treeview) tree.pack(side=tk.TOP, fill=tk.X) tree.bind("<Double-1>", partial(self.OnDoubleClick, tree, resturants))
def __init__(self, title: str = "Universal File Dialog", icon: str = "", show_hidden: bool = False, include_files: bool = True, multiselect: bool = True, select_dirs: bool = True, select_files: bool = True, unix_delimiter: bool = True, stdout: bool = False): """ Init kwargs as object attributes, save references to Tk PhotoImages, & define the widgets + layout """ if not isinstance(title, str): raise TypeError("Argument title must be type string.") self.title = title if icon: if not isinstance(icon, str): raise TypeError("Argument icon must be type string.") if not isfile(icon): raise FileNotFoundError(f"File not found: {icon}") self.icon = icon else: self.icon = "" if show_hidden: self.show_hidden = True else: self.show_hidden = False if include_files: self.include_files = True else: self.include_files = False if multiselect: self.multiselect = True else: self.multiselect = False if select_dirs: self.select_dirs = True else: self.select_dirs = False if select_files: self.select_files = True else: self.select_files = False if unix_delimiter: self.unix_delimiter = True else: self.unix_delimiter = False if stdout: self.stdout = True else: self.stdout = False # Tkinter: self.dialog = Tk() self.dialog.withdraw() self.dialog.title(self.title) self.dialog.minsize(width=300, height=200) self.dialog.geometry("500x300") self.dialog.update_idletasks() self.file_icon = PhotoImage(file=f"{dirname(__file__)}/file.gif", master=self.dialog).subsample(50) self.folder_icon = PhotoImage(file=f"{dirname(__file__)}/folder.gif", master=self.dialog).subsample(15) self.disk_icon = PhotoImage(file=f"{dirname(__file__)}/disk.gif", master=self.dialog).subsample(15) if self.icon: self.dialog.iconbitmap(self.icon) else: self.dialog.iconbitmap(f"{dirname(__file__)}/icon.ico") # Widgets: self.paneview = PanedWindow( self.dialog, sashwidth=7, bg="#cccccc", bd=0, ) self.left_pane = PanedWindow(self.paneview) self.right_pane = PanedWindow(self.paneview) self.paneview.add(self.left_pane) self.paneview.add(self.right_pane) self.treeview_x_scrollbar = Scrollbar(self.left_pane, orient="horizontal") self.treeview_y_scrollbar = Scrollbar(self.left_pane, orient="vertical") self.list_box_x_scrollbar = Scrollbar(self.right_pane, orient="horizontal") self.list_box_y_scrollbar = Scrollbar(self.right_pane, orient="vertical") # tstyle = Style().configure(".", ) self.treeview = Treeview( self.left_pane, xscrollcommand=self.treeview_x_scrollbar.set, yscrollcommand=self.treeview_y_scrollbar.set, show="tree", selectmode="browse", # style=tstyle ) self.list_box = Listbox(self.right_pane, xscrollcommand=self.list_box_x_scrollbar.set, yscrollcommand=self.list_box_y_scrollbar.set, width=34, highlightthickness=0, bd=2, relief="ridge") if self.multiselect: self.list_box.config(selectmode="extended") else: self.list_box.config(selectmode="browse") self.cancel_button = Button(self.left_pane, text="Cancel", command=self.cancel) self.submit_button = Button(self.right_pane, text="Submit", command=self.submit) self.treeview_x_scrollbar.config(command=self.treeview.xview) self.treeview_y_scrollbar.config(command=self.treeview.yview) self.list_box_x_scrollbar.config(command=self.list_box.xview) self.list_box_y_scrollbar.config(command=self.list_box.yview) #Layout: self.dialog.rowconfigure(0, weight=1) self.dialog.columnconfigure(0, weight=1) self.left_pane.grid_rowconfigure(0, weight=1) self.left_pane.grid_columnconfigure(0, weight=1) self.right_pane.grid_rowconfigure(0, weight=1) self.right_pane.grid_columnconfigure(0, weight=1) self.paneview.paneconfigure( self.left_pane, minsize=100, #Start off w/ the sash centered in the GUI: width=(self.dialog.winfo_width() / 2) - ceil( (self.paneview.cget("sashwidth") * 1.5)), ) self.paneview.paneconfigure(self.right_pane, minsize=100) self.paneview.grid(row=0, column=0, sticky="nsew") self.treeview.grid(row=0, column=0, sticky="nsew") self.treeview_y_scrollbar.grid(row=0, column=1, sticky="ns") self.treeview_x_scrollbar.grid(row=1, column=0, columnspan=2, sticky="ew") self.list_box.grid(row=0, column=0, sticky="nsew") self.list_box_y_scrollbar.grid(row=0, column=1, sticky="ns") self.list_box_x_scrollbar.grid(row=1, column=0, columnspan=2, sticky="ew") self.cancel_button.grid(row=2, column=0, sticky="w", padx=10, pady=10) self.submit_button.grid(row=2, column=0, columnspan=2, sticky="e", padx=10, pady=10) #Bindings, Protocols, & Misc: self.dialog.bind("<Control-w>", self.cancel) self.treeview.bind("<<TreeviewSelect>>", self.treeview_select) self.treeview.bind("<Double-Button-1>", self.dialog_populate) self.treeview.bind("<Return>", self.dialog_populate) self.treeview.bind("<Right>", self.dialog_populate) self.list_box.bind("<<ListboxSelect>>", self.list_box_select) self.list_box.bind("<Return>", self.submit) self.dialog.protocol("WM_DELETE_WINDOW", self.cancel) self.dialog_selection = deque() self.selection_paths = deque() for disk in self.get_disks(): self.treeview.insert( "", index="end", text=disk, image=self.disk_icon, ) self.dialog.focus()
def showHistoryOfOrders(): self.history_of_orders_screen = Tk() self.history_of_orders_screen.title("Hisotry of orders") Label(self.history_of_orders_screen, text="History of orders, click on them to comment", bg="yellow", width="300", height="2", font=("Calibri", 13)).pack() Label(text="").pack() tree = Treeview(self.history_of_orders_screen, style="mystyle.Treeview") tree["columns"] = ("one", "two", "three") #set tree columns tree.column("#0", width=270, minwidth=270, stretch=tk.NO) tree.column("one", width=150, minwidth=150, stretch=tk.NO) tree.column("two", width=400, minwidth=200) tree.column("three", width=80, minwidth=50, stretch=tk.YES) #set tree's heading tree.heading("#0", text="Order#", anchor=tk.W) tree.heading("one", text="Total Price", anchor=tk.W) tree.heading("two", text="Address", anchor=tk.W) tree.heading("three", text="Foods", anchor=tk.W) history_of_orders = mydb.showBuyHistory(self.user_id) invoic_dict = {} for history in history_of_orders: if ((history[0], history[1], history[2]) in invoic_dict.keys()): invoic_dict[(history[0], history[1], history[2])].append(history[3]) else: invoic_dict[(history[0], history[1], history[2])] = [] invoic_dict[(history[0], history[1], history[2])].append(history[3]) # print (type(list(invoic_dict.keys()))) # print (invoic_dict) tree.pack(side=tk.TOP, fill=tk.X) orders_list = [] for key in invoic_dict.keys(): orders_list.append(key[0]) for i in range(len(list(invoic_dict.keys()))): address_id = list(invoic_dict.keys())[i][2] foods_list = invoic_dict[list(invoic_dict.keys())[i]] print(foods_list) tree.insert("", i + 1, text="Order#" + str(i + 1), values=(list(invoic_dict.keys())[i][1], self.make_address_str(address_id), self.make_foods_str(foods_list))) # resturant_in_treeview = tree.insert("", i+1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], make_address_str(resturants[i][4]))) # list_of_resturant_in_treeview.append(resturant_in_treeview) tree.bind("<Double-1>", partial(OnDoubleClickOnOrder, tree, orders_list))
def open_records(self): top = Toplevel() top.title('记录') top.maxsize(600, 600) Label(top, text='欢迎使用人脸识别系统', width=35, height=2, bg='#56764C').grid(row=0, columnspan=2, sticky=W + E) columns = ('所选目标', '出现时间', '消失时间', '持续时间') tree = Treeview(top, show='headings', columns=columns) tree.column('所选目标', width=150, anchor='center') tree.column('出现时间', width=150, anchor='center') tree.column('消失时间', width=150, anchor='center') tree.column('持续时间', width=150, anchor='center') tree.heading('所选目标', text='所选目标') tree.heading('出现时间', text='出现时间') tree.heading('消失时间', text='消失时间') tree.heading('持续时间', text='持续时间') sql = "select * from records where aid = '%s'" % user.id ret = sql_conn(sql) for i in range(len(ret)): tree.insert('', i, values=(ret[i]['object_name'], ret[i]['appear'], ret[i]['disappear'], ret[i]['last_time'])) tree.grid(row=1, column=0, sticky=NSEW) scrollbar = Scrollbar(top) scrollbar.grid(row=1, column=1, sticky=NS) scrollbar.config(command=tree.yview)
size=12, weight='bold').measure(' ') codeInputTextBox = Text(topFrame, width=60, borderwidth=1, relief="solid", tabs=codeInputTextBoxTabSettings, font=("System")) codeInputTextBox.insert( END, "HAI" + "\n" + "\tVISIBLE \"HELLO WORLD\"" + "\n" "KTHXBYE" + "\n") codeInputTextBox.pack(side=LEFT) lexemeTableCols = ('Lexeme', 'Classification') lexemeTableTreeview = Treeview(topFrame, columns=lexemeTableCols, show='headings') for col in lexemeTableCols: lexemeTableTreeview.heading(col, text=col) lexemeTableTreeview.pack(side=LEFT, fill=Y) symbolTableCols = ('Identifier', 'Value') symbolTableTreeview = Treeview(topFrame, columns=symbolTableCols, show='headings') for col in symbolTableCols: symbolTableTreeview.heading(col, text=col) symbolTableTreeview.pack(side=LEFT, fill=Y) # Need to set state to normal if you want to change the contents executeButton = Button(bottomFrame, text="Execute", command=execute)
class DialogPluginManager(Toplevel): def __init__(self, mainWin, modulesWithNewerFileDates): super(DialogPluginManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.pluginConfig = PluginManager.pluginConfig self.pluginConfigChanged = False self.uiClassMethodsChanged = False self.modelClassesChanged = False self.disclosureSystemTypesChanged = False self.modulesWithNewerFileDates = modulesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Plug-in Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240) addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3) # right tree frame (plugins already known to arelle) modulesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL) hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL) self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect) hScrollbar["command"] = self.modulesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.modulesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) modulesFrame.columnconfigure(0, weight=1) modulesFrame.rowconfigure(0, weight=1) modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.modulesView.focus_set() self.modulesView.column("#0", width=120, anchor="w") self.modulesView.heading("#0", text=_("Name")) self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license") self.modulesView.column("author", width=100, anchor="w", stretch=False) self.modulesView.heading("author", text=_("Author")) self.modulesView.column("ver", width=50, anchor="w", stretch=False) self.modulesView.heading("ver", text=_("Version")) self.modulesView.column("status", width=50, anchor="w", stretch=False) self.modulesView.heading("status", text=_("Status")) self.modulesView.column("date", width=70, anchor="w", stretch=False) self.modulesView.heading("date", text=_("File Date")) self.modulesView.column("update", width=50, anchor="w", stretch=False) self.modulesView.heading("update", text=_("Update")) self.modulesView.column("descr", width=200, anchor="w", stretch=False) self.modulesView.heading("descr", text=_("Description")) self.modulesView.column("license", width=70, anchor="w", stretch=False) self.modulesView.heading("license", text=_("License")) classesFrame = Frame(frame) vScrollbar = Scrollbar(classesFrame, orient=VERTICAL) hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL) self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.classesView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.classesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.classesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) classesFrame.columnconfigure(0, weight=1) classesFrame.rowconfigure(0, weight=1) classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.classesView.focus_set() self.classesView.column("#0", width=200, anchor="w") self.classesView.heading("#0", text=_("Class")) self.classesView["columns"] = ("modules",) self.classesView.column("modules", width=500, anchor="w", stretch=False) self.classesView.heading("modules", text=_("Modules")) # bottom frame module info details moduleInfoFrame = Frame(frame, width=700) moduleInfoFrame.columnconfigure(1, weight=1) self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W) self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED) self.moduleAuthorHdr.grid(row=1, column=0, sticky=W) self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W) self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED) self.moduleDescrHdr.grid(row=2, column=0, sticky=W) self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W) self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED) self.moduleClassesHdr.grid(row=3, column=0, sticky=W) self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W) ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240) self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED) self.moduleUrlHdr.grid(row=4, column=0, sticky=W) self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W) ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240) self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED) self.moduleDateHdr.grid(row=5, column=0, sticky=W) self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W) ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240) self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED) self.moduleLicenseHdr.grid(row=6, column=0, sticky=W) self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W) self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable) ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240) self.moduleEnableButton.grid(row=7, column=1, sticky=E) self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload) ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240) self.moduleReloadButton.grid(row=7, column=2, sticky=E) self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove) ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240) self.moduleRemoveButton.grid(row=7, column=3, sticky=E) moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) moduleInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) enableDisableFrame = Frame(frame) enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3) enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll) ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240) disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll) ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240) enableAllButton.grid(row=1, column=1) disableAllButton.grid(row=1, column=2) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self) def loadTreeViews(self): self.selectedModule = None # clear previous treeview entries for previousNode in self.modulesView.get_children(""): self.modulesView.delete(previousNode) for i, moduleItem in enumerate(sorted(self.pluginConfig.get("modules", {}).items())): moduleInfo = moduleItem[1] name = moduleInfo.get("name", moduleItem[0]) node = self.modulesView.insert("", "end", name, text=name) self.modulesView.set(node, "author", moduleInfo.get("author")) self.modulesView.set(node, "ver", moduleInfo.get("version")) self.modulesView.set(node, "status", moduleInfo.get("status")) self.modulesView.set(node, "date", moduleInfo.get("fileDate")) if name in self.modulesWithNewerFileDates: self.modulesView.set(node, "update", _("available")) self.modulesView.set(node, "descr", moduleInfo.get("description")) self.modulesView.set(node, "license", moduleInfo.get("license")) # clear previous treeview entries for previousNode in self.classesView.get_children(""): self.classesView.delete(previousNode) for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())): className, moduleList = classItem node = self.classesView.insert("", "end", className, text=className) self.classesView.set(node, "modules", ', '.join(moduleList)) self.moduleSelect() # clear out prior selection def ok(self, event=None): if self.pluginConfigChanged: PluginManager.pluginConfig = self.pluginConfig PluginManager.pluginConfigChanged = True PluginManager.reset() # force reloading of modules if self.uiClassMethodsChanged or self.modelClassesChanged or self.disclosureSystemTypesChanged: # may require reloading UI affectedItems = "" if self.uiClassMethodsChanged: affectedItems += _("menus of the user interface") if self.modelClassesChanged: if self.uiClassMethodsChanged: affectedItems += _(" and ") affectedItems += _("model objects of the processor") if (self.uiClassMethodsChanged or self.modelClassesChanged): affectedItems += _(" and ") if self.disclosureSystemTypesChanged: if (self.uiClassMethodsChanged or self.modelClassesChanged): affectedItems += _(" and ") affectedItems += _("disclosure system types") if messagebox.askyesno(_("User interface plug-in change"), _("A change in plug-in class methods may have affected {0}. " "Please restart Arelle to due to these changes. \n\n" "Should Arelle restart itself now " "(if there are any unsaved changes they would be lost!)?" ).format(affectedItems), parent=self): self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True])) self.close() def close(self, event=None): self.parent.focus_set() self.destroy() def moduleSelect(self, *args): node = (self.modulesView.selection() or (None,))[0] moduleInfo = self.pluginConfig.get("modules", {}).get(node) if moduleInfo: self.selectedModule = node name = moduleInfo["name"] self.moduleNameLabel.config(text=name) self.moduleAuthorHdr.config(state=ACTIVE) self.moduleAuthorLabel.config(text=moduleInfo["author"]) self.moduleDescrHdr.config(state=ACTIVE) self.moduleDescrLabel.config(text=moduleInfo["description"]) self.moduleClassesHdr.config(state=ACTIVE) self.moduleClassesLabel.config(text=', '.join(moduleInfo["classMethods"])) self.moduleUrlHdr.config(state=ACTIVE) self.moduleUrlLabel.config(text=moduleInfo["moduleURL"]) self.moduleDateHdr.config(state=ACTIVE) self.moduleDateLabel.config(text=moduleInfo["fileDate"] + " " + (_("(an update is available)") if name in self.modulesWithNewerFileDates else "")) self.moduleLicenseHdr.config(state=ACTIVE) self.moduleLicenseLabel.config(text=moduleInfo["license"]) self.moduleEnableButton.config(state=ACTIVE, text={"enabled":self.DISABLE, "disabled":self.ENABLE}[moduleInfo["status"]]) self.moduleReloadButton.config(state=ACTIVE) self.moduleRemoveButton.config(state=ACTIVE) else: self.selectedModule = None self.moduleNameLabel.config(text="") self.moduleAuthorHdr.config(state=DISABLED) self.moduleAuthorLabel.config(text="") self.moduleDescrHdr.config(state=DISABLED) self.moduleDescrLabel.config(text="") self.moduleClassesHdr.config(state=DISABLED) self.moduleClassesLabel.config(text="") self.moduleUrlHdr.config(state=DISABLED) self.moduleUrlLabel.config(text="") self.moduleDateHdr.config(state=DISABLED) self.moduleDateLabel.config(text="") self.moduleLicenseHdr.config(state=DISABLED) self.moduleLicenseLabel.config(text="") self.moduleEnableButton.config(state=DISABLED, text=self.ENABLE) self.moduleReloadButton.config(state=DISABLED) self.moduleRemoveButton.config(state=DISABLED) def findLocally(self): initialdir = self.cntlr.pluginDir # default plugin directory if not self.cntlr.isMac: # can't navigate within app easily, always start in default directory initialdir = self.cntlr.config.setdefault("pluginOpenDir", initialdir) filename = self.cntlr.uiFileDialog("open", parent=self, title=_("Choose plug-in module file"), initialdir=initialdir, filetypes=[(_("Python files"), "*.py")], defaultextension=".py") if filename: # check if a package is selected (any file in a directory containing an __init__.py if (os.path.isdir(os.path.dirname(filename)) and os.path.isfile(os.path.join(os.path.dirname(filename), "__init__.py"))): filename = os.path.dirname(filename) # refer to the package instead self.cntlr.config["pluginOpenDir"] = os.path.dirname(filename) moduleInfo = PluginManager.moduleModuleInfo(filename) self.loadFoundModuleInfo(moduleInfo, filename) def findOnWeb(self): url = DialogURL.askURL(self) if url: # url is the in-cache or local file moduleInfo = PluginManager.moduleModuleInfo(url) self.cntlr.showStatus("") # clear web loading status self.loadFoundModuleInfo(moduleInfo, url) def loadFoundModuleInfo(self, moduleInfo, url): if moduleInfo and moduleInfo.get("name"): self.addPluginConfigModuleInfo(moduleInfo) self.loadTreeViews() else: messagebox.showwarning(_("Module is not itself a plug-in or in a directory with package __init__.py plug-in. "), _("File does not itself contain a python program with an appropriate __pluginInfo__ declaration: \n\n{0}") .format(url), parent=self) def removePluginConfigModuleInfo(self, name): moduleInfo = self.pluginConfig["modules"].get(name) if moduleInfo: for classMethod in moduleInfo["classMethods"]: classMethods = self.pluginConfig["classes"].get(classMethod) if classMethods and name in classMethods: classMethods.remove(name) if not classMethods: # list has become unused del self.pluginConfig["classes"][classMethod] # remove class if classMethod.startswith("CntlrWinMain.Menu"): self.uiClassMethodsChanged = True # may require reloading UI elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses": self.modelClassesChanged = True # model object factor classes changed elif classMethod == "DisclosureSystem.Types": self.disclosureSystemTypesChanged = True # disclosure system types changed del self.pluginConfig["modules"][name] self.pluginConfigChanged = True def addPluginConfigModuleInfo(self, moduleInfo): name = moduleInfo["name"] self.removePluginConfigModuleInfo(name) # remove any prior entry for this module self.modulesWithNewerFileDates.discard(name) # no longer has an update available self.pluginConfig["modules"][name] = moduleInfo # add classes for classMethod in moduleInfo["classMethods"]: classMethods = self.pluginConfig["classes"].setdefault(classMethod, []) if name not in classMethods: classMethods.append(name) if classMethod.startswith("CntlrWinMain.Menu"): self.uiClassMethodsChanged = True # may require reloading UI elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses": self.modelClassesChanged = True # model object factor classes changed elif classMethod == "DisclosureSystem.Types": self.disclosureSystemTypesChanged = True # disclosure system types changed self.pluginConfigChanged = True def moduleEnable(self): if self.selectedModule in self.pluginConfig["modules"]: moduleInfo = self.pluginConfig["modules"][self.selectedModule] if self.moduleEnableButton['text'] == self.ENABLE: moduleInfo["status"] = "enabled" self.moduleEnableButton['text'] = self.DISABLE elif self.moduleEnableButton['text'] == self.DISABLE: moduleInfo["status"] = "disabled" self.moduleEnableButton['text'] = self.ENABLE self.pluginConfigChanged = True self.loadTreeViews() def moduleReload(self): if self.selectedModule in self.pluginConfig["modules"]: url = self.pluginConfig["modules"][self.selectedModule].get("moduleURL") if url: moduleInfo = PluginManager.moduleModuleInfo(url, reload=True) if moduleInfo: self.addPluginConfigModuleInfo(moduleInfo) self.loadTreeViews() self.cntlr.showStatus(_("{0} reloaded").format(moduleInfo.get("name")), clearAfter=5000) else: messagebox.showwarning(_("Module error"), _("File or module cannot be reloaded: \n\n{0}") .format(url), parent=self) def moduleRemove(self): if self.selectedModule in self.pluginConfig["modules"]: self.removePluginConfigModuleInfo(self.selectedModule) self.pluginConfigChanged = True self.loadTreeViews() def enableAll(self): self.enableDisableAll(True) def disableAll(self): self.enableDisableAll(False) def enableDisableAll(self, doEnable): for module in self.pluginConfig["modules"]: moduleInfo = self.pluginConfig["modules"][module] if doEnable: moduleInfo["status"] = "enabled" self.moduleEnableButton['text'] = self.DISABLE else: moduleInfo["status"] = "disabled" self.moduleEnableButton['text'] = self.ENABLE self.pluginConfigChanged = True self.loadTreeViews()
class show: def __init__(self): self.window=Tk() self.window.title("Show | Sales Products") self.window.iconbitmap('shop.ico') self.window.geometry("1365x670+0+0") self.window.maxsize(1365,670) self.window.minsize(1365,670) # self.window.resizable(width=False,height=False) def add_background(self): self.image = Image.open("images/back.jpg") self.image = self.image.resize((1365, 700), Image.ANTIALIAS) self.img = ImageTk.PhotoImage(self.image) self.li = Label(image = self.img, text="TALHA") self.li.image = self.img self.li.pack() self.Menubar() def Menubar(self): self.menubar = Menu() self.menuitems_add = Menu(self.menubar, tearoff=0,bg="blue",fg="white") self.menuitems_add.add_command(label="Add Products", command=self.add_products) # self.menuitems.add_separator() self.menuitems_sales = Menu(self.menubar, tearoff=0,bg="blue",fg="white") self.menuitems_sales.add_command(label="Sale Products", command=self.sales_products) self.menuitems_customer = Menu(self.menubar, tearoff=0, bg="blue", fg="white") self.menuitems_customer.add_command(label="Add Customer", command=self.add_customer) self.menuitems_customer.add_command(label="Show Customer Records", command=self.customer_record) self.menuitems_reports = Menu(self.menubar, tearoff=0, bg="blue", fg="white") self.menuitems_reports.add_command(label="Check Products Quantity", command=self.check_products_quantity) self.menuitems_reports.add_command(label="Check Profit/Loss", command=self.check_profit_loss) self.menuitems_reports.add_command(label="Check Sales Products", command=self.check_products_sales) self.menuitems_reports.add_command(label="Check Sent Amount Details", command=self.check_amount) self.menubar.add_cascade(label="Add Products", menu=self.menuitems_add) self.menubar.add_cascade(label="Sales Products", menu=self.menuitems_sales) self.menubar.add_cascade(label="Customer", menu=self.menuitems_customer) self.menubar.add_cascade(label="Reports", menu=self.menuitems_reports) self.menubar.add_cascade(label="Exit", command=quit) self.window.config(menu=self.menubar) def add_table(self): self.l1=Label(self.window,text="**Sales Details**",font="Courier 25 bold",bg="black",fg="white",width=61) self.l1.place(x=82,y=20) self.l1 = Label(self.window, text="Developed by : Muhammad Talha | NTU", font="Courier 10 bold") self.l1.place(x=470, y=610) self.l1 = Label(self.window, text="Enter Product Name:", font="courier 16 bold",bg="blue",fg="white") self.l1.place(x=280, y=90) self.Entry_reg = Entry(self.window, font="courior 14 bold") self.Entry_reg.place(x=550, y=90, height=30) self.b1 = Button(self.window, text="Search", font="Times 13 bold",fg="white",bg="blue",width=10) self.b1.place(x=790, y=90) self.b1.bind('<Button-1>', self.search_product) # for Style Table style = Style() style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('courier 12 bold'),rowheight=43) # Modify the font of the body style.configure("mystyle.Treeview.Heading", font=('Times 15 bold'),foreground="black") # Modify the font of the headings # style.layout("mystyle.Treeview", [('mystyle.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders # import TreeViewe self.tr=Treeview(self.window,columns=('A','B','C','D','E'),selectmode="extended",style='mystyle.Treeview') # heading key+text self.tr.heading("#0", text="Sr.No") self.tr.column("#0", minwidth=0, width=85, stretch=NO) self.tr.heading("#1",text="Product Name") self.tr.column("#1",minwidth=0,width=160,stretch=NO) self.tr.heading("#2", text="Product Catagory") self.tr.column("#2", minwidth=0, width=200, stretch=NO) self.tr.heading("#3", text="Quantity") self.tr.column("#3", minwidth=0, width=175, stretch=NO) self.tr.heading("#4", text="Price Per Product") self.tr.column("#4", minwidth=0, width=175, stretch=NO) self.tr.heading("#5", text="Sales Price") self.tr.column("#5", minwidth=0, width=160, stretch=NO) j=1 for i in Database.show_sales_details(): self.tr.insert('',index=j,text=j,values=(i[1],i[2],i[3],i[4],i[5])) j+=1 self.Entry_reg.bind('<KeyRelease>', self.remove) self.sb = Scrollbar(self.tr) self.sb.place(x=935,y=2,height=452,width=22,bordermode=OUTSIDE) self.sb.config(command=self.tr.yview) self.tr.config(yscrollcommand=self.sb.set) self.tr.place(x=170,y=150) # to excel file self.b1 = Button(self.window, text="Save to Excel", font="Times 12 bold",bg="blue",fg="white",width=20, ) self.b1.place(x=938, y=610) self.b1.bind('<Button-1>', self.excel) self.window.mainloop() def remove(self,event): for row in self.tr.get_children(): self.tr.delete(row) j = 1 for i in Database.show_sales_details(): self.tr.insert('', index=j, text=j, values=(i[1], i[2], i[3], i[4], i[5])) j += 1 def search_product(self,event): try: data = (self.Entry_reg.get(),) if self.Entry_reg.get() == "": msg.showwarning("Message ! ", "please insert product name !") else: j = 1 D = Database.search_details_sales_table(data) if D: for row in self.tr.get_children(): self.tr.delete(row) self.Entry_reg.delete(0, END) for i in D: self.tr.insert('', index=j, text=j, values=(i[1],i[2],i[3],i[4],i[5])) j += 1 else: msg.showwarning("Message!", "No result Found!") except: msg.showwarning("Error!", "Something went wrong! please contact with developer !!!") def excel(self,event): try: x=Database.show_sales_details() p_name=[] p_catagory=[] p_quantity=[] price=[] p_sales_price=[] for i in range(len(x)): z=x.__getitem__(i) p_name.append(z[1]) p_catagory.append(z[2]) p_quantity.append(z[3]) price.append(z[4]) p_sales_price.append(z[5]) products = pd.DataFrame({ "Product Name": p_name, "Product Catagory":p_catagory, "Quantity":p_quantity, "Price Per Product":price, "Sales Price":p_sales_price }) with pd.ExcelWriter("Excel Files/Sales_Products_Records.xlsx") as writer: products.to_excel(writer, sheet_name="Sales_Products", index=False) msg.showinfo("Message ! ", "Your data has been inserted Susccessfully !") except: msg.showwarning("Message!","Something Went Wrong!please contact with developer!!!") def add_products(self): self.window.destroy() home = Home.data() home.add_background() home.add_frame() def sales_products(self): self.window.destroy() showP = Showing_Records.show() showP.add_background() showP.add_table() def check_products_quantity(self): self.window.destroy() showP = Check_Products_Quantity.show() showP.add_background() showP.add_table() def check_products_sales(self): pass def check_amount(self): self.window.destroy() showP = Check_Amount_Details.show() showP.add_background() showP.add_table() def check_profit_loss(self): self.window.destroy() showP = Check_Profit_Loss_GUI.show() showP.add_background() showP.add_table() def add_customer(self): self.window.destroy() home = Add_Customer.data() home.add_background() home.add_frame() def customer_record(self): self.window.destroy() showP = Customer_Records.show() showP.add_background() showP.add_table()
def __init__(self, mainWin, modulesWithNewerFileDates): super(DialogPluginManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.pluginConfig = PluginManager.pluginConfig self.pluginConfigChanged = False self.uiClassMethodsChanged = False self.modelClassesChanged = False self.disclosureSystemTypesChanged = False self.modulesWithNewerFileDates = modulesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Plug-in Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240) addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3) # right tree frame (plugins already known to arelle) modulesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL) hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL) self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect) hScrollbar["command"] = self.modulesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.modulesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) modulesFrame.columnconfigure(0, weight=1) modulesFrame.rowconfigure(0, weight=1) modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.modulesView.focus_set() self.modulesView.column("#0", width=120, anchor="w") self.modulesView.heading("#0", text=_("Name")) self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license") self.modulesView.column("author", width=100, anchor="w", stretch=False) self.modulesView.heading("author", text=_("Author")) self.modulesView.column("ver", width=50, anchor="w", stretch=False) self.modulesView.heading("ver", text=_("Version")) self.modulesView.column("status", width=50, anchor="w", stretch=False) self.modulesView.heading("status", text=_("Status")) self.modulesView.column("date", width=70, anchor="w", stretch=False) self.modulesView.heading("date", text=_("File Date")) self.modulesView.column("update", width=50, anchor="w", stretch=False) self.modulesView.heading("update", text=_("Update")) self.modulesView.column("descr", width=200, anchor="w", stretch=False) self.modulesView.heading("descr", text=_("Description")) self.modulesView.column("license", width=70, anchor="w", stretch=False) self.modulesView.heading("license", text=_("License")) classesFrame = Frame(frame) vScrollbar = Scrollbar(classesFrame, orient=VERTICAL) hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL) self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.classesView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.classesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.classesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) classesFrame.columnconfigure(0, weight=1) classesFrame.rowconfigure(0, weight=1) classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.classesView.focus_set() self.classesView.column("#0", width=200, anchor="w") self.classesView.heading("#0", text=_("Class")) self.classesView["columns"] = ("modules",) self.classesView.column("modules", width=500, anchor="w", stretch=False) self.classesView.heading("modules", text=_("Modules")) # bottom frame module info details moduleInfoFrame = Frame(frame, width=700) moduleInfoFrame.columnconfigure(1, weight=1) self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W) self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED) self.moduleAuthorHdr.grid(row=1, column=0, sticky=W) self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W) self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED) self.moduleDescrHdr.grid(row=2, column=0, sticky=W) self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W) self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED) self.moduleClassesHdr.grid(row=3, column=0, sticky=W) self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W) ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240) self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED) self.moduleUrlHdr.grid(row=4, column=0, sticky=W) self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W) ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240) self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED) self.moduleDateHdr.grid(row=5, column=0, sticky=W) self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W) ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240) self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED) self.moduleLicenseHdr.grid(row=6, column=0, sticky=W) self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W) self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable) ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240) self.moduleEnableButton.grid(row=7, column=1, sticky=E) self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload) ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240) self.moduleReloadButton.grid(row=7, column=2, sticky=E) self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove) ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240) self.moduleRemoveButton.grid(row=7, column=3, sticky=E) moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) moduleInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) enableDisableFrame = Frame(frame) enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3) enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll) ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240) disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll) ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240) enableAllButton.grid(row=1, column=1) disableAllButton.grid(row=1, column=2) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
class DialogOpenArchive(Toplevel): def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False): if isinstance(parent, Cntlr): cntlr = parent parent = parent.parent # parent is cntlrWinMain else: # parent is a Toplevel dialog cntlr = parent.cntlr super(DialogOpenArchive, self).__init__(parent) self.parent = parent self.showAltViewButton = showAltViewButton parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.accepted = False self.transient(self.parent) frame = Frame(self) treeFrame = Frame(frame, width=500) vScrollbar = Scrollbar(treeFrame, orient=VERTICAL) hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL) self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set) self.treeView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.treeView.xview hScrollbar.grid(row=1, column=0, sticky=(E, W)) vScrollbar["command"] = self.treeView.yview vScrollbar.grid(row=0, column=1, sticky=(N, S)) treeFrame.columnconfigure(0, weight=1) treeFrame.rowconfigure(0, weight=1) treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.treeView.focus_set() if openType not in (PLUGIN, PACKAGE): cntlr.showStatus(_("loading archive {0}").format(filesource.url)) self.filesource = filesource self.filenames = filenames self.selection = filesource.selection self.hasToolTip = False selectedNode = None if openType == ENTRY_POINTS: try: metadataFiles = filesource.taxonomyPackageMetadataFiles ''' take first for now if len(metadataFiles) != 1: raise IOError(_("Taxonomy package contained more than one metadata file: {0}.") .format(', '.join(metadataFiles))) ''' metadataFile = metadataFiles[0] metadata = filesource.url + os.sep + metadataFile self.metadataFilePrefix = os.sep.join( os.path.split(metadataFile)[:-1]) if self.metadataFilePrefix: self.metadataFilePrefix += "/" # zip contents have /, never \ file seps self.taxonomyPkgMetaInf = '{}/META-INF/'.format( os.path.splitext(os.path.basename(filesource.url))[0]) self.taxonomyPackage = parsePackage( cntlr, filesource, metadata, os.sep.join(os.path.split(metadata)[:-1]) + os.sep) if self.taxonomyPackage["entryPoints"]: # may have instance documents too self.packageContainedInstances = [] packageContentTypeCounts = {} for suffix in (".xhtml", ".htm", ".html"): for potentialInstance in filesource.dir: if potentialInstance.endswith(".xhtml"): _type = "Inline Instance" self.packageContainedInstances.append( [potentialInstance, _type]) packageContentTypeCounts[ potentialInstance] = packageContentTypeCounts.get( potentialInstance, 0) + 1 if self.packageContainedInstances: break if self.packageContainedInstances: # add sequences to any duplicated entry types for _type, count in packageContentTypeCounts.items(): if count > 1: _dupNo = 0 for i in range( len(self.packageContainedInstances)): if self.packageContainedInstances[i][ 0] == _type: _dupNo += 1 self.packageContainedInstances[i][ 0] = "{} {}".format(_type, _dupNo) else: # may be a catalog file with no entry oint names openType = ARCHIVE # no entry points to show, just archive self.showAltViewButton = False except Exception as e: self.close() err = _( "Failed to parse metadata; the underlying error was: {0}" ).format(e) messagebox.showerror(_("Malformed taxonomy package"), err) cntlr.addToLog(err) return if openType not in (PLUGIN, PACKAGE): cntlr.showStatus(None) if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE): y = 3 else: y = 1 okButton = Button(frame, text=_("OK"), command=self.ok) cancelButton = Button(frame, text=_("Cancel"), command=self.close) okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3) cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3) if self.showAltViewButton: self.altViewButton = Button(frame, command=self.showAltView) self.altViewButton.grid(row=y, column=0, sticky=(S, W), pady=3, padx=3) self.loadTreeView(openType, colHeader, title) self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100)) frame.grid(row=0, column=0, sticky=(N, S, E, W)) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.toolTipText = StringVar() if self.hasToolTip: self.treeView.bind("<Motion>", self.motion, '+') self.treeView.bind("<Leave>", self.leave, '+') self.toolTipText = StringVar() self.toolTip = ToolTip(self.treeView, textvariable=self.toolTipText, wraplength=640, follow_mouse=True, state="disabled") self.toolTipRowId = None self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self) def loadTreeView(self, openType, title, colHeader): self.title(title) self.openType = openType selectedNode = None # clear previous treeview entries for previousNode in self.treeView.get_children(""): self.treeView.delete(previousNode) # set up treeView widget and tabbed pane if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE): if openType in (PLUGIN, PACKAGE): width = 770 else: width = 500 self.treeView.column("#0", width=width, anchor="w") self.treeView.heading("#0", text=colHeader) self.isRss = getattr(self.filesource, "isRss", False) if self.isRss: self.treeView.column("#0", width=350, anchor="w") self.treeView["columns"] = ("descr", "date", "instDoc") self.treeView.column("descr", width=50, anchor="center", stretch=False) self.treeView.heading("descr", text="Form") self.treeView.column("date", width=170, anchor="w", stretch=False) self.treeView.heading("date", text="Pub Date") self.treeView.column("instDoc", width=200, anchor="w", stretch=False) self.treeView.heading("instDoc", text="Instance Document") elif openType == PLUGIN: self.treeView.column("#0", width=150, anchor="w") self.treeView["columns"] = ("name", "vers", "descr", "license") self.treeView.column("name", width=150, anchor="w", stretch=False) self.treeView.heading("name", text="Name") self.treeView.column("vers", width=60, anchor="w", stretch=False) self.treeView.heading("vers", text="Version") self.treeView.column("descr", width=300, anchor="w", stretch=False) self.treeView.heading("descr", text="Description") self.treeView.column("license", width=60, anchor="w", stretch=False) self.treeView.heading("license", text="License") elif openType == PACKAGE: self.treeView.column("#0", width=200, anchor="w") self.treeView["columns"] = ("vers", "descr", "license") self.treeView.column("vers", width=100, anchor="w", stretch=False) self.treeView.heading("vers", text="Version") self.treeView.column("descr", width=400, anchor="w", stretch=False) self.treeView.heading("descr", text="Description") self.treeView.column("license", width=70, anchor="w", stretch=False) self.treeView.heading("license", text="License") else: self.treeView["columns"] = tuple() loadedPaths = [] for i, filename in enumerate(self.filenames): if isinstance(filename, tuple): if self.isRss: form, date, instDoc = filename[2:5] elif openType == PLUGIN: name, vers, descr, license = filename[3:7] elif openType == PACKAGE: vers, descr, license = filename[3:6] filename = filename[0] # ignore tooltip self.hasToolTip = True if filename.endswith("/"): filename = filename[:-1] path = filename.split("/") if not self.isRss and len( path) > 1 and path[:-1] in loadedPaths: parent = "file{0}".format(loadedPaths.index(path[:-1])) else: parent = "" node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1]) if self.isRss: self.treeView.set(node, "descr", form) self.treeView.set(node, "date", date) self.treeView.set(node, "instDoc", os.path.basename(instDoc)) elif openType == PLUGIN: self.treeView.set(node, "name", name) self.treeView.set(node, "vers", vers) self.treeView.set(node, "descr", descr) self.treeView.set(node, "license", license) elif openType == PACKAGE: self.treeView.set(node, "vers", vers) self.treeView.set(node, "descr", descr) self.treeView.set(node, "license", license) if self.selection == filename: selectedNode = node loadedPaths.append(path) elif openType == ENTRY_POINTS: self.treeView.column("#0", width=200, anchor="w") self.treeView.heading("#0", text="Name") self.treeView["columns"] = ("url", ) self.treeView.column("url", width=300, anchor="w") self.treeView.heading("url", text="URL") for fileType, fileUrl in getattr(self, "packageContainedInstances", ()): self.treeView.insert("", "end", fileUrl, values=fileType, text=fileUrl or urls[0][2]) for name, urls in sorted( self.taxonomyPackage["entryPoints"].items(), key=lambda i: i[0][2]): self.treeView.insert("", "end", name, values="\n".join(url[1] for url in urls), text=name or urls[0][2]) self.hasToolTip = True else: # unknown openType return None if selectedNode: self.treeView.see(selectedNode) self.treeView.selection_set(selectedNode) if self.showAltViewButton: self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries")) def ok(self, event=None): selection = self.treeView.selection() if len(selection) > 0: if hasattr(self, "taxonomyPackage"): # load file source remappings self.filesource.mappedPaths = self.taxonomyPackage[ "remappings"] filename = None if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM): filename = self.filenames[int(selection[0][4:])] if isinstance(filename, tuple): if self.isRss: filename = filename[4] else: filename = filename[0] elif self.openType == ENTRY_POINTS: epName = selection[0] #index 0 is the remapped Url, as opposed to the canonical one used for display # Greg Acsone reports [0] does not work for Corep 1.6 pkgs, need [1], old style packages filenames = [] for _url, _type in self.packageContainedInstances: # check if selection was an inline instance if _type == epName: filenames.append(_url) if not filenames: # else if it's a named taxonomy entry point for url in self.taxonomyPackage["entryPoints"][epName]: filename = url[0] if not filename.endswith("/"): # check if it's an absolute URL rather than a path into the archive if not isHttpUrl( filename ) and self.metadataFilePrefix != self.taxonomyPkgMetaInf: # assume it's a path inside the archive: filename = self.metadataFilePrefix + filename filenames.append(filename) if filenames: self.filesource.select(filenames) self.accepted = True self.close() return elif self.openType in (PLUGIN, PACKAGE): filename = self.filenames[int(selection[0][4:])][2] if filename is not None and not filename.endswith("/"): if hasattr(self, "taxonomyPackage"): # attempt to unmap the filename to original file # will be mapped again in loading, but this allows schemaLocation to be unmapped for prefix, remapping in self.taxonomyPackage[ "remappings"].items(): if isHttpUrl(remapping): remapStart = remapping else: remapStart = self.metadataFilePrefix + remapping if filename.startswith(remapStart): # set unmmapped file filename = prefix + filename[len(remapStart):] break if self.openType in (PLUGIN, PACKAGE): self.filesource.selection = filename else: self.filesource.select(filename) self.accepted = True self.close() def close(self, event=None): self.parent.focus_set() self.destroy() def showAltView(self, event=None): if self.openType == ENTRY_POINTS: self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File")) else: self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File")) def leave(self, *args): self.toolTipRowId = None def motion(self, *args): tvRowId = self.treeView.identify_row(args[0].y) if tvRowId != self.toolTipRowId: text = None if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE): self.toolTipRowId = tvRowId if tvRowId and len(tvRowId) > 4: try: text = self.filenames[int(tvRowId[4:])] if isinstance(text, tuple): text = (text[1] or "").replace("\\n", "\n") except (KeyError, ValueError): pass elif self.openType == ENTRY_POINTS: try: text = "{0}\n{1}".format( tvRowId, "\n".join( url[1] for url in self.taxonomyPackage["entryPoints"][tvRowId])) except KeyError: pass self.setToolTip(text) def setToolTip(self, text): self.toolTip._hide() if text: self.toolTipText.set(text) self.toolTip.configure(state="normal") self.toolTip._schedule() else: self.toolTipText.set("") self.toolTip.configure(state="disabled")
# headings and data tree_columns = ['Colours', 'Hash', 'RGB'] tree_data = (('red', '#FF0000', (255, 0, 0)), ('yellow', '#FFFF00', (255, 255, 0)), ('blue', '#0000FF', (0, 0, 255)), ('green', '#00FF00', (0, 255, 0)), ('magenta', '#FF00FF', (255, 0, 255)), ('cyan', '#00FFFF', (0, 255, 255))) fr0 = Frame(root) fr0.grid(column=0, row=0, sticky='nsew') # create Treeview widget tree = Treeview(fr0, column=tree_columns, show='headings') tree.grid(column=0, row=0, sticky='nsew') tree.bind("<ButtonRelease-1>", select_item) # insert header and data for col in tree_columns: tree.heading(col, text=col.title()) for item in tree_data: itemID = tree.insert('', 'end', values=item) # display selection lvar = StringVar() lbl = Label(fr0, textvariable=lvar, text="Ready") lbl.grid(column=0, row=1, sticky='nsew')
class StructEditor(tk.Frame, Subscriber, Observable): """Displays and allow editing of the coordinates and points of one superstructure Args: parent (tk.Frame): widget that is the parent of the editor structure (model.structure.Structure): the ship superstructure that will be edited """ def __init__(self, parent, structure, command_stack): Subscriber.__init__(self, structure) Observable.__init__(self) tk.Frame.__init__(self, parent, borderwidth=4, relief="raised") self._structure = structure self._command_stack = command_stack self.bind("<Button-1>", self._on_click) self.bind("<FocusIn>", self._on_get_focus) self.bind("<FocusOut>", self._on_lost_focus) self._tree = Treeview(self, columns=["#", "X", "Y"], selectmode="browse") #kill the icon column self._tree.column("#0", minwidth=0, width=0) style = Style() style.configure("Treeview.Heading", font=(None, 16)) self._tree.column("#", minwidth=20, width=40, anchor=tk.CENTER) self._tree.column("X", minwidth=20, width=40, anchor=tk.CENTER) self._tree.column("Y", minwidth=20, width=40, anchor=tk.CENTER) self._tree.heading("#", text="#") self._tree.heading("X", text="\u21d5") self._tree.heading("Y", text="\u21d4") self._tree.grid(row=0, column=POINTS_TABLE_COL, sticky=tk.N + tk.S) self._tree.bind("<<TreeviewSelect>>", self._on_point_selected) self._tree.bind("<FocusIn>", self._on_get_focus) self._tree.bind("<FocusOut>", self._on_lost_focus) scroll = Scrollbar(self, command=self._tree.yview) scroll.grid(row=0, column=SCROLL_COL, sticky=tk.N + tk.S) scroll.bind("<FocusIn>", self._on_get_focus) self._tree.configure(yscrollcommand=scroll.set) self._index_of_sel_point = -1 self._fill_tree() self._edit_zone = EditZone(self, self._structure, command_stack, self._on_get_focus) self._edit_zone.grid(column=EDIT_ZONE_COL, row=0, sticky=tk.N) def _set_selection(self, new_sel_index): """Set the selected point to the new_sel_index Gives correct focus, update, etc to the editor's widgets if the index is outside of the self.points, does nothing """ if new_sel_index >= 0 and new_sel_index <= len(self.points) - 1: iid = self._tree.get_children()[new_sel_index] self._tree.selection_set(iid) def _on_click(self, *_args): self._tree.focus_set() def _on_get_focus(self, *_args): if self._index_of_sel_point == -1: self._set_selection(0) self.configure(relief="sunken") self._notify("focus", {}) def _on_lost_focus(self, event): if event.widget not in self.winfo_children(): self.configure(relief="raised") def _on_point_selected(self, _event): """called back when a point is selected in the table/treeview Updates the editable fields """ selected_iid = self._tree.selection() self._index_of_sel_point = self._tree.index(selected_iid) self._edit_zone.set_editable_point( self._tree.item(selected_iid)["values"][0]) self._notify("focus", {}) def _fill_tree(self): """fills the treeview with data from the structure """ self._tree.delete(*self._tree.get_children()) for point_index, point in enumerate(self._structure.points): self._tree.insert( '', 'end', values=[point_index, round(point[0]), round(point[1])]) if point_index == self._index_of_sel_point: self._set_selection(point_index) def _on_notification(self, observable, event_type, event_info): """Rebuild the treeview on structure update Depending on the structure state and the operation, change the selcted point """ if event_type == "add_point": self._index_of_sel_point = event_info["index"] self._fill_tree() else: if self._index_of_sel_point >= len(self._structure.points): self._index_of_sel_point = len(self._structure.points) self._edit_zone.unset_point() self._fill_tree() self._notify("focus", {}) def update_to_coord(self, point): """Move the selected point to the position of the given point Intended to be called from click on the top view Args: point (x, y): new position in funnel coordinates """ if self._index_of_sel_point != -1 and self._index_of_sel_point <= len( self.points) - 1: self._command_stack.do( model.structure.UpdatePoint(self._structure, self._index_of_sel_point, round(point[0]), round(point[1]))) elif self._index_of_sel_point == len(self.points) or not self.points: self._command_stack.do( model.structure.AddPoint(self._structure, self._index_of_sel_point + 1, round(point[0]), round(point[1]))) if self._index_of_sel_point + 1 >= len(self.points): self.winfo_toplevel().update() self._index_of_sel_point = len(self.points) else: self._set_selection(self._index_of_sel_point + 1) self.winfo_toplevel().update() @property def points(self): """Pipe throught the struct's properties""" return self._structure.points @property def fill(self): """Pipe throught the struct's properties""" return self._structure.fill @property def selected_index(self): """the index in the struct's point list of the currently selected point Should be -1 if none selected """ return self._index_of_sel_point
class Ufd: """ Universal File Dialog - "UFD" Unopinionated, minimalist, reusable, slightly configurable, general-purpose file-dialog. """ def __init__(self, title: str = "Universal File Dialog", icon: str = "", show_hidden: bool = False, include_files: bool = True, multiselect: bool = True, select_dirs: bool = True, select_files: bool = True, unix_delimiter: bool = True, stdout: bool = False): """ Init kwargs as object attributes, save references to Tk PhotoImages, & define the widgets + layout """ if not isinstance(title, str): raise TypeError("Argument title must be type string.") self.title = title if icon: if not isinstance(icon, str): raise TypeError("Argument icon must be type string.") if not isfile(icon): raise FileNotFoundError(f"File not found: {icon}") self.icon = icon else: self.icon = "" if show_hidden: self.show_hidden = True else: self.show_hidden = False if include_files: self.include_files = True else: self.include_files = False if multiselect: self.multiselect = True else: self.multiselect = False if select_dirs: self.select_dirs = True else: self.select_dirs = False if select_files: self.select_files = True else: self.select_files = False if unix_delimiter: self.unix_delimiter = True else: self.unix_delimiter = False if stdout: self.stdout = True else: self.stdout = False # Tkinter: self.dialog = Tk() self.dialog.withdraw() self.dialog.title(self.title) self.dialog.minsize(width=300, height=200) self.dialog.geometry("500x300") self.dialog.update_idletasks() self.file_icon = PhotoImage(file=f"{dirname(__file__)}/file.gif", master=self.dialog).subsample(50) self.folder_icon = PhotoImage(file=f"{dirname(__file__)}/folder.gif", master=self.dialog).subsample(15) self.disk_icon = PhotoImage(file=f"{dirname(__file__)}/disk.gif", master=self.dialog).subsample(15) if self.icon: self.dialog.iconbitmap(self.icon) else: self.dialog.iconbitmap(f"{dirname(__file__)}/icon.ico") # Widgets: self.paneview = PanedWindow( self.dialog, sashwidth=7, bg="#cccccc", bd=0, ) self.left_pane = PanedWindow(self.paneview) self.right_pane = PanedWindow(self.paneview) self.paneview.add(self.left_pane) self.paneview.add(self.right_pane) self.treeview_x_scrollbar = Scrollbar(self.left_pane, orient="horizontal") self.treeview_y_scrollbar = Scrollbar(self.left_pane, orient="vertical") self.list_box_x_scrollbar = Scrollbar(self.right_pane, orient="horizontal") self.list_box_y_scrollbar = Scrollbar(self.right_pane, orient="vertical") # tstyle = Style().configure(".", ) self.treeview = Treeview( self.left_pane, xscrollcommand=self.treeview_x_scrollbar.set, yscrollcommand=self.treeview_y_scrollbar.set, show="tree", selectmode="browse", # style=tstyle ) self.list_box = Listbox(self.right_pane, xscrollcommand=self.list_box_x_scrollbar.set, yscrollcommand=self.list_box_y_scrollbar.set, width=34, highlightthickness=0, bd=2, relief="ridge") if self.multiselect: self.list_box.config(selectmode="extended") else: self.list_box.config(selectmode="browse") self.cancel_button = Button(self.left_pane, text="Cancel", command=self.cancel) self.submit_button = Button(self.right_pane, text="Submit", command=self.submit) self.treeview_x_scrollbar.config(command=self.treeview.xview) self.treeview_y_scrollbar.config(command=self.treeview.yview) self.list_box_x_scrollbar.config(command=self.list_box.xview) self.list_box_y_scrollbar.config(command=self.list_box.yview) #Layout: self.dialog.rowconfigure(0, weight=1) self.dialog.columnconfigure(0, weight=1) self.left_pane.grid_rowconfigure(0, weight=1) self.left_pane.grid_columnconfigure(0, weight=1) self.right_pane.grid_rowconfigure(0, weight=1) self.right_pane.grid_columnconfigure(0, weight=1) self.paneview.paneconfigure( self.left_pane, minsize=100, #Start off w/ the sash centered in the GUI: width=(self.dialog.winfo_width() / 2) - ceil( (self.paneview.cget("sashwidth") * 1.5)), ) self.paneview.paneconfigure(self.right_pane, minsize=100) self.paneview.grid(row=0, column=0, sticky="nsew") self.treeview.grid(row=0, column=0, sticky="nsew") self.treeview_y_scrollbar.grid(row=0, column=1, sticky="ns") self.treeview_x_scrollbar.grid(row=1, column=0, columnspan=2, sticky="ew") self.list_box.grid(row=0, column=0, sticky="nsew") self.list_box_y_scrollbar.grid(row=0, column=1, sticky="ns") self.list_box_x_scrollbar.grid(row=1, column=0, columnspan=2, sticky="ew") self.cancel_button.grid(row=2, column=0, sticky="w", padx=10, pady=10) self.submit_button.grid(row=2, column=0, columnspan=2, sticky="e", padx=10, pady=10) #Bindings, Protocols, & Misc: self.dialog.bind("<Control-w>", self.cancel) self.treeview.bind("<<TreeviewSelect>>", self.treeview_select) self.treeview.bind("<Double-Button-1>", self.dialog_populate) self.treeview.bind("<Return>", self.dialog_populate) self.treeview.bind("<Right>", self.dialog_populate) self.list_box.bind("<<ListboxSelect>>", self.list_box_select) self.list_box.bind("<Return>", self.submit) self.dialog.protocol("WM_DELETE_WINDOW", self.cancel) self.dialog_selection = deque() self.selection_paths = deque() for disk in self.get_disks(): self.treeview.insert( "", index="end", text=disk, image=self.disk_icon, ) self.dialog.focus() def __call__(self): """ Display dialog & return selection """ (width_offset, height_offset) = self.get_offset(self.dialog) self.dialog.geometry(f"+{width_offset}+{height_offset}") self.dialog.update_idletasks() self.dialog.deiconify() self.dialog.wait_window() for i, path in enumerate(self.dialog_selection): if self.unix_delimiter: self.dialog_selection[i] = sub("\\\\", "/", path) else: self.dialog_selection[i] = sub("/", "\\\\", path) if self.stdout: [print(item) for item in self.dialog_selection] return list(self.dialog_selection) def __str__(self): """ Return own address """ return "Universal File Dialog"\ f" @ {hex(id(self))}" def __repr__(self): """ Return full string representation of constructor signature """ return f"Ufd("\ f"title=\"{self.title}\","\ f" icon=\"{self.icon}\","\ f" show_hidden={self.show_hidden},"\ f" include_files={self.include_files},"\ f" multiselect={self.multiselect},"\ f" select_dirs={self.select_dirs},"\ f" select_files={self.select_files},"\ f" unix_delimiter={self.unix_delimiter})"\ f" stdout={self.stdout})"\ f" @ {hex(id(self))}" @staticmethod def get_offset(tk_window): """ Returns an appropriate offset for a given tkinter toplevel, such that it always is created center screen on the primary display. """ width_offset = int((tk_window.winfo_screenwidth() / 2) - (tk_window.winfo_width() / 2)) height_offset = int((tk_window.winfo_screenheight() / 2) - (tk_window.winfo_height() / 2)) return (width_offset, height_offset) @staticmethod def get_disks(): """ Returns all mounted disks (for Windows) >> ["A:", "B:", "C:"] """ if system() != "Windows": raise OSError("For use with Windows platforms.") logicaldisks = run(["wmic", "logicaldisk", "get", "name"], capture_output=True) return findall("[A-Z]:", str(logicaldisks.stdout)) @staticmethod def list_dir(path, force=False): """ Reads a directory with a shell call to dir. Truthiness of bool force determines whether hidden items are returned or not. (For Windows) """ path = sub("/", "\\\\", path) if force: dir_listing = run(["dir", path, "/b", "/a"], shell=True, capture_output=True) else: dir_listing = run(["dir", path, "/b"], shell=True, capture_output=True) output = dir_listing.stdout err = dir_listing.stderr if not output: return [] if err: err = err.decode("utf-8") raise Exception(err) str_output = output.decode("utf-8") list_output = re_split("\r\n", str_output) return sorted([item for item in list_output if item]) def climb(self, item): """ Builds & returns a complete path to root directory, including the item name itself as the path tail. An extra delimiter is appeneded for the subsequent child node, which is normalized in dialog_populate() """ item_text = self.treeview.item(item)["text"] parent = self.treeview.parent(item) path = "" parents = deque() while parent: parents.append(self.treeview.item(parent)["text"] + "/") parent = self.treeview.parent(parent) for parent in reversed(parents): path += parent path += item_text + "/" return path def dialog_populate(self, event=None): """ Dynamically populates & updates the treeview, listbox, and keeps track of the full paths corresponding to each item in the listbox """ if not self.treeview.focus(): return self.treeview.column("#0", width=1000) existing_children = self.treeview.get_children(self.treeview.focus()) [self.treeview.delete(child) for child in existing_children] self.list_box.delete(0, "end") self.selection_paths.clear() focus_item = self.treeview.focus() path = self.climb(focus_item) if self.show_hidden: children = self.list_dir(path, force=True) else: children = self.list_dir(path) for child in children: if isdir(path + child): self.treeview.insert(focus_item, index="end", text=child, image=self.folder_icon) if self.select_dirs: self.list_box.insert("end", child) self.selection_paths.append(path + child) elif isfile(path + child): if self.include_files: self.treeview.insert(focus_item, index="end", text=child, image=self.file_icon) if self.select_files: self.list_box.insert("end", child) self.list_box.itemconfig("end", {"bg": "#EAEAEA"}) self.selection_paths.append(path + child) if isfile(normpath(path)): (head, tail) = path_split(normpath(path)) head = sub("\\\\", "/", head) self.list_box.insert("end", tail) self.selection_paths.append(head + "/" + tail) self.list_box.itemconfig("end", {"bg": "#EAEAEA"}) def list_box_select(self, event=None): """ Dynamically refresh the dialog selection with what's selected in the listbox (Callback for <<ListboxSelect>>). """ self.dialog_selection.clear() for i in self.list_box.curselection(): self.dialog_selection.append(self.selection_paths[i]) def treeview_select(self, event=None): """ Dynamically refresh the dialog selection with what's selected in the treeview (Callback for <<TreeviewSelect>>). """ for i in self.list_box.curselection(): self.list_box.selection_clear(i) self.dialog_selection.clear() item = normpath(self.climb(self.treeview.focus())) self.dialog_selection.append(item) def submit(self, event=None): """ Satisfies wait_window() in self.__call__() and validates selection (Callback for <Return>, <Button-1> on file_list, submit_button) """ if self.select_dirs == False: for item in self.dialog_selection: if isdir(item): messagebox.showwarning( "Error - Invalid Selection", "Unable to select directory. Please select a file(s).") return if self.select_files == False: for item in self.dialog_selection: if isfile(item): messagebox.showwarning( "Error - Invalid Selection", "Unable to select file. Please select a folder(s)") return self.dialog.destroy() def cancel(self, event=None): """ Satisfies wait_window() in self.__call__() (Callback for <Button-1> on cancel_button) (Callback for protocol "WM_DELETE_WINDOW" on self.dialog) """ self.dialog_selection.clear() self.dialog.destroy()
def createScoreTable(self): """Crée le tableau des scores.""" tk.Label(self.master, text="Scores", font="-weight bold").grid(row=3, column=0, columnspan=2) tv = Treeview(self.master, height=3) tv['columns'] = ('Score', "Bomb") tv.heading("#0", text='User', anchor=tk.W) tv.heading('Bomb', text='Bombs available', anchor=tk.W) tv.column('Bomb', anchor=tk.W, width=100) tv.heading('Score', text='Score', anchor=tk.W) tv.column('Score', anchor=tk.W, width=100) tv.grid(row=4, column=0, columnspan=3, sticky=tk.EW) self.treeview = tv
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)
ShowDataFrame.place(x=550, y=80, width=620, height=600) ##------------------------------------------------- Showdataframe style = ttk.Style() style.configure('Treeview.Heading', font=('chiller', 20, 'bold'), foreground='blue') style.configure('Treeview', font=('times', 15, 'bold'), background='cyan', foreground='black') scroll_x = Scrollbar(ShowDataFrame, orient=HORIZONTAL) scroll_y = Scrollbar(ShowDataFrame, orient=VERTICAL) studenmttable = Treeview(ShowDataFrame, columns=('Id', 'Name', 'Mobile No', 'Email', 'Address', 'Gender', 'D.O.B', 'Added Date', 'Added Time'), yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set) scroll_x.pack(side=BOTTOM, fill=X) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.config(command=studenmttable.xview) scroll_y.config(command=studenmttable.yview) studenmttable.heading('Id', text='Id') studenmttable.heading('Name', text='Name') studenmttable.heading('Mobile No', text='Mobile No') studenmttable.heading('Email', text='Email') 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')
class DialogPackageManager(Toplevel): def __init__(self, mainWin, packageNamesWithNewerFileDates): super(DialogPackageManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.packagesConfig = PackageManager.packagesConfig self.packagesConfigChanged = False self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Taxonomy Packages Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system. " "Select either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package. "), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system. " "URL may be either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package. "), wraplength=240) manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName) ToolTip(manifestNameButton, text=_("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml). " "Uses unix file name pattern matching. " "Multiple manifest files are supported in archive (such as oasis catalogs). " "(Replaces search for either .taxonomyPackage.xml or catalog.xml). "), wraplength=240) self.manifestNamePattern = "" addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) manifestNameButton.grid(row=3, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3) # right tree frame (packages already known to arelle) packagesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL) hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL) self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect) hScrollbar["command"] = self.packagesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.packagesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) packagesFrame.columnconfigure(0, weight=1) packagesFrame.rowconfigure(0, weight=1) packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.packagesView.focus_set() self.packagesView.column("#0", width=120, anchor="w") self.packagesView.heading("#0", text=_("Name")) self.packagesView["columns"] = ("ver", "status", "date", "update", "descr") self.packagesView.column("ver", width=150, anchor="w", stretch=False) self.packagesView.heading("ver", text=_("Version")) self.packagesView.column("status", width=50, anchor="w", stretch=False) self.packagesView.heading("status", text=_("Status")) self.packagesView.column("date", width=170, anchor="w", stretch=False) self.packagesView.heading("date", text=_("File Date")) self.packagesView.column("update", width=50, anchor="w", stretch=False) self.packagesView.heading("update", text=_("Update")) self.packagesView.column("descr", width=200, anchor="w", stretch=False) self.packagesView.heading("descr", text=_("Description")) remappingsFrame = Frame(frame) vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL) hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL) self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.remappingsView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.remappingsView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) remappingsFrame.columnconfigure(0, weight=1) remappingsFrame.rowconfigure(0, weight=1) remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.remappingsView.focus_set() self.remappingsView.column("#0", width=200, anchor="w") self.remappingsView.heading("#0", text=_("Prefix")) self.remappingsView["columns"] = ("remapping") self.remappingsView.column("remapping", width=500, anchor="w", stretch=False) self.remappingsView.heading("remapping", text=_("Remapping")) # bottom frame package info details packageInfoFrame = Frame(frame, width=700) packageInfoFrame.columnconfigure(1, weight=1) self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W) self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED) self.packageVersionHdr.grid(row=1, column=0, sticky=W) self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W) self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED) self.packageDescrHdr.grid(row=2, column=0, sticky=W) self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W) self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED) self.packagePrefixesHdr.grid(row=3, column=0, sticky=W) self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W) ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240) self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED) self.packageUrlHdr.grid(row=4, column=0, sticky=W) self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W) ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240) self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED) self.packageDateHdr.grid(row=5, column=0, sticky=W) self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W) ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240) self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable) ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240) self.packageEnableButton.grid(row=6, column=1, sticky=E) self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp) ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240) self.packageMoveUpButton.grid(row=6, column=2, sticky=E) self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown) ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240) self.packageMoveDownButton.grid(row=6, column=3, sticky=E) self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload) ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240) self.packageReloadButton.grid(row=6, column=4, sticky=E) self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove) ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240) self.packageRemoveButton.grid(row=6, column=5, sticky=E) packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) packageInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self) def loadTreeViews(self): self.selectedModule = None # clear previous treeview entries for previousNode in self.packagesView.get_children(""): self.packagesView.delete(previousNode) for i, packageInfo in enumerate(self.packagesConfig.get("packages", [])): name = packageInfo.get("name", "package{}".format(i)) node = self.packagesView.insert("", "end", "_{}".format(i), text=name) self.packagesView.set(node, "ver", packageInfo.get("version")) self.packagesView.set(node, "status", packageInfo.get("status")) self.packagesView.set(node, "date", packageInfo.get("fileDate")) if name in self.packageNamesWithNewerFileDates: self.packagesView.set(node, "update", _("available")) self.packagesView.set(node, "descr", packageInfo.get("description")) # clear previous treeview entries for previousNode in self.remappingsView.get_children(""): self.remappingsView.delete(previousNode) for i, remappingItem in enumerate(sorted(self.packagesConfig.get("remappings", {}).items())): prefix, remapping = remappingItem node = self.remappingsView.insert("", "end", prefix, text=prefix) self.remappingsView.set(node, "remapping", remapping) self.packageSelect() # clear out prior selection def ok(self, event=None): if self.packagesConfigChanged: PackageManager.packagesConfig = self.packagesConfig PackageManager.packagesConfigChanged = True self.cntlr.onPackageEnablementChanged() self.close() def close(self, event=None): self.parent.focus_set() self.destroy() def packageSelect(self, *args): node = (self.packagesView.selection() or (None,))[0] try: nodeIndex = int(node[1:]) except (ValueError, TypeError): nodeIndex = -1 if 0 <= nodeIndex < len(self.packagesConfig["packages"]): packageInfo = self.packagesConfig["packages"][nodeIndex] self.selectedPackageIndex = nodeIndex name = packageInfo["name"] self.packageNameLabel.config(text=name) self.packageVersionHdr.config(state=ACTIVE) self.packageVersionLabel.config(text=packageInfo["version"]) self.packageDescrHdr.config(state=ACTIVE) self.packageDescrLabel.config(text=packageInfo["description"]) self.packagePrefixesHdr.config(state=ACTIVE) self.packagePrefixesLabel.config(text=', '.join(packageInfo["remappings"].keys())) self.packageUrlHdr.config(state=ACTIVE) self.packageUrlLabel.config(text=packageInfo["URL"]) self.packageDateHdr.config(state=ACTIVE) self.packageDateLabel.config(text=packageInfo["fileDate"] + " " + (_("(an update is available)") if name in self.packageNamesWithNewerFileDates else "")) self.packageEnableButton.config(state=ACTIVE, text={"enabled":self.DISABLE, "disabled":self.ENABLE}[packageInfo["status"]]) self.packageMoveUpButton.config(state=ACTIVE if 0 < nodeIndex else DISABLED) self.packageMoveDownButton.config(state=ACTIVE if nodeIndex < (len(self.packagesConfig["packages"]) - 1) else DISABLED) self.packageReloadButton.config(state=ACTIVE) self.packageRemoveButton.config(state=ACTIVE) else: self.selectedPackageIndex = -1 self.packageNameLabel.config(text="") self.packageVersionHdr.config(state=DISABLED) self.packageVersionLabel.config(text="") self.packageDescrHdr.config(state=DISABLED) self.packageDescrLabel.config(text="") self.packagePrefixesHdr.config(state=DISABLED) self.packagePrefixesLabel.config(text="") self.packageUrlHdr.config(state=DISABLED) self.packageUrlLabel.config(text="") self.packageDateHdr.config(state=DISABLED) self.packageDateLabel.config(text="") self.packageEnableButton.config(state=DISABLED, text=self.ENABLE) self.packageMoveUpButton.config(state=DISABLED) self.packageMoveDownButton.config(state=DISABLED) self.packageReloadButton.config(state=DISABLED) self.packageRemoveButton.config(state=DISABLED) def findLocally(self): initialdir = self.cntlr.pluginDir # default plugin directory if not self.cntlr.isMac: # can't navigate within app easily, always start in default directory initialdir = self.cntlr.config.setdefault("packageOpenDir", initialdir) filename = self.cntlr.uiFileDialog("open", parent=self, title=_("Choose taxonomy package file"), initialdir=initialdir, filetypes=[(_("Taxonomy package files (*.zip)"), "*.zip"), (_("Manifest (*.taxonomyPackage.xml)"), "*.taxonomyPackage.xml"), (_("Oasis Catalog (*catalog.xml)"), "*catalog.xml")], defaultextension=".zip") if filename: # check if a package is selected (any file in a directory containing an __init__.py self.cntlr.config["packageOpenDir"] = os.path.dirname(filename) packageInfo = PackageManager.packageInfo(filename, packageManifestName=self.manifestNamePattern) self.loadFoundPackageInfo(packageInfo, filename) def findOnWeb(self): url = DialogURL.askURL(self) if url: # url is the in-cache or local file packageInfo = PackageManager.packageInfo(url, packageManifestName=self.manifestNamePattern) self.cntlr.showStatus("") # clear web loading status self.loadFoundPackageInfo(packageInfo, url) def manifestName(self): self.manifestNamePattern = simpledialog.askstring(_("Archive manifest file name pattern"), _("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml). \n" "Uses unix file name pattern matching. \n" "Multiple manifest files are supported in archive (such as oasis catalogs). \n" "(If blank, search for either .taxonomyPackage.xml or catalog.xml). "), initialvalue=self.manifestNamePattern, parent=self) def loadFoundPackageInfo(self, packageInfo, url): if packageInfo and packageInfo.get("name"): self.addPackageInfo(packageInfo) self.loadTreeViews() else: messagebox.showwarning(_("Package is not itself a taxonomy package. "), _("File does not itself contain a manifest file: \n\n{0}\n\n " "If opening an archive file, the manifest file search pattern currently is \"\", please press \"Manifest\" to change manifest file name pattern, e.g.,, \"*.taxonomyPackage.xml\", if needed. ") .format(url), parent=self) def removePackageInfo(self, name, version): # find package entry packagesList = self.packagesConfig["packages"] j = -1 for i, packageInfo in enumerate(packagesList): if packageInfo['name'] == name and packageInfo['version'] == version: j = i break if 0 <= j < len(packagesList): del self.packagesConfig["packages"][i] self.packagesConfigChanged = True def addPackageInfo(self, packageInfo): name = packageInfo["name"] version = packageInfo["version"] self.removePackageInfo(name, version) # remove any prior entry for this package self.packageNamesWithNewerFileDates.discard(name) # no longer has an update available self.packagesConfig["packages"].append(packageInfo) PackageManager.rebuildRemappings() self.packagesConfigChanged = True def packageEnable(self): if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]): packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex] if self.packageEnableButton['text'] == self.ENABLE: packageInfo["status"] = "enabled" self.packageEnableButton['text'] = self.DISABLE elif self.packageEnableButton['text'] == self.DISABLE: packageInfo["status"] = "disabled" self.packageEnableButton['text'] = self.ENABLE self.packagesConfigChanged = True PackageManager.rebuildRemappings() self.loadTreeViews() def packageMoveUp(self): if 1 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]): packages = self.packagesConfig["packages"] packageInfo = packages[self.selectedPackageIndex] del packages[self.selectedPackageIndex] packages.insert(self.selectedPackageIndex -1, packageInfo) self.packagesConfigChanged = True PackageManager.rebuildRemappings() self.loadTreeViews() def packageMoveDown(self): if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]) - 1: packages = self.packagesConfig["packages"] packageInfo = packages[self.selectedPackageIndex] del packages[self.selectedPackageIndex] packages.insert(self.selectedPackageIndex + 1, packageInfo) self.packagesConfigChanged = True PackageManager.rebuildRemappings() self.loadTreeViews() def packageReload(self): if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]): packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex] url = packageInfo.get("URL") if url: packageInfo = PackageManager.packageInfo(url, reload=True, packageManifestName=packageInfo.get("manifestName")) if packageInfo: self.addPackageInfo(packageInfo) PackageManager.rebuildRemappings() self.loadTreeViews() self.cntlr.showStatus(_("{0} reloaded").format(packageInfo.get("name")), clearAfter=5000) else: messagebox.showwarning(_("Package error"), _("File or package cannot be reloaded: \n\n{0}") .format(url), parent=self) def packageRemove(self): if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]): packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex] self.removePackageInfo(packageInfo["name"], packageInfo["version"]) self.packagesConfigChanged = True PackageManager.rebuildRemappings() self.loadTreeViews()
def _setup(self): tk = self.tk tk.wm_title("Jumbonet GUI Example") tk.protocol("WM_DELETE_WINDOW", self.shutdown) height = 250 # center: treeview self.tv = Treeview(tk) tv = self.tv tv.config(height=height) # treeview configuration tv["columns"] = ("process", "status") tv.column("process", width=130) tv.column("status", width=70) tv.heading("process", text="Process UUID") tv.heading("status", text="Status") tv.bind("<ButtonRelease-1>", self.row_selected) # right: log windows r_frame = Frame(tk, height=height) scroll = Scrollbar(r_frame) #the global log (top) self.dsp_global = TextDisplay(r_frame, width=70, height=20) self.dsp_global.append("Global information") #the process log (bottom) self.dsp_process = TextDisplay(r_frame, width=70, height=25) self.dsp_process.append("This shows output of the selected process") #left: entry and buttons self.input.set("") l_frame = Frame(tk, width=200, height=height) l = Label(l_frame, text="Start process here") e = Entry(l_frame, textvariable=self.input) buttons = Frame(l_frame) # buttons button_add = Button(buttons, text="Start", command=self.start_process) button_kill = Button(buttons, text="Kill", command=self.kill_process) # packing all of it # frame on left l.pack(side=TOP, fill=X) e.pack(side=TOP, fill=X) button_add.pack(side=LEFT) button_kill.pack(side=LEFT) buttons.pack(side=TOP, fill=X) # applog frame on right scroll.pack(side=RIGHT, fill=Y) self.dsp_global.pack(side=TOP, fill=X) self.dsp_process.pack(side=TOP, fill=X) # top-level pack l_frame.pack(side=LEFT, fill=Y, expand=False) tv.pack(side=LEFT, fill=Y, expand=False) r_frame.pack(side=LEFT, fill=Y, expand=False)
def __init__(self, mainWin, packageNamesWithNewerFileDates): super(DialogPackageManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.packagesConfig = PackageManager.packagesConfig self.packagesConfigChanged = False self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Taxonomy Packages Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system. " "Select either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package. "), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system. " "URL may be either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package. "), wraplength=240) manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName) ToolTip(manifestNameButton, text=_("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml). " "Uses unix file name pattern matching. " "Multiple manifest files are supported in archive (such as oasis catalogs). " "(Replaces search for either .taxonomyPackage.xml or catalog.xml). "), wraplength=240) self.manifestNamePattern = "" addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) manifestNameButton.grid(row=3, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3) # right tree frame (packages already known to arelle) packagesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL) hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL) self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect) hScrollbar["command"] = self.packagesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.packagesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) packagesFrame.columnconfigure(0, weight=1) packagesFrame.rowconfigure(0, weight=1) packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.packagesView.focus_set() self.packagesView.column("#0", width=120, anchor="w") self.packagesView.heading("#0", text=_("Name")) self.packagesView["columns"] = ("ver", "status", "date", "update", "descr") self.packagesView.column("ver", width=150, anchor="w", stretch=False) self.packagesView.heading("ver", text=_("Version")) self.packagesView.column("status", width=50, anchor="w", stretch=False) self.packagesView.heading("status", text=_("Status")) self.packagesView.column("date", width=170, anchor="w", stretch=False) self.packagesView.heading("date", text=_("File Date")) self.packagesView.column("update", width=50, anchor="w", stretch=False) self.packagesView.heading("update", text=_("Update")) self.packagesView.column("descr", width=200, anchor="w", stretch=False) self.packagesView.heading("descr", text=_("Description")) remappingsFrame = Frame(frame) vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL) hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL) self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.remappingsView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.remappingsView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) remappingsFrame.columnconfigure(0, weight=1) remappingsFrame.rowconfigure(0, weight=1) remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.remappingsView.focus_set() self.remappingsView.column("#0", width=200, anchor="w") self.remappingsView.heading("#0", text=_("Prefix")) self.remappingsView["columns"] = ("remapping") self.remappingsView.column("remapping", width=500, anchor="w", stretch=False) self.remappingsView.heading("remapping", text=_("Remapping")) # bottom frame package info details packageInfoFrame = Frame(frame, width=700) packageInfoFrame.columnconfigure(1, weight=1) self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W) self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED) self.packageVersionHdr.grid(row=1, column=0, sticky=W) self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W) self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED) self.packageDescrHdr.grid(row=2, column=0, sticky=W) self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W) self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED) self.packagePrefixesHdr.grid(row=3, column=0, sticky=W) self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W) ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240) self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED) self.packageUrlHdr.grid(row=4, column=0, sticky=W) self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W) ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240) self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED) self.packageDateHdr.grid(row=5, column=0, sticky=W) self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left") self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W) ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240) self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable) ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240) self.packageEnableButton.grid(row=6, column=1, sticky=E) self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp) ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240) self.packageMoveUpButton.grid(row=6, column=2, sticky=E) self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown) ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240) self.packageMoveDownButton.grid(row=6, column=3, sticky=E) self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload) ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240) self.packageReloadButton.grid(row=6, column=4, sticky=E) self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove) ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240) self.packageRemoveButton.grid(row=6, column=5, sticky=E) packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) packageInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
open_button.pack(side=LEFT, after=stop_button, padx=10, pady=10) save_button.pack(side=LEFT, after=open_button, padx=10, pady=10) quit_button.pack(side=LEFT, after=save_button, padx=10, pady=10) filter_label.pack(side=LEFT, after=quit_button, padx=0, pady=10) fitler_entry.pack(side=LEFT, after=filter_label, padx=20, pady=10, fill=X, expand=YES) toolbar.pack(side=TOP, fill=X) # 数据包列表区 packet_list_frame = Frame() packet_list_sub_frame = Frame(packet_list_frame) packet_list_tree = Treeview(packet_list_sub_frame, selectmode='browse') packet_list_tree.bind('<<TreeviewSelect>>', on_click_packet_list_tree) # 数据包列表垂直滚动条 packet_list_vscrollbar = Scrollbar(packet_list_sub_frame, orient="vertical", command=packet_list_tree.yview) packet_list_vscrollbar.pack(side=RIGHT, fill=Y, expand=YES) packet_list_tree.configure(yscrollcommand=packet_list_vscrollbar.set) packet_list_sub_frame.pack(side=TOP, fill=BOTH, expand=YES) # 数据包列表水平滚动条 packet_list_hscrollbar = Scrollbar(packet_list_frame, orient="horizontal", command=packet_list_tree.xview) packet_list_hscrollbar.pack(side=BOTTOM, fill=X, expand=YES) packet_list_tree.configure(xscrollcommand=packet_list_hscrollbar.set) # 数据包列表区列标题
class FacultyDelWindow: def __init__(self, data=''): self.data = data print(self.data) self.win = Tk() self.canvas = Canvas(self.win, width=800, height=420, bg='white') self.canvas.pack(expand=YES, fill=BOTH) # show window in center of the screen width = self.win.winfo_screenwidth() height = self.win.winfo_screenheight() x = int(width / 2 - 800 / 2) y = int(height / 2 - 420 / 2) str1 = "800x420+" + str(x) + "+" + str(y) self.win.geometry(str1) # disable resize window self.win.resizable(False, False) # changing title of the window self.win.title( "| DELETING FACULTY DETAILS | LIBRARY MANAGEMENT SYSTEM |") def add_frame(self): self.frame = Frame(self.win, height=420, width=800) self.frame.place(x=0, y=0) x, y = 0, 0 self.label = Label(self.frame, text="DELETING FACULTY DETAILS", fg='black') self.label.config(font=("Poppins", 20, 'underline bold')) self.label.place(x=190, y=35) # use tree view to show details from the table self.tr = Treeview(self.frame, columns=('FACULTY_ID', 'FACULTY_NAME', 'GENDER', 'DEPARTMENT', 'CONTACT_NO'), selectmode="extended") # heading key + text self.tr.heading('#0', text='FACULTY_ID') self.tr.column('#0', minwidth=0, width=100, stretch=NO) self.tr.heading('#1', text='FACULTY_NAME') self.tr.column('#1', minwidth=0, width=100, stretch=NO) self.tr.heading('#2', text='GENDER') self.tr.column('#2', minwidth=0, width=100, stretch=NO) self.tr.heading('#3', text='DEPARTMENT') self.tr.column('#3', minwidth=0, width=100, stretch=NO) self.tr.heading('#4', text='CONTACT_NO') self.tr.column('#4', minwidth=0, width=100, stretch=NO) self.tr.heading('#5', text='DELETE') self.tr.column('#5', minwidth=0, width=100, stretch=NO) # self.tr.heading('#6', text='DELETE') # self.tr.column('#6', minwidth=0, width=100, stretch=NO) j = 0 for i in Database.database.Faculties(): self.tr.insert('', index=j, text=i[0], values=(i[1], i[2], i[3], i[4], 'DELETE')) j += 1 # create action on deletion self.tr.bind('<Double-Button-1>', self.actions) self.tr.place(x=100, y=y + 100) self.win.mainloop() def actions(self, e): # get the value of deleted row tt = self.tr.focus() # get the column id col = self.tr.identify_column(e.x) print(col) print(self.tr.item(tt)) data = (self.tr.item(tt).get('text'), ) if col == '#5': res = messagebox.askyesno("Message", "Do you want to delete..!") if res: d = Database.database.DeleteFaculty(data) if d: messagebox.showinfo( "Message", "Faculty Details deleted successfully..!") self.win.destroy() x = Thirdpage else: self.win.destroy() x = Student.DeleteFaculty.FacultyDelWindow() x.add_frame()
def __init__(self, mainWin, modulesWithNewerFileDates): super(DialogPluginManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.pluginConfig = PluginManager.pluginConfig self.pluginConfigChanged = False self.uiClassMethodsChanged = False self.modelClassesChanged = False self.disclosureSystemTypesChanged = False self.hostSystemFeaturesChanged = False self.modulesWithNewerFileDates = modulesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Plug-in Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240) addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3) # right tree frame (plugins already known to arelle) modulesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL) hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL) self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect) hScrollbar["command"] = self.modulesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.modulesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) modulesFrame.columnconfigure(0, weight=1) modulesFrame.rowconfigure(0, weight=1) modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.modulesView.focus_set() self.modulesView.column("#0", width=120, anchor="w") self.modulesView.heading("#0", text=_("Name")) self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license") self.modulesView.column("author", width=100, anchor="w", stretch=False) self.modulesView.heading("author", text=_("Author")) self.modulesView.column("ver", width=50, anchor="w", stretch=False) self.modulesView.heading("ver", text=_("Version")) self.modulesView.column("status", width=50, anchor="w", stretch=False) self.modulesView.heading("status", text=_("Status")) self.modulesView.column("date", width=70, anchor="w", stretch=False) self.modulesView.heading("date", text=_("File Date")) self.modulesView.column("update", width=50, anchor="w", stretch=False) self.modulesView.heading("update", text=_("Update")) self.modulesView.column("descr", width=200, anchor="w", stretch=False) self.modulesView.heading("descr", text=_("Description")) self.modulesView.column("license", width=70, anchor="w", stretch=False) self.modulesView.heading("license", text=_("License")) classesFrame = Frame(frame) vScrollbar = Scrollbar(classesFrame, orient=VERTICAL) hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL) self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.classesView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.classesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.classesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) classesFrame.columnconfigure(0, weight=1) classesFrame.rowconfigure(0, weight=1) classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.classesView.focus_set() self.classesView.column("#0", width=200, anchor="w") self.classesView.heading("#0", text=_("Class")) self.classesView["columns"] = ("modules",) self.classesView.column("modules", width=500, anchor="w", stretch=False) self.classesView.heading("modules", text=_("Modules")) # bottom frame module info details moduleInfoFrame = Frame(frame, width=700) moduleInfoFrame.columnconfigure(1, weight=1) self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W) self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED) self.moduleAuthorHdr.grid(row=1, column=0, sticky=W) self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W) self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED) self.moduleDescrHdr.grid(row=2, column=0, sticky=W) self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W) self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED) self.moduleClassesHdr.grid(row=3, column=0, sticky=W) self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W) ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240) self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED) self.moduleUrlHdr.grid(row=4, column=0, sticky=W) self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W) ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240) self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED) self.moduleDateHdr.grid(row=5, column=0, sticky=W) self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W) ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240) self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED) self.moduleLicenseHdr.grid(row=6, column=0, sticky=W) self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W) self.moduleImportsHdr = Label(moduleInfoFrame, text=_("imports:"), state=DISABLED) self.moduleImportsHdr.grid(row=7, column=0, sticky=W) self.moduleImportsLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleImportsLabel.grid(row=7, column=1, columnspan=3, sticky=W) self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable) ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240) self.moduleEnableButton.grid(row=8, column=1, sticky=E) self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload) ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240) self.moduleReloadButton.grid(row=8, column=2, sticky=E) self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove) ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240) self.moduleRemoveButton.grid(row=8, column=3, sticky=E) moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) moduleInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) enableDisableFrame = Frame(frame) enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3) enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll) ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240) disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll) ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240) enableAllButton.grid(row=1, column=1) disableAllButton.grid(row=1, column=2) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self)
########### ShowFrame ############ style = Style() # ["aqua", "step", "clam", "alt", "default", "classic"] style.theme_use("classic") style.configure('Treeview.Heading', font=('times', 10, 'bold'), foreground='black') style.configure('Treeview', font=('times', 7, 'bold'), background="yellow", foreground='black') scroll_x = Scrollbar(ShowFrame, orient=HORIZONTAL) scroll_y = Scrollbar(ShowFrame, orient=VERTICAL) EmpTable = Treeview(ShowFrame, columns=('ID', 'Name', 'Phone'), yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set) scroll_x.pack(side=BOTTOM, fill=X) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.config(command=EmpTable.xview) scroll_y.config(command=EmpTable.yview) EmpTable.heading('ID', text='ID') EmpTable.heading('Name', text='Name') EmpTable.heading('Phone', text='Phone') EmpTable['show'] = 'headings' EmpTable.column('ID', width=60) EmpTable.column('Name', width=120) EmpTable.column('Phone', width=120)
class DialogPluginManager(Toplevel): def __init__(self, mainWin, modulesWithNewerFileDates): super(DialogPluginManager, self).__init__(mainWin.parent) self.ENABLE = _("Enable") self.DISABLE = _("Disable") self.parent = mainWin.parent self.cntlr = mainWin # copy plugins for temporary display self.pluginConfig = PluginManager.pluginConfig self.pluginConfigChanged = False self.uiClassMethodsChanged = False self.modelClassesChanged = False self.disclosureSystemTypesChanged = False self.hostSystemFeaturesChanged = False self.modulesWithNewerFileDates = modulesWithNewerFileDates parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry()) dialogX = int(parentGeometry.group(3)) dialogY = int(parentGeometry.group(4)) self.title(_("Plug-in Manager")) frame = Frame(self) # left button frame buttonFrame = Frame(frame, width=40) buttonFrame.columnconfigure(0, weight=1) addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center") addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally) ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240) addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb) ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240) addLabel.grid(row=0, column=0, pady=4) addLocalButton.grid(row=1, column=0, pady=4) addWebButton.grid(row=2, column=0, pady=4) buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3) # right tree frame (plugins already known to arelle) modulesFrame = Frame(frame, width=700) vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL) hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL) self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7) self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W)) self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect) hScrollbar["command"] = self.modulesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.modulesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) modulesFrame.columnconfigure(0, weight=1) modulesFrame.rowconfigure(0, weight=1) modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.modulesView.focus_set() self.modulesView.column("#0", width=120, anchor="w") self.modulesView.heading("#0", text=_("Name")) self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license") self.modulesView.column("author", width=100, anchor="w", stretch=False) self.modulesView.heading("author", text=_("Author")) self.modulesView.column("ver", width=50, anchor="w", stretch=False) self.modulesView.heading("ver", text=_("Version")) self.modulesView.column("status", width=50, anchor="w", stretch=False) self.modulesView.heading("status", text=_("Status")) self.modulesView.column("date", width=70, anchor="w", stretch=False) self.modulesView.heading("date", text=_("File Date")) self.modulesView.column("update", width=50, anchor="w", stretch=False) self.modulesView.heading("update", text=_("Update")) self.modulesView.column("descr", width=200, anchor="w", stretch=False) self.modulesView.heading("descr", text=_("Description")) self.modulesView.column("license", width=70, anchor="w", stretch=False) self.modulesView.heading("license", text=_("License")) classesFrame = Frame(frame) vScrollbar = Scrollbar(classesFrame, orient=VERTICAL) hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL) self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5) self.classesView.grid(row=0, column=0, sticky=(N, S, E, W)) hScrollbar["command"] = self.classesView.xview hScrollbar.grid(row=1, column=0, sticky=(E,W)) vScrollbar["command"] = self.classesView.yview vScrollbar.grid(row=0, column=1, sticky=(N,S)) classesFrame.columnconfigure(0, weight=1) classesFrame.rowconfigure(0, weight=1) classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3) self.classesView.focus_set() self.classesView.column("#0", width=200, anchor="w") self.classesView.heading("#0", text=_("Class")) self.classesView["columns"] = ("modules",) self.classesView.column("modules", width=500, anchor="w", stretch=False) self.classesView.heading("modules", text=_("Modules")) # bottom frame module info details moduleInfoFrame = Frame(frame, width=700) moduleInfoFrame.columnconfigure(1, weight=1) self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", font=font.Font(family='Helvetica', size=12, weight='bold')) self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W) self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED) self.moduleAuthorHdr.grid(row=1, column=0, sticky=W) self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W) self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED) self.moduleDescrHdr.grid(row=2, column=0, sticky=W) self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W) self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED) self.moduleClassesHdr.grid(row=3, column=0, sticky=W) self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W) ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240) self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED) self.moduleUrlHdr.grid(row=4, column=0, sticky=W) self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W) ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240) self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED) self.moduleDateHdr.grid(row=5, column=0, sticky=W) self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W) ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240) self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED) self.moduleLicenseHdr.grid(row=6, column=0, sticky=W) self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W) self.moduleImportsHdr = Label(moduleInfoFrame, text=_("imports:"), state=DISABLED) self.moduleImportsHdr.grid(row=7, column=0, sticky=W) self.moduleImportsLabel = Label(moduleInfoFrame, wraplength=600, justify="left") self.moduleImportsLabel.grid(row=7, column=1, columnspan=3, sticky=W) self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable) ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240) self.moduleEnableButton.grid(row=8, column=1, sticky=E) self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload) ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240) self.moduleReloadButton.grid(row=8, column=2, sticky=E) self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove) ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240) self.moduleRemoveButton.grid(row=8, column=3, sticky=E) moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3) moduleInfoFrame.config(borderwidth=4, relief="groove") okButton = Button(frame, text=_("Close"), command=self.ok) ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240) cancelButton = Button(frame, text=_("Cancel"), command=self.close) ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240) okButton.grid(row=3, column=3, sticky=(S,E), pady=3) cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3) enableDisableFrame = Frame(frame) enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3) enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll) ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240) disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll) ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240) enableAllButton.grid(row=1, column=1) disableAllButton.grid(row=1, column=2) self.loadTreeViews() self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100)) frame.grid(row=0, column=0, sticky=(N,S,E,W)) frame.columnconfigure(0, weight=0) frame.columnconfigure(1, weight=1) frame.rowconfigure(0, weight=1) window = self.winfo_toplevel() window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) self.bind("<Return>", self.ok) self.bind("<Escape>", self.close) self.protocol("WM_DELETE_WINDOW", self.close) self.grab_set() self.wait_window(self) def loadTreeViews(self): self.selectedModule = None # clear previous treeview entries for previousNode in self.modulesView.get_children(""): self.modulesView.delete(previousNode) def loadSubtree(parentNode, moduleItems): for moduleItem in sorted(moduleItems, key=lambda item: item[0]): moduleInfo = moduleItem[1] if parentNode or not moduleInfo.get("isImported"): nodeName = moduleItem[0] if parentNode: nodeName = parentNode + GROUPSEP + nodeName name = moduleInfo.get("name", nodeName) node = self.modulesView.insert(parentNode, "end", nodeName, text=name) self.modulesView.set(node, "author", moduleInfo.get("author")) self.modulesView.set(node, "ver", moduleInfo.get("version")) self.modulesView.set(node, "status", moduleInfo.get("status")) self.modulesView.set(node, "date", moduleInfo.get("fileDate")) if name in self.modulesWithNewerFileDates: self.modulesView.set(node, "update", _("available")) self.modulesView.set(node, "descr", moduleInfo.get("description")) self.modulesView.set(node, "license", moduleInfo.get("license")) if moduleInfo.get("imports"): loadSubtree(node, [(importModuleInfo["name"],importModuleInfo) for importModuleInfo in moduleInfo["imports"]]) loadSubtree("", self.pluginConfig.get("modules", {}).items()) # clear previous treeview entries for previousNode in self.classesView.get_children(""): self.classesView.delete(previousNode) for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())): className, moduleList = classItem node = self.classesView.insert("", "end", className, text=className) self.classesView.set(node, "modules", ', '.join(moduleList)) self.moduleSelect() # clear out prior selection def ok(self, event=None): if self.pluginConfigChanged: PluginManager.pluginConfig = self.pluginConfig PluginManager.pluginConfigChanged = True PluginManager.reset() # force reloading of modules if self.uiClassMethodsChanged or self.modelClassesChanged or self.disclosureSystemTypesChanged or self.hostSystemFeaturesChanged: # may require reloading UI affectedItems = "" if self.uiClassMethodsChanged: affectedItems += _("menus of the user interface") if self.modelClassesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("model objects of the processor") if self.disclosureSystemTypesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("disclosure system types") if self.hostSystemFeaturesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("host system features") if messagebox.askyesno(_("User interface plug-in change"), _("A change in plug-in class methods may have affected {0}. " "Please restart Arelle to due to these changes. \n\n" "Should Arelle restart itself now " "(if there are any unsaved changes they would be lost!)?" ).format(affectedItems), parent=self): self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True])) self.close() def close(self, event=None): self.parent.focus_set() self.destroy() def moduleSelect(self, *args): node = (self.modulesView.selection() or (None,))[0] if node: node = node.rpartition(GROUPSEP)[2] # drop leading path names for module name moduleInfo = self.pluginConfig.get("modules", {}).get(node) if moduleInfo: self.selectedModule = node name = moduleInfo["name"] self.moduleNameLabel.config(text=name) self.moduleAuthorHdr.config(state=ACTIVE) self.moduleAuthorLabel.config(text=moduleInfo["author"]) self.moduleDescrHdr.config(state=ACTIVE) self.moduleDescrLabel.config(text=moduleInfo["description"]) self.moduleClassesHdr.config(state=ACTIVE) self.moduleClassesLabel.config(text=', '.join(moduleInfo["classMethods"])) self.moduleUrlHdr.config(state=ACTIVE) self.moduleUrlLabel.config(text=moduleInfo["moduleURL"]) self.moduleDateHdr.config(state=ACTIVE) self.moduleDateLabel.config(text=moduleInfo["fileDate"] + " " + (_("(an update is available)") if name in self.modulesWithNewerFileDates else "")) self.moduleLicenseHdr.config(state=ACTIVE) self.moduleLicenseLabel.config(text=moduleInfo["license"]) if moduleInfo.get("imports"): self.moduleImportsHdr.config(state=ACTIVE) _text = ", ".join(mi["name"] for mi in moduleInfo["imports"][:3]) if len(moduleInfo["imports"]) >= 3: _text += ", ..." self.moduleImportsLabel.config(text=_text) _buttonState = DISABLED if moduleInfo.get("isImported") else ACTIVE self.moduleEnableButton.config(state=_buttonState, text={"enabled":self.DISABLE, "disabled":self.ENABLE}[moduleInfo["status"]]) self.moduleReloadButton.config(state=_buttonState) self.moduleRemoveButton.config(state=_buttonState) else: self.selectedModule = None self.moduleNameLabel.config(text="") self.moduleAuthorHdr.config(state=DISABLED) self.moduleAuthorLabel.config(text="") self.moduleDescrHdr.config(state=DISABLED) self.moduleDescrLabel.config(text="") self.moduleClassesHdr.config(state=DISABLED) self.moduleClassesLabel.config(text="") self.moduleUrlHdr.config(state=DISABLED) self.moduleUrlLabel.config(text="") self.moduleDateHdr.config(state=DISABLED) self.moduleDateLabel.config(text="") self.moduleLicenseHdr.config(state=DISABLED) self.moduleLicenseLabel.config(text="") self.moduleImportsHdr.config(state=DISABLED) self.moduleImportsLabel.config(text="") self.moduleEnableButton.config(state=DISABLED, text=self.ENABLE) self.moduleReloadButton.config(state=DISABLED) self.moduleRemoveButton.config(state=DISABLED) def findLocally(self): initialdir = self.cntlr.pluginDir # default plugin directory if not self.cntlr.isMac: # can't navigate within app easily, always start in default directory initialdir = self.cntlr.config.setdefault("pluginOpenDir", initialdir) filename = self.cntlr.uiFileDialog("open", parent=self, title=_("Choose plug-in module file"), initialdir=initialdir, filetypes=[(_("Python files"), "*.py")], defaultextension=".py") if filename: # check if a package is selected (any file in a directory containing an __init__.py #if (os.path.basename(filename) == "__init__.py" and os.path.isdir(os.path.dirname(filename)) and # os.path.isfile(filename)): # filename = os.path.dirname(filename) # refer to the package instead self.cntlr.config["pluginOpenDir"] = os.path.dirname(filename) moduleInfo = PluginManager.moduleModuleInfo(filename) self.loadFoundModuleInfo(moduleInfo, filename) def findOnWeb(self): url = DialogURL.askURL(self) if url: # url is the in-cache or local file moduleInfo = PluginManager.moduleModuleInfo(url) self.cntlr.showStatus("") # clear web loading status self.loadFoundModuleInfo(moduleInfo, url) def loadFoundModuleInfo(self, moduleInfo, url): if moduleInfo and moduleInfo.get("name"): self.addPluginConfigModuleInfo(moduleInfo) self.loadTreeViews() else: messagebox.showwarning(_("Module is not itself a plug-in or in a directory with package __init__.py plug-in. "), _("File does not itself contain a python program with an appropriate __pluginInfo__ declaration: \n\n{0}") .format(url), parent=self) def checkIfImported(self, moduleInfo): if moduleInfo.get("isImported"): messagebox.showwarning(_("Plug-in is imported by a parent plug-in. "), _("Plug-in has a parent, please request operation on the parent: \n\n{0}") .format(moduleInfo.get("name")), parent=self) return True return False def removePluginConfigModuleInfo(self, name): moduleInfo = self.pluginConfig["modules"].get(name) if moduleInfo: if self.checkIfImported(moduleInfo): return; def _removePluginConfigModuleInfo(moduleInfo): _name = moduleInfo.get("name") if _name: for classMethod in moduleInfo["classMethods"]: classMethods = self.pluginConfig["classes"].get(classMethod) if classMethods and _name in classMethods: classMethods.remove(_name) if not classMethods: # list has become unused del self.pluginConfig["classes"][classMethod] # remove class if classMethod.startswith("CntlrWinMain.Menu"): self.uiClassMethodsChanged = True # may require reloading UI elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses": self.modelClassesChanged = True # model object factor classes changed elif classMethod == "DisclosureSystem.Types": self.disclosureSystemTypesChanged = True # disclosure system types changed elif classMethod.startswith("Proxy."): self.hostSystemFeaturesChanged = True # system features (e.g., proxy) changed for importModuleInfo in moduleInfo.get("imports", EMPTYLIST): _removePluginConfigModuleInfo(importModuleInfo) self.pluginConfig["modules"].pop(_name, None) _removePluginConfigModuleInfo(moduleInfo) self.pluginConfigChanged = True def addPluginConfigModuleInfo(self, moduleInfo): if self.checkIfImported(moduleInfo): return; name = moduleInfo.get("name") self.removePluginConfigModuleInfo(name) # remove any prior entry for this module def _addPlugin(moduleInfo): _name = moduleInfo.get("name") if _name: self.modulesWithNewerFileDates.discard(_name) # no longer has an update available self.pluginConfig["modules"][_name] = moduleInfo # add classes for classMethod in moduleInfo["classMethods"]: classMethods = self.pluginConfig["classes"].setdefault(classMethod, []) if name not in classMethods: classMethods.append(_name) if classMethod.startswith("CntlrWinMain.Menu"): self.uiClassMethodsChanged = True # may require reloading UI elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses": self.modelClassesChanged = True # model object factor classes changed elif classMethod == "DisclosureSystem.Types": self.disclosureSystemTypesChanged = True # disclosure system types changed elif classMethod.startswith("Proxy."): self.hostSystemFeaturesChanged = True # system features (e.g., proxy) changed for importModuleInfo in moduleInfo.get("imports", EMPTYLIST): _addPlugin(importModuleInfo) _addPlugin(moduleInfo) self.pluginConfigChanged = True def moduleEnable(self): if self.selectedModule in self.pluginConfig["modules"]: moduleInfo = self.pluginConfig["modules"][self.selectedModule] if self.checkIfImported(moduleInfo): return; def _moduleEnable(moduleInfo): if self.moduleEnableButton['text'] == self.ENABLE: moduleInfo["status"] = "enabled" elif self.moduleEnableButton['text'] == self.DISABLE: moduleInfo["status"] = "disabled" for importModuleInfo in moduleInfo.get("imports", EMPTYLIST): _moduleEnable(importModuleInfo) _moduleEnable(moduleInfo) if self.moduleEnableButton['text'] == self.ENABLE: self.moduleEnableButton['text'] = self.DISABLE elif self.moduleEnableButton['text'] == self.DISABLE: self.moduleEnableButton['text'] = self.ENABLE self.pluginConfigChanged = True self.loadTreeViews() def moduleReload(self): if self.selectedModule in self.pluginConfig["modules"]: url = self.pluginConfig["modules"][self.selectedModule].get("moduleURL") if url: moduleInfo = PluginManager.moduleModuleInfo(url, reload=True) if moduleInfo: if self.checkIfImported(moduleInfo): return; self.addPluginConfigModuleInfo(moduleInfo) self.loadTreeViews() self.cntlr.showStatus(_("{0} reloaded").format(moduleInfo["name"]), clearAfter=5000) else: messagebox.showwarning(_("Module error"), _("File or module cannot be reloaded: \n\n{0}") .format(url), parent=self) def moduleRemove(self): if self.selectedModule in self.pluginConfig["modules"]: self.removePluginConfigModuleInfo(self.selectedModule) self.pluginConfigChanged = True self.loadTreeViews() def enableAll(self): self.enableDisableAll(True) def disableAll(self): self.enableDisableAll(False) def enableDisableAll(self, doEnable): for module in self.pluginConfig["modules"]: if not module.get("isImported"): moduleInfo = self.pluginConfig["modules"][module] def _enableDisableAll(moduleInfo): if doEnable: moduleInfo["status"] = "enabled" else: moduleInfo["status"] = "disabled" for importModuleInfo in moduleInfo.get("imports", EMPTYLIST): _enableDisableAll(importModuleInfo) _enableDisableAll(moduleInfo) if doEnable: self.moduleEnableButton['text'] = self.DISABLE else: self.moduleEnableButton['text'] = self.ENABLE self.pluginConfigChanged = True self.loadTreeViews()