def main(): root = Tk() root.geometry("600x185+200+200") app = MemberChecker(root) menubar = Menu(root) menubar.add_command(label="Clear log", command=app.clear_log) menubar.add_command(label="Load API data", command=app.load_data) root.config(menu=menubar) root.pack_slaves() root.mainloop()
def _init_menubar(self): menubar = Menu(self._top) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Print to Postscript', underline=0, command=self._cframe.print_to_file, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) zoommenu = Menu(menubar, tearoff=0) zoommenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) zoommenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) zoommenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) zoommenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=28, command=self.resize) zoommenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=50, command=self.resize) menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu) self._top.config(menu=menubar)
def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.parent.option_add('*tearOff', False) self.after(50, self.onAfter) #set this frame to expand to %100 available space self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) #init menu menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Save", command=self.onSave) fileMenu.add_command(label="Load", command=self.onLoad) fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=fileMenu) #init textbox self.text = ScrolledText(self, wrap='word') #add widgets to the layout manager self.text.grid(sticky=inflate)
class Example(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.master.title("Popup menu") self.menu = Menu(self.master, tearoff=0) self.menu.add_command(label="Beep", command=self.bell) self.menu.add_command(label="Exit", command=self.onExit) self.master.bind("<Button-3>", self.showMenu) self.pack() def showMenu(self, e): self.menu.post(e.x_root, e.y_root) def onExit(self): self.quit()
def BuildScriptMenu(self,parentmenu,modulename): from tkinter import Menu menu = Menu(parentmenu,bd=1,activeborderwidth=0) try: module = importlib.import_module('vmtk.'+modulename) except ImportError: return None scriptnames = [scriptname for scriptname in getattr(module, '__all__')] for index, scriptname in enumerate(scriptnames): # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user. if 'vmtk.' == scriptname[0:5]: splitList = scriptname.split('.') scriptnames[index] = splitList[1] else: continue menulength = 20 for i in range(len(scriptnames)//menulength+1): subscriptnames = scriptnames[i*menulength:(i+1)*menulength] if not subscriptnames: break submenu = Menu(menu,bd=1,activeborderwidth=0) menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu) for scriptname in subscriptnames: callback = CallbackShim(self.InsertScriptName,scriptname) submenu.add_command(label=scriptname,command=callback) return menu
def add_menubar(root): menubar = Menu(root) # file menu filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Load project", command=build_in_progress) filemenu.add_command(label="Save project", command=build_in_progress) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", menu=filemenu) # view menu viewmenu = Menu(menubar, tearoff=0) viewmenu.add_command(label="Progress", command=root.progress) viewmenu.add_command(label="Workflow", command=root.workflow) menubar.add_cascade(label="View", menu=viewmenu) # help menu helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Help", command=build_in_progress) helpmenu.add_separator() helpmenu.add_command(label="About", command=about) menubar.add_cascade(label="Help", menu=helpmenu) root.config(menu=menubar)
def handle_button_click(self, event): val = self.button_selected.get() - 1 val = self.radio_buttons.index(event.widget) if event.state & 0x001: # Shift key down self.x_flipped[val] = not self.x_flipped[val] try: raise IOError image_file = imget(self.img_lists[val][self.images_selected[val]]) import_image = Image.open(image_file) except IOError: image_file = imget_bdgp(self.img_lists[val][self.images_selected[val]]) import_image = Image.open(image_file) import_image = import_image.resize((180,80), Image.ANTIALIAS) import_image = import_image.rotate(180*self.x_flipped[val]) embryo_image = ImageTk.PhotoImage(import_image) label = Label(image=embryo_image) label.image = embryo_image self.radio_buttons[val].configure( #text=image_file, image=label.image, ) elif event.state & 0x004: # Control key down popup = Menu(root, tearoff=0) popup.add_command(label=self.radio_buttons[val].cget('text')) popup.add_separator() popup.add_command(label="Invert X") popup.add_command(label="Invert Y") try: popup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) popup.grab_release() elif val >= 0: self.images_selected[val] = ((self.images_selected[val] + 2*event.num - 3) % len(self.img_lists[val])) self.x_flipped[val] = False if self.images_selected[val] == 0: stdout.write('\a') stdout.flush() try: raise IOError image_file = imget(self.img_lists[val][self.images_selected[val]]) import_image = Image.open(image_file) except IOError: image_file = imget_bdgp(self.img_lists[val][self.images_selected[val]]) import_image = Image.open(image_file) import_image = import_image.resize((180,80), Image.ANTIALIAS) embryo_image = ImageTk.PhotoImage(import_image) label = Label(image=embryo_image) label.image = embryo_image self.radio_buttons[val].configure( #text=image_file, image=label.image, ) self.image_files[val] = image_file self.button_selected.set(-1)
def init_ui(self): """getting all things started""" self.parent.title("PyMeno") self.left_list.bind("<Double-Button-1>", self.on_double_click) self.parent.config(menu=self.menu_bar) file_menu = Menu(self.menu_bar, tearoff=False) menu2_parse = Menu(self.menu_bar, tearoff=False) # menu3_parse = Menu(menu_bar, tearoff=False) # sub_menu = Menu(file_menu, tearoff=False) self.left_list.pack(side=LEFT, fill=BOTH, expand=2) self.right_list.pack(side=RIGHT, fill=BOTH, expand=2) # add something to menu file_menu.add_command(label="Choose folder with music ALG 1", underline=0, command=self.new_thread_2) file_menu.add_command(label="Choose folder with music ALG 2", underline=0, command=self.new_thread_1) file_menu.add_command(label="Choose folder with music ALG 3", underline=0, command=self.new_thread_2) file_menu.add_command(label="Exit", underline=0, command=self.on_exit) menu2_parse.add_command(label="Download artists list", underline=0, command=self.db_creator.download_list_of_artists) menu2_parse.\ add_command(label="Parse artists information to database", underline=0, command=self.go_to_lilis_parsing) self.menu_bar.add_cascade(label="File", underline=0, menu=file_menu) self.menu_bar.add_cascade(label="Data", underline=0, menu=menu2_parse)
def __init__(self, master=None): Frame.__init__(self, master) self.pack(expand=1, fill='both') self.master.geometry('1440x900') paned_window = PanedWindow(self) self.treeview_kspelements = TreeviewKSPElements(self) self.treeview_kspobjects = TreeviewKSPObjects(self) paned_window.pack(expand=1, fill='both') paned_window.add(self.treeview_kspelements) paned_window.add(self.treeview_kspobjects) menubar = Menu(self) filemenu = Menu(self) filemenu.add_command(label='Open', command=self._open) filemenu.add_command(label='Save', command=self._save) filemenu.add_command(label='Save As', command=self._save_as) filemenu.add_separator() filemenu.add_command(label='Exit', command=self.master.destroy) menubar.add_cascade(menu=filemenu, label='File') insertmenu = Menu(self) insertmenu.add_command(label='KSP Element', command=self._insert_element, state='disabled') insertmenu.add_command(label='KSP Object', command=self._insert_object) menubar.add_cascade(menu=insertmenu, label='Insert') self.master.config(menu=menubar)
def viewRenderedGrid(modelXbrl, tabWin, lang=None): modelXbrl.modelManager.showStatus(_("viewing rendering")) view = ViewRenderedGrid(modelXbrl, tabWin, lang) view.blockMenuEvents = 1 menu = view.contextMenu() optionsMenu = Menu(view.viewFrame, tearoff=0) optionsMenu.add_command(label=_("New fact item options"), underline=0, command=lambda: getNewFactItemOptions(modelXbrl.modelManager.cntlr, view.newFactItemOptions)) optionsMenu.add_command(label=_("Open breakdown entry rows"), underline=0, command=view.setOpenBreakdownEntryRows) view.ignoreDimValidity.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("Ignore Dimensional Validity"), underline=0, variable=view.ignoreDimValidity, onvalue=True, offvalue=False) view.xAxisChildrenFirst.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("X-Axis Children First"), underline=0, variable=view.xAxisChildrenFirst, onvalue=True, offvalue=False) view.yAxisChildrenFirst.trace("w", view.viewReloadDueToMenuAction) optionsMenu.add_checkbutton(label=_("Y-Axis Children First"), underline=0, variable=view.yAxisChildrenFirst, onvalue=True, offvalue=False) menu.add_cascade(label=_("Options"), menu=optionsMenu, underline=0) view.tablesMenu = Menu(view.viewFrame, tearoff=0) menu.add_cascade(label=_("Tables"), menu=view.tablesMenu, underline=0) view.tablesMenuLength = 0 view.menuAddLangs() saveMenu = Menu(view.viewFrame, tearoff=0) saveMenu.add_command(label=_("HTML file"), underline=0, command=lambda: view.modelXbrl.modelManager.cntlr.fileSave(view=view, fileType="html")) saveMenu.add_command(label=_("Layout model"), underline=0, command=lambda: view.modelXbrl.modelManager.cntlr.fileSave(view=view, fileType="xml")) saveMenu.add_command(label=_("XBRL instance"), underline=0, command=view.saveInstance) menu.add_cascade(label=_("Save"), menu=saveMenu, underline=0) menu.add_command(label=_("Enter new facts..."), underline=0, command=view.enterNewFacts) view.view() view.blockSelectEvent = 1 view.blockViewModelObject = 0 view.viewFrame.bind("<Enter>", view.cellEnter, '+') view.viewFrame.bind("<Leave>", view.cellLeave, '+') view.viewFrame.bind("<1>", view.onClick, '+') view.blockMenuEvents = 0
def initUI(self): self.parent.title('PyZilla') self.padding = 5 self.pack(fill=BOTH, expand=1) # Create a menubar mnuMenu = Menu(self.parent) self.parent.config(menu=mnuMenu) # Create menubar mnuFileMenu = Menu(mnuMenu) # Add File menu items mnuFileMenu.add_command(label='Open', command=self.onBtnOpenFile) mnuFileMenu.add_command(label='Exit', command=self.quit) # Add File menu items to File menu mnuMenu.add_cascade(label='File', menu=mnuFileMenu) # Create frame for all the widgets frame = Frame(self) frame.pack(anchor=N, fill=BOTH) # Create file open dialog btnOpenFile = Button(frame, text="Load file", command=self.onBtnOpenFile) btnOpenFile.pack(side=RIGHT, pady=self.padding) # Create filename label self.lblFilename = Label(frame, text='No filename chosen...') self.lblFilename.pack(side=LEFT, pady=self.padding, padx=self.padding) # Create the text widget for the results self.txtResults = Text(self) self.txtResults.pack(fill=BOTH, expand=1, pady=self.padding, padx=self.padding)
class Example(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.master.title("Toolbar") menubar = Menu(self.master) self.fileMenu = Menu(self.master, tearoff=0) self.fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=self.fileMenu) toolbar = Frame(self.master, bd=1, relief=RAISED) self.img = Image.open("images.png") eimg = ImageTk.PhotoImage(self.img) exitButton = Button(toolbar, image=eimg, relief=FLAT, command=self.quit) exitButton.image = eimg exitButton.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) self.master.config(menu=menubar) self.pack() def onExit(self): self.quit()
class FrontEnd(Frame): def __init__(self, master, version): Frame.__init__(self, master) master.title(version[:-5]) # MAKE IT LOOK GOOD style = Style() style.configure("atitle.TLabel", font="tkDefaultFont 12 bold italic") # CREATE AND SET VARIABLES self.version = version self.description = None self.logo = None self.status_lbl = StringVar() # TO HOLD STATUS VARIABLE IN STATUSBAR # CREATE ROOT MENUBAR menubar = Menu(self.master) self.master["menu"] = menubar self.master.option_add("*tearOff", False) # CREATE FILE MENU self.menu_file = Menu(menubar, name="file") self.menu_file.add_separator() self.menu_file.add_command(label="Exit", accelerator="Alt-F4", command=self.master.destroy) menubar.add_cascade(menu=self.menu_file, label="File", underline=0) # CREATE HELP MENU menu_help = Menu(menubar, name="help") menu_help.add_command(label="About", command=self.show_about) menubar.add_cascade(menu=menu_help, label="Help", underline=0) # CREATE BUTTON BAR self.button_bar = Frame(self.master, relief="groove", padding="0 1 0 2") self.button_bar.grid(sticky="ew") # SETUP PRIMARY FRAME FOR WIDGETS self.frame = Frame(self.master, padding="25") self.frame.grid(sticky="nsew") # CREATE STATUS BAR Separator(self.master).grid(row=8, sticky="ew") self.status_bar = Frame(self.master, padding="8 0 0 1") self.status_bar.grid(row=9, sticky="ews") Label(self.status_bar, textvariable=self.status_lbl).grid(row=0, column=0, padx="0 7") Label(self.status_bar, text=self.version[-5:]).grid(row=0, column=8) Sizegrip(self.status_bar).grid(row=0, column=9, sticky="e") # CONFIGURE AUTO-RESIZING self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) self.frame.columnconfigure(0, weight=1) # self.frame.rowconfigure(0, weight=1) self.status_bar.columnconfigure(1, weight=1) def show_about(self): about = About(self.master, "About {}".format(self.version[:-5]), self.logo) Label(about.frame, text=self.version, style="atitle.TLabel").grid(sticky="w") Label(about.frame, text="Developer: Joel W. Dafoe").grid(pady="6", sticky="w") link = Link(about.frame, text="http://cyberdatx.com", foreground="blue", cursor="hand2") link.grid(sticky="w") link.bind("<Button-1>", lambda e: webbrowser.open("http://cyberdatx.com")) Label(about.frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky=W)
def contents_widget(self, text): "Create table of contents." toc = Menubutton(self, text='TOC') drop = Menu(toc, tearoff=False) for tag, lbl in text.parser.contents: drop.add_command(label=lbl, command=lambda mark=tag:text.see(mark)) toc['menu'] = drop return toc
def toc_menu(self, text): "Create table of contents as drop-down menu." toc = Menubutton(self, text='TOC') drop = Menu(toc, tearoff=False) for lbl, dex in text.parser.toc: drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex)) toc['menu'] = drop return toc
class DataEntry(object): def __init__(self, parent_frame, grid_col, grid_row, data): self._data = data self._parent = parent_frame self._frame = ttk.Frame(self._parent, borderwidth=2, relief='sunken') self._frame.grid(column=grid_col, row=grid_row) self._menu = Menu(master=self._parent, tearoff=0) self._menu.add_command(label='info', command=self.info_popup) self._should_plot = tk.BooleanVar() self._should_plot.set(False) def menu_popup(event): self._menu.post(event.x_root, event.y_root) self._chkbox = ttk.Checkbutton(self._frame, text="Plot", variable=self._should_plot, onvalue=True) self._chkbox.pack() self._button = ttk.Button(self._frame, text="{} -> {}".format(grid_row, grid_col), command=self.info_popup ) self._button.pack() self._button.bind('<Button-3>', menu_popup) @property def data(self): return self._data @property def should_plot(self): return self._should_plot.get() def info_popup(self): top = Toplevel() top.title("Info") frame = ttk.Frame(top) frame.pack() sourceLbl = ttk.Label(frame, text="Source") targetLbl = ttk.Label(frame, text="Target") sourceText = ttk.Label(frame, text=str(self._data._source), relief='sunken') targetText = ttk.Label(frame, text=str(self._data._target), relief='sunken') sourceLbl.grid(column=0, row=0) targetLbl.grid(column=1, row=0) sourceText.grid(column=0, row=1, padx=5, pady=5) targetText.grid(column=1, row=1, padx=5, pady=5)
def add_menus(self): menu_bar = Menu(self.root) stampede_menu = Menu(menu_bar, tearoff=0) stampede_menu.add_command(label="Settings", command=self.edit_default_settings) stampede_menu.add_separator() stampede_menu.add_command(label="Quit", command=self.root.quit) menu_bar.add_cascade(label="Stampede", menu=stampede_menu) self.root.config(menu=menu_bar)
def objectmakerMenuEntender(cntlr, menu, *args, **kwargs): # Extend menu with an item for the savedts plugin drawDiagMenu = Menu(cntlr.menubar, tearoff=0) menu.add_cascade(label="Draw Diagram", underline=0, menu=drawDiagMenu) drawDiagMenu.add_command(label=_("DTS"), underline=0, command=lambda: objectmakerMenuCommand(cntlr, "dts") ) drawDiagMenu.add_command(label=_("Presentation"), underline=0, command=lambda: objectmakerMenuCommand(cntlr, "pre") ) drawDiagMenu.add_command(label=_("Calculation"), underline=0, command=lambda: objectmakerMenuCommand(cntlr, "cal") ) drawDiagMenu.add_command(label=_("Definition"), underline=0, command=lambda: objectmakerMenuCommand(cntlr, "def") ) drawDiagMenu.add_command(label=_("UML"), underline=0, command=lambda: objectmakerMenuCommand(cntlr, "uml") )
def _init_menubar(self): self._result_size = IntVar(self.top) self._cntx_bf_len = IntVar(self.top) self._cntx_af_len = IntVar(self.top) menubar = Menu(self.top) filemenu = Menu(menubar, tearoff=0, borderwidth=0) filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q") menubar.add_cascade(label="File", underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) rescntmenu = Menu(editmenu, tearoff=0) rescntmenu.add_radiobutton( label="20", variable=self._result_size, underline=0, value=20, command=self.set_result_size ) rescntmenu.add_radiobutton( label="50", variable=self._result_size, underline=0, value=50, command=self.set_result_size ) rescntmenu.add_radiobutton( label="100", variable=self._result_size, underline=0, value=100, command=self.set_result_size ) rescntmenu.invoke(1) editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu) cntxmenu = Menu(editmenu, tearoff=0) cntxbfmenu = Menu(cntxmenu, tearoff=0) cntxbfmenu.add_radiobutton( label="60 characters", variable=self._cntx_bf_len, underline=0, value=60, command=self.set_cntx_bf_len ) cntxbfmenu.add_radiobutton( label="80 characters", variable=self._cntx_bf_len, underline=0, value=80, command=self.set_cntx_bf_len ) cntxbfmenu.add_radiobutton( label="100 characters", variable=self._cntx_bf_len, underline=0, value=100, command=self.set_cntx_bf_len ) cntxbfmenu.invoke(1) cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu) cntxafmenu = Menu(cntxmenu, tearoff=0) cntxafmenu.add_radiobutton( label="70 characters", variable=self._cntx_af_len, underline=0, value=70, command=self.set_cntx_af_len ) cntxafmenu.add_radiobutton( label="90 characters", variable=self._cntx_af_len, underline=0, value=90, command=self.set_cntx_af_len ) cntxafmenu.add_radiobutton( label="110 characters", variable=self._cntx_af_len, underline=0, value=110, command=self.set_cntx_af_len ) cntxafmenu.invoke(1) cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu) editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu) menubar.add_cascade(label="Edit", underline=0, menu=editmenu) self.top.config(menu=menubar)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) menubar = Menu(self) filemenu = Menu(menubar,tearoff=0) filemenu.add_command(label="New",) filemenu.add_command(label="Open",) filemenu.add_command(label="Save As..") filemenu.add_command(label="Colour") filemenu.add_command(label="Close") menubar.add_cascade(label="File",menu=filemenu) controller.configure(menu = menubar)
def add_menu(self): top = self.root top["menu"] = menubar = Menu(top) menu_file = Menu(menubar) menu_settings = Menu(menubar) menu_help = Menu(menubar) menubar.add_cascade(menu=menu_file, label=_("File")) menubar.add_cascade(menu=menu_settings, label=_("Settings")) menubar.add_cascade(menu=menu_help, label=_("Help")) menu_settings.add_command(label=_("Pannel Settings"), command=self.dlg_panset)
def init_menubar(self): """ Creates the menubar. Called once on startup. The rendering of the menubar is operating-system dependent (Windows renders it inside the app window, OS X renders it in the OS menubar). """ menubar = Menu(self.window) game_menu = Menu(menubar, tearoff=0) game_menu.add_command( label='New (Easy)', command=lambda: self.start_new_game('easy')) game_menu.add_command( label='New (Intermediate)', command=lambda: self.start_new_game('intermediate')) game_menu.add_command( label='New (Advanced)', command=lambda: self.start_new_game('advanced')) game_menu.add_command( label='New (Custom)', command=lambda: self.start_new_game('custom')) menubar.add_cascade(label='Game', menu=game_menu) # finally add the menubar to the root window self.window.config(menu=menubar) self.ui_elements += [menubar, game_menu]
def initUI(self, server): self.parent.title("TrackWise Service Manager") self.pack(fill=BOTH, expand = True, padx = 300) # self.centerWindow() menubar = Menu(self.parent) self.parent.config(menu = menubar) fileMenu = Menu(menubar) fileMenu.add_command(label = "Exit", command = self.onExit) menubar.add_cascade(label = "File", menu = fileMenu) svcsMenu = Menu(menubar) svcsMenu.add_command(label = "List Service Status", command = self.onStatus) svcsMenu.add_command(label = "Stop Services", command = self.onStop) svcsMenu.add_command(label = "Start Services", command = self.onStart) menubar.add_cascade(label = "Services", menu = svcsMenu) # svcs = ['TrackWise Tomcat', 'Web Services Tomcat', 'QMD Tomcat', 'Keystone Intake', 'ID Intake', 'TWC'] svcs = server.getservices() hostname = server.gethostname().strip() servertype = server.gettype().strip() frame0 = Labelframe(self, text = "Server Details", borderwidth = 1) frame0.grid(column = 0, row = 0, sticky = W) so = StringVar() svroverview = Message(frame0, textvariable = so, anchor = W, width = 300) svroverview.grid(column = 0, row = 0) sstr = "Server: {}\n".format(hostname) sstr += "Server Type: {}".format(servertype) so.set(sstr) frame1 = Labelframe(self, text = "Service Status", borderwidth = 1) frame1.grid(column = 0, row = 1, sticky = W) l = StringVar() label1 = Message(frame1, textvariable = l , anchor = W) svcscount = 0 lstr = "" for i in svcs: svcscount += 1 lstr += '{} - '.format(i) + ('UP\n' if svcscount % 2 else 'DOWN\n') l.set(lstr) label1.pack(side=TOP, padx = 5, pady = 5) frame4 = Frame(self, relief=RAISED, borderwidth = 1) frame4.grid(column = 0, row = 2, sticky = W) closeButton = Button(frame4, text="Close", command = self.quit) closeButton.grid(column = 0, row = 0) okButton = Button(frame4, text = "OK") okButton.grid(column = 1, row = 0)
def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="q") menubar.add_cascade(label="File", underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label="Next", underline=0, command=self.next, accelerator="n, Space") actionmenu.add_command(label="Previous", underline=0, command=self.prev, accelerator="p, Backspace") menubar.add_cascade(label="Action", underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton( label="Remove Duplicates", underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator="r", ) menubar.add_cascade(label="Options", underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label="View", underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", underline=0, command=self.about) menubar.add_cascade(label="Help", underline=0, menu=helpmenu) parent.config(menu=menubar)
def initUI(self): self.parent.title("File dialog") self.pack(fill=BOTH, expand=1) menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Open", command=self.onOpen) menubar.add_cascade(label="File", menu=fileMenu) self.txt = Text(self) self.txt.pack(fill=BOTH, expand=1)
def __init__(self, master, version): Frame.__init__(self, master) master.title(version[:-5]) # MAKE IT LOOK GOOD style = Style() style.configure("atitle.TLabel", font="tkDefaultFont 12 bold italic") # CREATE AND SET VARIABLES self.version = version self.description = None self.logo = None self.status_lbl = StringVar() # TO HOLD STATUS VARIABLE IN STATUSBAR # CREATE ROOT MENUBAR menubar = Menu(self.master) self.master["menu"] = menubar self.master.option_add("*tearOff", False) # CREATE FILE MENU self.menu_file = Menu(menubar, name="file") self.menu_file.add_separator() self.menu_file.add_command(label="Exit", accelerator="Alt-F4", command=self.master.destroy) menubar.add_cascade(menu=self.menu_file, label="File", underline=0) # CREATE HELP MENU menu_help = Menu(menubar, name="help") menu_help.add_command(label="About", command=self.show_about) menubar.add_cascade(menu=menu_help, label="Help", underline=0) # CREATE BUTTON BAR self.button_bar = Frame(self.master, relief="groove", padding="0 1 0 2") self.button_bar.grid(sticky="ew") # SETUP PRIMARY FRAME FOR WIDGETS self.frame = Frame(self.master, padding="25") self.frame.grid(sticky="nsew") # CREATE STATUS BAR Separator(self.master).grid(row=8, sticky="ew") self.status_bar = Frame(self.master, padding="8 0 0 1") self.status_bar.grid(row=9, sticky="ews") Label(self.status_bar, textvariable=self.status_lbl).grid(row=0, column=0, padx="0 7") Label(self.status_bar, text=self.version[-5:]).grid(row=0, column=8) Sizegrip(self.status_bar).grid(row=0, column=9, sticky="e") # CONFIGURE AUTO-RESIZING self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) self.frame.columnconfigure(0, weight=1) # self.frame.rowconfigure(0, weight=1) self.status_bar.columnconfigure(1, weight=1)
def _createMenu(self): """ Create the menu """ menubar = Menu(self.parent) self.parent.config(menu=menubar) # File Menu mnuFile = Menu(menubar) mnuFile.add_command(label="Exit", underline=1, command=self._onMenuFileExit) menubar.add_cascade(label="File", underline=0, menu=mnuFile) # Help Menu mnuHelp = Menu(menubar) mnuHelp.add_command(label="About", underline=0, command=self._onMenuHelpAbout) menubar.add_cascade(label="Help", underline=0, menu=mnuHelp)
def main(): '''Makes the application ''' root = Tk() app = Application(master=root) app.master.title("Password Generator") root.minsize(500, 500) root.maxsize(600, 600) menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", command=root.destroy) menubar.add_cascade(label="File", menu=filemenu) root.config(bg='#2A2C2B', menu=menubar) app.mainloop()
def make_menu(self): menu = Menu(self) file_menu = Menu(menu, tearoff=0) file_menu.add_command(label='Exit', command=self.ask_for_quiting) help_menu = Menu(menu, tearoff=0) help_menu.add_command(label='About', command=lambda: messagebox.showinfo('Calendar', 'By Fedor')) menu.add_cascade(label='File', menu=file_menu) menu.add_cascade(label='Help', menu=help_menu) return menu
def __init__(self): super().__init__() self.title('Hangman') self.geometry('640x480+200+200') self.resizable(width=False, height=False) menu_bar = Menu(self, tearoff=0) self.config(menu=menu_bar) game_menu = Menu(menu_bar, tearoff=0) game_menu.add_command(label='New game', command=self.__on_new_game) game_menu.add_command(label='Quit', command=self.__on_quit) menu_bar.add_cascade(label='Game', menu=game_menu) self.__hang_canvas = Canvas(self, background='#ffffff') self.__hang_canvas.pack(fill=BOTH, expand=True) self.__dict_filename = os.path.join(os.path.dirname(__file__), 'dictionary.txt') self.__dictionary = [] self.__secret_word_masked = StringVar() self.__game_stages = ( # (is_circle, x1, y1, x2, y2), (False, 50, 300, 200, 300), # podstawa (False, 60, 300, 60, 10), # maszt (False, 60, 10, 160, 10), (False, 60, 30, 100, 10), (False, 160, 10, 160, 30), (True, 140, 30, 180, 70), (False, 160, 70, 160, 200), # tułów (False, 140, 120, 160, 70), # lewa reka (False, 180, 120, 160, 70), # prawa ręka (False, 160, 200, 140, 250), (False, 160, 200, 180, 250) ) self.__errors_count = 0 secret_word_label = Label(self, font=('purisa', 36), textvariable=self.__secret_word_masked) secret_word_label.pack(fill=X) # user input panel Label(self, text='Please input a char:').pack(fill=X) self.__user_input_char = StringVar() user_input_entry = Entry(self, textvariable=self.__user_input_char) user_input_entry.bind('<Return>', self.__on_user_input) user_input_entry.pack() self.__load_dictionary() self.__new_game()
def _quit(): win.quit() win.destroy() exit() def _msgBox(): answer = messagebox.askyesnocancel("Python Message Multi Choice Box", "Make the choice:") print(answer) if answer is True: messagebox.showinfo('Message Info Box', 'YES is the Chosen One.') elif answer is False: messagebox.showwarning('Message Warning Box', 'NO is the chosen One.') else: messagebox.showerror('Message Error Box', 'Cancel is the chosen One.') menu_bar = Menu(win) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=_quit) menu_bar.add_cascade(label="File", menu=file_menu) help_menu = Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label="Help", menu=help_menu) help_menu.add_command(label="About", command=_msgBox) win.config(menu=menu_bar) win.mainloop()
def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del") filemenu.add_command( label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p", ) filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x") menubar.add_cascade(label="File", underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command( label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g", ) editmenu.add_command( label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t", ) menubar.add_cascade(label="Edit", underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space") rulemenu.add_separator() rulemenu.add_command(label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s") rulemenu.add_command(label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r") rulemenu.add_separator() rulemenu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u") menubar.add_cascade(label="Apply", underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton( label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar, ) viewmenu.add_separator() viewmenu.add_radiobutton( label="Tiny", variable=self._size, underline=0, value=10, command=self.resize, ) viewmenu.add_radiobutton( label="Small", variable=self._size, underline=0, value=12, command=self.resize, ) viewmenu.add_radiobutton( label="Medium", variable=self._size, underline=0, value=14, command=self.resize, ) viewmenu.add_radiobutton( label="Large", variable=self._size, underline=0, value=18, command=self.resize, ) viewmenu.add_radiobutton( label="Huge", variable=self._size, underline=0, value=24, command=self.resize, ) menubar.add_cascade(label="View", underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0) animatemenu.add_radiobutton( label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator="-", ) animatemenu.add_radiobutton( label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator="=", ) animatemenu.add_radiobutton( label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator="+", ) menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", underline=0, command=self.about) helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1") menubar.add_cascade(label="Help", underline=0, menu=helpmenu) parent.config(menu=menubar)
class Main(tk.Tk): # Main definition def __init__(self): super().__init__() # Global variables in class self.tab_counter = 1 self.array_tabs = [] self.array_canvas = [] self.array_name = [] self.search_list = list() self.active_file = "" self.DATA_TYPES_BLUE = [ "CREATE", "create", "SHOW", "show", "USE", "use", "ALTER", "alter", "DROP", "drop" ] self.KEYWORDS_FUNCTIONS = ["DATABASE", "database"] self.SPACES_REGEX = re.compile("^\s*") self.STRING_REGEX_SINGLE = re.compile("'[^'\r\n]*'") self.STRING_REGEX_DOUBLE = re.compile('"[^"\r\n]*"') self.NUMBER_REGEX = re.compile(r"\b(?=\(*)\d+\.?\d*(?=\)*\,*)\b") self.KEYWORDS_REGEX = re.compile( "(?=\(*)(?<![a-z])(None|True|False)(?=\)*\,*)") self.SELF_REGEX = re.compile("(?=\(*)(?<![a-z])(self)(?=\)*\,*)") self.FUNCTIONS_REGEX = re.compile( "(?=\(*)(?<![a-z])(print|list|dict|set|int|str)(?=\()") self.REGEX_TO_TAG = { self.STRING_REGEX_SINGLE: "string", self.STRING_REGEX_DOUBLE: "string", self.NUMBER_REGEX: "digit", self.KEYWORDS_REGEX: "keywordcaps", self.SELF_REGEX: "keyword1", self.FUNCTIONS_REGEX: "keywordfunc", } # Properties of the window ------------------------------------------------- self.title("Tytus DB - Grupo 5") self.geometry("1200x800") self.minsize(800, 800) self.maxsize(1200, 800) # Menu Widget self.menu_bar = Menu() # Submenu [File] self.sm_file = Menu(self.menu_bar, tearoff=False) self.sm_file.add_command(label="Nueva pestaña", command=lambda: self.file_new_tab()) self.sm_file.add_command(label="Abrir", command=lambda: self.file_open()) self.sm_file.add_command(label="Guardar", command=lambda: self.file_save()) self.sm_file.add_command(label="Guardar como", command=lambda: self.file_save_as()) self.sm_file.add_command(label="Cerrar pestaña", command=lambda: self.file_close_tab()) self.sm_file.add_command(label="Salir", command=lambda: self.exit_program()) self.menu_bar.add_cascade(label="Archivo", menu=self.sm_file) # Submenu [Edit] self.sm_edit = Menu(self.menu_bar, tearoff=False) self.sm_edit.add_command(label="Copiar", command=lambda: self.edit_copy()) self.sm_edit.add_command(label="Cortar", command=lambda: self.edit_cut()) self.sm_edit.add_command(label="Pegar", command=lambda: self.edit_paste()) self.sm_edit.add_command(label="Buscar", command=lambda: self.edit_search()) self.sm_edit.add_command(label="Reemplazar", command=lambda: self.edit_replace()) self.menu_bar.add_cascade(label="Edicion", menu=self.sm_edit) # Submenu [Analysis] self.sm_analyze = Menu(self.menu_bar, tearoff=False) self.sm_analyze.add_command(label="Ejecutar", command=lambda: self.tytus_ejecutar()) self.sm_analyze.add_command(label="Cerrar pestaña", command=lambda: self.close_output_tab()) self.sm_analyze.add_command(label="Cerrar pestañas", command=lambda: self.delete_outputs()) self.menu_bar.add_cascade(label="Queries", menu=self.sm_analyze) # Submenu [Reports] self.sm_report = Menu(self.menu_bar, tearoff=False) self.sm_report.add_command(label="Reporte Léxico", command=lambda: self.report_lexic()) self.sm_report.add_command(label="Reporte Sintáctico", command=lambda: self.report_syntactic()) self.sm_report.add_command(label="Reporte Semántico", command=lambda: self.report_semantic()) self.sm_report.add_command(label="Reporte Tabla de Simbolos", command=lambda: self.report_st()) self.sm_report.add_command(label="Reporte AST", command=lambda: self.ast_report()) self.menu_bar.add_cascade(label="Reportes", menu=self.sm_report) # Submenu [Help] self.sm_help = Menu(self.menu_bar, tearoff=False) self.sm_help.add_command(label="Ayuda") self.sm_help.add_command(label="Acerca de", command=lambda: self.help_about_it()) self.menu_bar.add_cascade(label="Ayuda", menu=self.sm_help) # Input Frame & Widget self.in_frame = Frame(self) self.in_frame.pack(fill="both", pady=5, expand=1) self.ta_input = Notebook(self.in_frame, width=150, height=20) self.ta_input.pack(fill="both", expand=1) # Output Frame & Widget self.out_frame = Frame(self) self.out_frame.pack(fill="both", pady=5, expand=1) self.ta_output = Notebook(self.out_frame, width=150, height=15) self.ta_output.pack(fill="both", expand=1) # Menu Configuration self.config(menu=self.menu_bar) # Opening first tab self.file_new_tab() def _on_change(self, event): index = self.ta_input.index(self.ta_input.select()) canvas = self.array_canvas[index] canvas.redraw() del index, canvas # New output tab def new_output(self, output=""): try: # Creando nueva tab tab1 = Frame(self.ta_output) self.ta_output.add(tab1, text="SALIDA") self.ta_output.pack(expand=1, fill="both") # Creando campo de texto text = ln.TextAreaWidget(tab1, bg="black", fg="white", width=150, height=15) text.pack(side="right", fill="both", expand=True) text.insert(END, output) del text except: messagebox.showerror( "A OCURRIDO UN ERROR", "No se ha podido crear una nueva pestaña. Por favor, intente nuevamente." ) # Close output tab def close_output_tab(self): try: # Getting selected tab & deleting it index = self.ta_output.index(self.ta_output.select()) self.ta_output.forget(index) del index except: pass # Delete outputs def delete_outputs(self): try: _list = self.ta_output.winfo_children() for item in _list: if item.winfo_children(): self.ta_output.forget(item) del _list except: pass # New tab with custom text widget def file_new_tab(self): try: # Creating the tab tab1 = Frame(self.ta_input) self.ta_input.add(tab1, text="Tab " + str(self.tab_counter)) self.ta_input.pack(expand=1, fill="both") # Creating text input text = ln.TextAreaWidget(tab1) text.bind("<KeyRelease>", self.tag_keywords) text.tag_config("keyword1", foreground="blue") text.tag_config("keywordfunc", foreground="darkgrey") line_numbers = ln.LineNumber(tab1, width=30) line_numbers.attach(text) line_numbers.pack(side="left", fill="y") text.pack(side="right", fill="both", expand=True) text.bind("<<Change>>", self._on_change) text.bind("<Configure>", self._on_change) self.array_tabs.append(text) self.array_name.append("Tab " + str(self.tab_counter)) self.array_canvas.append(line_numbers) self.tab_counter += 1 del tab1, text, line_numbers except: messagebox.showerror( "A OCURRIDO UN ERROR", "No se ha podido crear una nueva pestaña. Por favor, intente nuevamente." ) # Open new file with .txt extension def file_open(self): try: # Getting file name & content filename = filedialog.askopenfilename( initialdir="/", title="Select file", filetypes=(("Archivos de Texto", "*.txt"), ("Todos los archivos", "*.*"))) a_file = open(filename) txt_input = a_file.read() file_title = os.path.basename(a_file.name) # Creating the tab tab1 = Frame(self.ta_input) self.ta_input.add(tab1, text=file_title) self.ta_input.pack(expand=1, fill="both") # Creating the text area text = ln.TextAreaWidget(tab1) text.insert(END, txt_input) line_numbers = ln.LineNumber(tab1, width=30) line_numbers.attach(text) line_numbers.pack(side="left", fill="y") text.pack(side="right", fill="both", expand=True) text.bind("<<Change>>", self._on_change) text.bind("<Configure>", self._on_change) self.array_tabs.append(text) self.array_name.append(a_file.name) self.array_canvas.append(line_numbers) self.tab_counter += 1 a_file.close() del filename, a_file, tab1, text, line_numbers except: pass # Save opened file def file_save(self): try: # Getting text from tab and file path index = self.ta_input.index(self.ta_input.select()) txt_input = self.array_tabs[index].get("1.0", END) txt_filepath = self.array_name[index] if os.path.exists(txt_filepath): a_file = open(txt_filepath, "r+") a_file.write(txt_input) a_file.close() else: self.file_save_as() messagebox.showinfo("INFO", "El archivo ha sido guardado exitosamente") del index, txt_input, txt_filepath, a_file except: messagebox.showerror( "A OCURRIDO UN ERROR", "No se ha podido guardar. Por favor, intente nuevamente.") # Save as new file def file_save_as(self): try: # Getting text from tab index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index].get("1.0", END) # Path of new file file = filedialog.asksaveasfile(initialdir="/", title="Select file", filetypes=(("Archivos de Texto", "*.txt"), ("Todos los archivos", "*.*"))).name if not ".txt" in file: file += ".txt" # Creating file a_file = open(file, "w+") a_file.write(input_text) a_file.close() messagebox.showinfo("INFO", "El archivo ha sido guardado exitosamente") del index, input_text, file, a_file except: messagebox.showerror( "A OCURRIDO UN ERROR", "No se tiene seleccionada una pestaña para guardar. Por favor, intente nuevamente." ) # Exit tab def file_close_tab(self): try: # Getting selected tab & deleting it index = self.ta_input.index(self.ta_input.select()) self.ta_input.forget(index) del self.array_name[index] del self.array_tabs[index] del index except: pass # Exiting IDE def exit_program(self): self.destroy() # Copy option def edit_copy(self, event=None): self.clipboard_clear() index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index] text = input_text.get("sel.first", "sel.last") self.clipboard_append(text) del index, input_text, text # Cut option def edit_cut(self): self.edit_copy() index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index] input_text.delete("sel.first", "sel.last") del index, input_text # Paste option def edit_paste(self): index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index] text = self.selection_get(selection='CLIPBOARD') input_text.insert('insert', text) del index, input_text, text # Search word option def edit_search(self): # Getting the word to search word = askstring('Buscar palabra', '¿Qué palabra desea buscar?') # Getting the input widget index = self.ta_input.index(self.ta_input.select()) input_widget = self.array_tabs[index] input_text = input_widget.get("1.0", END) # Reset list self.search_list.clear() input_widget.tag_remove(SEL, 1.0, "end-1c") # Searching word input_widget.focus_set() if word: if not self.search_list: idx = "1.0" else: idx = self.search_list[-1] idx = input_widget.search(word, idx, nocase=1, stopindex=END) lastidx = '%s+%dc' % (idx, len(word)) try: input_widget.tag_remove(SEL, 1.0, lastidx) except: pass try: input_widget.tag_add(SEL, idx, lastidx) counter_list = [] counter_list = str(idx).split('.') input_widget.mark_set( "insert", "%d.%d" % (float(int(counter_list[0])), float(int(counter_list[1])))) input_widget.see(float(int(counter_list[0]))) self.search_list.append(lastidx) except: messagebox.showinfo("Busqueda completada", "No hay coincidencias.") self.search_list.clear() input_widget.tag_remove(SEL, 1.0, "end-1c") del word, index, input_widget, input_text, idx, lastidx, counter_list # Replace word option def edit_replace(self): # Getting the words to search and replace word = askstring('Reemplazar palabra', '¿Qué palabra desea reemplazar?') replace = askstring('Nueva palabra', 'Nuevo valor para \'' + word + '\'') # Getting the input widget index = self.ta_input.index(self.ta_input.select()) input_widget = self.array_tabs[index] input_text = input_widget.get("1.0", END) # Reset list self.search_list.clear() input_widget.tag_remove(SEL, 1.0, "end-1c") # Searching word input_widget.focus_set() if word: if not self.search_list: idx = "1.0" else: idx = self.search_list[-1] idx = input_widget.search(word, idx, nocase=1, stopindex=END) lastidx = '%s+%dc' % (idx, len(word)) try: input_widget.tag_remove(SEL, 1.0, lastidx) except: pass try: input_widget.delete(idx, lastidx) input_widget.insert(idx, replace) except: messagebox.showinfo("Busqueda completada", "No hay coincidencias para reemplazar.") self.search_list.clear() input_widget.tag_remove(SEL, 1.0, "end-1c") del word, index, input_widget, input_text, idx, lastidx # Lexic report def report_lexic(self): if os.path.exists("reports/reporte_lexico.html"): os.remove("reports/reporte_lexico.html") if os.path.exists("reports/error_lexical.txt"): report = open("reports/reporte_lexico.html", "a") file1 = open("reports/inicio_error_lexico.txt", "r") file2 = open("reports/error_lexical.txt", "r") file3 = open("reports/fin_error.txt", "r") report.write(file1.read()) report.write(file2.read()) report.write(file3.read()) report.close() webbrowser.open('file://' + os.path.realpath("reports/reporte_lexico.html")) else: messagebox.showerror("INFO", "No exite un archivo de reporte.") # Syntactic report def report_syntactic(self): if os.path.exists("reports/reporte_sintactico.html"): os.remove("reports/reporte_sintactico.html") if os.path.exists("reports/error_syntactic.txt"): report = open("reports/reporte_sintactico.html", "a") file1 = open("reports/inicio_error_sintactico.txt", "r") file2 = open("reports/error_syntactic.txt", "r") file3 = open("reports/fin_error.txt", "r") report.write(file1.read()) report.write(file2.read()) report.write(file3.read()) report.close() webbrowser.open( 'file://' + os.path.realpath("reports/reporte_sintactico.html")) else: messagebox.showerror("INFO", "No exite un archivo de reporte.") # Semantic report def report_semantic(self): pass # ST report def report_st(self): pass # AST report def ast_report(self): pass # About it section def help_about_it(self): messagebox.showinfo( "Tytus DB", "Organización de Lenguajes y Compiladores 2\n" "Proyecto Fase 1\n\n" "201213062 - Mónica Raquel Calderon Muñoz\n" "201213223 - Astrid Edith Hernandez Gonzalez\n" "201213255 - Leonel Eduardo Avila Calvillo\n" "201220159 - Diego Ahtohil Noj Armira\n" "201220165 - Oscar Rolando Bernard Peralta") # Highlight of MinorC words def tag_keywords(self, event=None, current_index=None): if not (event.keysym == "Home" or event.keysym == "Shift_L"): # Getting selected tab's widget index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index] # Getting position of last letter written if not current_index: current_index = input_text.index(tk.INSERT) line_number = current_index.split(".")[0] line_beginning = ".".join([line_number, "0"]) line_text = input_text.get(line_beginning, line_beginning + " lineend") line_words = line_text.split() number_of_spaces = self.number_of_leading_spaces(line_text) y_position = number_of_spaces for tag in input_text.tag_names(): input_text.tag_remove(tag, line_beginning, line_beginning + " lineend") self.add_regex_tags(line_number, line_text) for word in line_words: stripped_word = word.strip("():,") word_start = str(y_position) word_end = str(y_position + len(stripped_word)) start_index = ".".join([line_number, word_start]) end_index = ".".join([line_number, word_end]) if stripped_word in self.DATA_TYPES_BLUE: input_text.tag_add("keyword1", start_index, end_index) y_position += len(word) + 1 # Number of leading spaces def number_of_leading_spaces(self, line): spaces = re.search(self.SPACES_REGEX, line) if spaces.group(0) is not None: number_of_spaces = len(spaces.group(0)) else: number_of_spaces = 0 return number_of_spaces # Add regex tags def add_regex_tags(self, line_number, line_text): # Getting selected tab's widget index = self.ta_input.index(self.ta_input.select()) input_text = self.array_tabs[index] # for regex, tag in self.REGEX_TO_TAG.items(): for match in regex.finditer(line_text): start, end = match.span() start_index = ".".join([line_number, str(start)]) end_index = ".".join([line_number, str(end)]) input_text.tag_add(tag, start_index, end_index) def do_nothing(self, event=None): if not (event.keysym == "Home" or event.keysym == "Shift_L"): print(event.keysym) # Ejecución de Parser def tytus_ejecutar(self): # Getting widget index = self.ta_input.index(self.ta_input.select()) ta_input = self.array_tabs[index] # Delete old lexical report if os.path.exists("reports/error_lexical.txt"): os.remove("reports/error_lexical.txt") # Delete old syntactic report if os.path.exists("reports/error_syntactic.txt"): os.remove("reports/error_syntactic.txt") # Delete old semantic report if os.path.exists("reports/error_semantic.txt"): os.remove("reports/error_semantic.txt") if ta_input.compare("end-1c", "!=", "1.0"): # Gets new input tytus = ta_input.get(1.0, END) # Start parser ins = g.parse(tytus) st_global = st.SymbolTable() if not ins: messagebox.showerror( "ERROR", "Ha ocurrido un error. Verificar reportes.") else: self.do_body(ins, st_global) else: messagebox.showerror("INFO", "El campo de entrada esta vacío.") # EJECUCIÓN DE ANÁLISIS - PARSER -------------------------- def do_body(self, p_instruccion, p_st): if not p_instruccion: messagebox.showerror( "Tytus DB", "Ha ocurrido un problema en la ejecución del programa. Revisar los reportes de errores. " ) return for inst in p_instruccion: if isinstance(inst, CreateDatabase): self.do_create_database(inst, p_st) elif isinstance(inst, UseDatabase): self.do_use(inst, p_st) elif isinstance(inst, DropDB): self.do_drop_db(inst, p_st) # elif isinstance(inst, CreateType): # self.do_create_type(inst, p_st) elif isinstance(inst, SelectCompleto): self.do_select(inst, p_st) else: print(inst) print("--- ANÁLISIS TERMINADO ---") # USO DE BASE DE DATOS def do_use(self, p_inst, p_st): print('USAR BASE DE DATOS') print('Nombre: ' + p_inst.nombre) print() # CREACIÓN DE BASE DE DATOS def do_create_database(self, p_inst, p_st): print('CREAR BASE DE DATOS') print('Nombre: ' + p_inst.datos.nombre) if p_inst.replace: print('Reemplazar: SI') else: print('Reemplazar: NO') if p_inst.datos.noexiste: print('Comprobar si no existe?: SI') else: print('Comprobar si no existe?: NO') if p_inst.datos.datos is not None: if p_inst.datos.datos.owner is not None: print('Owner: ' + p_inst.datos.datos.owner) if p_inst.datos.datos.mode is not None: print('Mode: ' + str(p_inst.datos.datos.mode)) print() # ELIMINACIÓN DE BASE DE DATOS def do_drop_db(self, p_inst, p_st): print('ELIMINAR BASE DE DATOS') print('Nombre: ' + p_inst.ifexist.nombre) print() # CREACIÓN DE LISTADO DE TIPOS def do_create_type(self, p_inst, p_st): print('CREACIÓN DE LISTADO DE TIPOS') print('Nombre: ' + p_inst.nombre) print('Items: ' + str(p_inst.listado)) print() # SELECT def do_select(self, p_inst, p_st): print('SELECT EN TABLA') print()
MissionEditorIndex.missionTeacherYObj], Sdata[i][j].Data[ MissionEditorIndex.missionSpecialItemObj], Sdata[i][j].Data[ MissionEditorIndex.missionSpecialDesObj] ]) exportIDHead += 1 # Creating a Menu Bar menu_bar = Menu(win) win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="匯出", command=ExportData) file_menu.add_separator() file_menu.add_command(label="Exit", command=_quit) menu_bar.add_cascade(label="File", menu=file_menu) # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label="About") menu_bar.add_cascade(label="Help", menu=help_menu) # ====================== # 初始化資料 DeclareVar() ImportData() GentGridPanel() GenPageSelectPanel()
def __init__(self): ##############################################VENTANA PRINCIPAL#################################### self.window = Tk() #self.window.configure(background="#04DE5E") img = PhotoImage(file='img/icons/postgesql2.png') self.window.tk.call('wm', 'iconphoto', self.window._w, img) #img = PhotoImage(file='img/icons/Postgresql.ico') #self.window.tk.call('wm', 'iconphoto', self.window._w, img) self.window.configure(background="#6a8d92") self.window.title("Query Tool - Grupo 8 y Grupo 4") #w, h = self.window.winfo_screenwidth()/2, self.window.winfo_screenheight()/2 w, h = 1300, 670 self.window.geometry("%dx%d+0+0" % (w, h)) ##############################################MENU#################################### menu = Menu(self.window) new_item = Menu(menu, tearoff=0) new_item.add_command(label='Abrir', command=self.abrir_click) new_item.add_command(label='Guardar', command=self.guardar_click) new_item.add_command(label='Guardar Como...', command=self.guardar_como_click) #new_item.add_separator() #new_item.add_command(label='Edit') menu.add_cascade(label='Archivo', menu=new_item) mnreportes = Menu(menu, tearoff=0) mnreportes.add_command(label='Tabla de Errores', command=self.tblerrores_click) mnreportes.add_command(label='Tabla de Simbolos', command=self.tblsimbolos_click) mnreportes.add_command(label='Tabla de Index', command=self.tbindex_click) mnreportes.add_command(label='Tabla de Simbolos 3D', command=self.tblsimbolos3D_click) mnreportes.add_command(label='AST', command=self.ast_click) mnreportes.add_command(label='Reporte Gramatical', command=self.repDin_click) menu.add_cascade(label='Reportes', menu=mnreportes) self.window.config(menu=menu) ##############################################BOTONES#################################### img2 = PhotoImage(file='img/icons/lupita2.png') btnanalizar = Button(self.window, image=img2, bg="#6a8d92", height=35, width=40, command=self.btnanalizar_click) btnanalizar.place(x=20, y=4) img3 = PhotoImage(file='img/icons/lupita3.png') btnpostsql = Button(self.window, image=img3, bg="#6a8d92", height=35, width=40, command=self.btnanalizar3D_click) btnpostsql.place(x=115, y=5) img4 = PhotoImage(file='img/icons/play32.png') btnejecutar = Button(self.window, image=img4, bg="#6a8d92", height=35, width=40, command=self.btngetCodigo_click) btnejecutar.place(x=210, y=5) ##############################################PESTAÑAS#################################### self.tab = ttk.Notebook(self.window) self.tab.pack(fill='both', padx=20, pady=[50, 20]) self.tab_frame = [] self.txtentrada = [] self.txtsalida = [] self.crear_tab("", "Nuevo.sql") lblentrada = Label(self.window, text="Archivo de Entrada:", height=1, width=15, bg='#80b192') lblentrada.place(x=20, y=80) lblsalida = Label(self.window, text="Consola de Salida:", height=1, width=15, bg='#80b192') lblsalida.place(x=20, y=350) #redimensionar los elementos #self.window.bind('<Configure>',self.resizeEvent) #Objeto que almacena el Archivo self.file = "" self.window.mainloop()
class style(): def __init__(self, Pad): # i still need a muscle file to link these two self.Pad = pad def create_file_menu(self): self.file_menu = Menu(self.menu_bar, tearoff=0) self.file_menu.add_command(label="New File", accelerator="Ctrl+N", command=self.on_new_clicked) self.file_menu.add_command(label="Open File", accelerator="Ctrl+O", command=self.on_open_clicked) self.file_menu.add_command(label="Save", accelerator="Ctrl+S", command=self.on_save_clicked) self.file_menu.add_command(label="Save As", accelerator="Ctrl+Shift+S", command=self.on_save_as_clicked) self.file_menu.add_command(label="Recent File", command=self.on_recent_file_clicked) self.menu_bar.add_cascade(label="File", menu=self.file_menu) self.muscle.config(menu=None) #something is here def create_edit_menu(self): self.edit_menu = Menu(self.menu_bar, tearoff=0) self.edit_menu.add_command(label="Undo", accelerator="Ctrl+Z", command=self.on_undo_clicked) self.edit_menu.add_command(label="Redo", accelerator="Ctrl+Y", command=self.on_redo_clicked) self.edit_menu.add_command(label="Copy", accelerator="Ctrl+C", command=self.on_copy_clicked) self.edit_menu.add_command(label="Paste", accelerator="Ctrl+P", command=self.on_paste_clicked) self.menu_bar.add_cascade(label="Edit", command=self.edit_menu) self.muscle.config(menu=None) #something is here too def create_view_menu(self): # the most strainous thing i would experience self.view_menu = Menu(self.menu_bar, tearoff=0) self.view_menu.add_command(label="Run", accelerator="F5", command=self.on_run_clicked) self.view_menu.add_command(label="Create Dump File", command=self.on_dump_clicked) self.view_menu.add_command( label="Preference", command=self.on_theme_clicked) #i used theme instead of preference self.menu_bar.add_cascade(Label="View", command=self.view_menu) def create_help_menu(self): self.help_menu = Menu(self.menu_bar, tearoff=0) self.help_menu.add_command(label="About", command=self.on_about_clicked) self.help_menu.add_command(label="License", command=self.on_info_clicked) self.help_menu.add_command(accelerator="Ctrl+F", command=self.on_find_clicked) self.menu_bar.add_cascade(label="Help", command=self.help_menu) self.muscle.config(menu=None) #something here too #*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#* # ill be needing a lot of textboxes and i mean a awfull lot def on_new_clicked(self): Pad( name ) # dont know if this should do the trick, besides pad has no attribute name def on_open_clicked(self): #honestly i'll like to say i know how this would look like but its too early too lie pass def on_save_clicked(self): pass def on_save_as_clicked(self): pass def on_recent_file_clicked(self): pass #this one is not understandable #*#*#*#*#*#*##**##*#**#*#*#*#*#*#*#*#*#***#*#*#*#*##*#*# #the edit menu properties def on_undo_clicked(self): pass def on_redo_clicked(self): pass def on_copy_clicked(self): pass def on_paste_clicked(self): pass #*#*#*#*#*#*##**##*#**#*#*#*#*#*#*#*#*#***#*#*#*#*##*#*# def on_run_clicked(self): pass def on_dump_clicked(self): pass def on_theme_clicked(self): pass
panel.pack(side=LEFT) img2 = ImageTk.PhotoImage(Image.open("spr3_3.png")) panel2 = Label(imageFrame, image=img2) panel2.pack(side=LEFT) img3 = ImageTk.PhotoImage(Image.open("1.png")) panel3 = Label(imageFrame, image=img3) panel3.pack(side=LEFT) img4 = ImageTk.PhotoImage(Image.open("Leaf_Spring_2.png")) panel4 = Label(imageFrame, image=img4) panel4.pack(side=LEFT) # adding a menu menu = Menu(window) # add submenu below three lines new_item = Menu(menu, tearoff=0) new_item.add_command(label='New', command=create_window) new_item.add_command(label='Export') new_item.add_command(label='Exit', command=window.quit) new_item2 = Menu(menu, tearoff=0) new_item2.add_command(label='Helical', command=create_window) new_item2.add_command(label='Belleville', command=create_window_2) new_item2.add_command(label='Torsion', command=create_window_2) new_item2.add_command(label='Constant Force', command=create_window_2) new_item2.add_command(label='Leaf', command=create_window_2) menu.add_cascade(label='File', menu=new_item) menu.add_cascade(label='Start', menu=new_item2) menu.add_command(label='Save') menu.add_command(label='About', command=create_window_about) menu.add_command(label='Help', command=create_window_help) window.config(menu=menu)
class showPathGUI(): def __init__(self): self.MAP_WIDTH = 15 self.MAP_HEIGHT = 14 self.BLOCK_SIZE = 40 self.X_OFFSET = 0 self.Y_OFFSET = 0 self.BOARD_WIDTH = self.BLOCK_SIZE * self.MAP_WIDTH + 2 * self.X_OFFSET self.BOARD_HEIGHT = self.BLOCK_SIZE * self.MAP_HEIGHT + 2 * self.Y_OFFSET self.new_window(destroy=False) self.plotImg() def new_window(self, destroy=True): if destroy: self.root.destroy() # initialize map self.mapmap = np.zeros((self.MAP_WIDTH, self.MAP_HEIGHT), dtype=np.int) self.startPosition = (2, 0) #Initial point self.goalPosition = (self.MAP_WIDTH - 2, self.MAP_HEIGHT - 3 ) #End point # create window self.root = Tk() self.root.resizable(width=False, height=False) self.root.title('路径规划') self.WIN_WIDTH = self.root.winfo_screenwidth() self.WIN_HEIGHT = self.root.winfo_screenheight() self.MAX_WIDTH = int((self.WIN_WIDTH) / self.BLOCK_SIZE) self.MAX_HEIGHT = int((self.WIN_HEIGHT - 100) / self.BLOCK_SIZE) # create menubar self.menubar = Menu(self.root) self.menubar.add_command(label='Setting', command=self.setup_config) self.menubar.add_command(label='Help', command=self.help) self.root.config(menu=self.menubar) # create Canvas self.cv = Canvas(self.root, background='white', width=self.BOARD_WIDTH, height=self.BOARD_HEIGHT) self.cv.pack() self.cv.bind('<Button-1>', self.click_handler) self.cv.bind('<Double-Button-1>', self.dclick1_handler) self.cv.bind('<Button-3>', self.dclick3_handler) global imgs imgs = [ PhotoImage(file="images/000.png"), PhotoImage(file="images/111.png"), PhotoImage(file="images/444.png"), PhotoImage(file="images/ppp.png"), PhotoImage(file="images/222.png") ] def click_handler(self, event): # compute selected node userX = max( 0, min(int((event.x - self.X_OFFSET) / self.BLOCK_SIZE), self.MAP_WIDTH - 1)) userY = max( 0, min(int((event.y - self.Y_OFFSET) / self.BLOCK_SIZE), self.MAP_HEIGHT - 1)) if (userX, userY) == self.startPosition or (userX, userY) == self.goalPosition: return self.mapmap[userX][userY] = 1 - self.mapmap[userX][userY] self.plotImg() def dclick1_handler(self, event): userX = max( 0, min(int((event.x - self.X_OFFSET) / self.BLOCK_SIZE), self.MAP_WIDTH - 1)) userY = max( 0, min(int((event.y - self.Y_OFFSET) / self.BLOCK_SIZE), self.MAP_HEIGHT - 1)) self.mapmap[self.startPosition[0], self.startPosition[1]] = 0 self.startPosition = (userX, userY) self.plotImg() def dclick3_handler(self, event): userX = max( 0, min(int((event.x - self.X_OFFSET) / self.BLOCK_SIZE), self.MAP_WIDTH - 1)) userY = max( 0, min(int((event.y - self.Y_OFFSET) / self.BLOCK_SIZE), self.MAP_HEIGHT - 1)) self.goalPosition = (userX, userY) self.plotImg() def plotImg(self): ################################################################## # The function you need to implement in `findPath.py`. path = findPath(self.mapmap, self.startPosition, self.goalPosition) ################################################################## newMap = self.mapmap.copy() newMap[self.startPosition[0], self.startPosition[1]] = 2 newMap[self.goalPosition[0], self.goalPosition[1]] = 4 for node in path: newMap[node[0], node[1]] = 3 for i in range(self.MAP_WIDTH): for j in range(self.MAP_HEIGHT): self.cv.create_image( (i + 1 / 2) * self.BLOCK_SIZE + self.X_OFFSET, (j + 1 / 2) * self.BLOCK_SIZE + self.Y_OFFSET, image=imgs[newMap[i, j]]) def setup_config(self): # setup configure of map res = self.ask_userinfo() if res is None: return self.MAP_WIDTH, self.MAP_HEIGHT = res self.BOARD_WIDTH = self.BLOCK_SIZE * self.MAP_WIDTH + 2 * self.X_OFFSET self.BOARD_HEIGHT = self.BLOCK_SIZE * self.MAP_HEIGHT + 2 * self.Y_OFFSET self.new_window() self.plotImg() def ask_userinfo(self): # receive configure data current_parameter = [self.MAP_WIDTH, self.MAP_HEIGHT] setting_info = Setting(self.MAX_WIDTH, self.MAX_HEIGHT, current_parameter) self.root.wait_window(setting_info) return setting_info.userinfo def help(self): messagebox.showinfo( title='Hi,这是你需要的帮助(^-^)', message='''黄色:起点\n红色:终点\n蓝色:路径\n试着点击一下地图!\n然后双击地图!\n然后再右键单击!''')
class CMenuBar: def __init__(self, master): self.master = master self.menuBar = Menu(master) master.config(menu=self.menuBar) self.fileMenu = Menu(self.menuBar, tearoff=0) self.fileMenu.add_command(label="新建脚本") self.fileMenu.add_command(label="导入脚本") self.fileMenu.add_command(label="基本设置") self.fileMenu.add_separator() self.fileMenu.add_command(label="退出", command=self.exitApp) self.menuBar.add_cascade(label="文件", menu=self.fileMenu) self.editMenu = Menu(self.menuBar, tearoff=0) self.editMenu.add_command(label="重复") self.editMenu.add_command(label="撤销") self.menuBar.add_cascade(label="编辑", menu=self.editMenu) self.controlMenu = Menu(self.menuBar, tearoff=0) self.controlMenu.add_command(label="连接设备") self.controlMenu.add_command(label="断开连接") self.controlMenu.add_separator() self.controlMenu.add_command(label="执行脚本") self.controlMenu.add_command(label="暂停执行") self.controlMenu.add_command(label="终止执行") self.menuBar.add_cascade(label="控制", menu=self.controlMenu) self.helpMenu = Menu(self.menuBar, tearoff=0) self.helpMenu.add_command(label="文档") self.helpMenu.add_command(label="关于") self.menuBar.add_cascade(label="帮助", menu=self.helpMenu) def exitApp(self): # 做一些清理工作, 如断开串口 self.master.quit()
\n а если возвести матрицу в степень то введите искомую матрицу в поле для первой,\ \n а степень в первую строку и первыый столбец поля второй матрицы. \ \n При этом возводимая матрица должна быть квадратной\ \n \n 3) Если вы выбрали операцию умножения матриц, то количество столбцов \ \n первой матрицы должно совпадать с количеством столбцов второй \ \n \n 4) Для нахождения суммы или разности матриц вы должны ввести \ \n матрицы одинаковой размерности \ \n \n 5) Чтобы 'разделить' матрицы нужно учитывать условие умножения \ \n \n 6) Нажмите на кнопку 'Execute' чтобы посчитать результат \ \n \n 7) Чтобы выполнить новую операцию нажмите 'Clear' и повторите действия начиная с п. 1", justify=LEFT) info2.grid(row=0, column=0) menu = Menu(root) menu.add_command(label='Instruction', command=HowToUse) root.config(menu=menu) menu.add_command(label='Autor', command=autorinfo) combo = Combobox(root) combo['values'] = ("SUM", "MINUS", "MULT", "DIV", "POW", "DET") combo.current(2) combo.grid(row=0, column=0) #chek = Label(root, text="Rows and colls") #chek.grid(row=1, column=0) r1 = Label(root, text="Rows1", justify=LEFT) r1.grid(row=2, column=0) rows1 = Spinbox(root, from_=2, to=20, width=3) rows1.grid(column=1, row=2) c1 = Label(root, text="Columns1", justify=LEFT) c1.grid(row=3, column=0)
def create_widgets(self): tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Modify adding a Label using mighty as the parent instead of win a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() self.name_entered = ttk.Entry(mighty, width=24, textvariable=self.name) self.name_entered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(mighty, text="Click Me!", command=self.click_me) self.action.grid(column=2, row=1) ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() self.number_chosen = ttk.Combobox(mighty, width=14, textvariable=number, state='readonly') self.number_chosen['values'] = (1, 2, 4, 42, 100) self.number_chosen.grid(column=1, row=1) self.number_chosen.current(0) # Adding a Spinbox widget self.spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=self._spin) # using range self.spin.grid(column=0, row=2, sticky='W') # align left # Using a scrolled Text control scrol_w = 40; scrol_h = 10 # increase sizes self.scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) self.scrol.grid(column=0, row=3, sticky='WE', columnspan=3) for child in mighty.winfo_children(): # add spacing to align widgets within tabs child.grid_configure(padx=4, pady=2) #===================================================================================== # Tab Control 2 ---------------------------------------------------------------------- self.mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.mighty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.mighty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.mighty2, text="UnChecked", variable=chVarUn) check2.deselect() check2.grid(column=1, row=0, sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.mighty2, text="Enabled", variable=chVarEn) check3.deselect() check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # First, we change our Radiobutton global variables into a list colors = ["Blue", "Gold", "Red"] # create three Radiobuttons using one variable self.radVar = tk.IntVar() # Next we are selecting a non-existing index value for radVar self.radVar.set(99) # Now we are creating all three Radiobutton widgets within one loop for col in range(3): curRad = tk.Radiobutton(self.mighty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=1, sticky=tk.W) # row=6 # And now adding tooltips tt.create_ToolTip(curRad, 'This is a Radiobutton control') # Add a Progressbar to Tab 2 self.progress_bar = ttk.Progressbar(tab2, orient='horizontal', length=286, mode='determinate') self.progress_bar.grid(column=0, row=3, pady=2) # Create a container to hold buttons buttons_frame = ttk.LabelFrame(self.mighty2, text=' ProgressBar ') buttons_frame.grid(column=0, row=2, sticky='W', columnspan=2) # Add Buttons for Progressbar commands ttk.Button(buttons_frame, text=" Run Progressbar ", command=self.run_progressbar).grid(column=0, row=0, sticky='W') ttk.Button(buttons_frame, text=" Start Progressbar ", command=self.start_progressbar).grid(column=0, row=1, sticky='W') ttk.Button(buttons_frame, text=" Stop immediately ", command=self.stop_progressbar).grid(column=0, row=2, sticky='W') ttk.Button(buttons_frame, text=" Stop after second ", command=self.progressbar_stop_after).grid(column=0, row=3, sticky='W') for child in buttons_frame.winfo_children(): child.grid_configure(padx=2, pady=2) for child in self.mighty2.winfo_children(): child.grid_configure(padx=8, pady=2) # Creating a Menu Bar menu_bar = Menu(self.win) self.win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=self._quit) menu_bar.add_cascade(label="File", menu=file_menu) # Display a Message Box def _msgBox(): msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.') # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label="About", command=_msgBox) # display messagebox when clicked menu_bar.add_cascade(label="Help", menu=help_menu) # Change the main windows icon self.win.iconbitmap('pyc.ico') # It is not necessary to create a tk.StringVar() # strData = tk.StringVar() strData = self.spin.get() # call function self.usingGlobal() self.name_entered.focus() # Add Tooltips ----------------------------------------------------- # Add a Tooltip to the Spinbox tt.create_ToolTip(self.spin, 'This is a Spinbox control') # Add Tooltips to more widgets tt.create_ToolTip(self.name_entered, 'This is an Entry control') tt.create_ToolTip(self.action, 'This is a Button control') tt.create_ToolTip(self.scrol, 'This is a ScrolledText control')
# end of this iteration new_file_icon = PhotoImage(file='icons/new_file.gif') open_file_icon = PhotoImage(file='icons/open_file.gif') save_file_icon = PhotoImage(file='icons/save.gif') cut_icon = PhotoImage(file='icons/cut.gif') copy_icon = PhotoImage(file='icons/copy.gif') paste_icon = PhotoImage(file='icons/paste.gif') undo_icon = PhotoImage(file='icons/undo.gif') redo_icon = PhotoImage(file='icons/redo.gif') menu_bar = Menu(root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='New', accelerator='Ctrl+N', compound='left', image=new_file_icon, underline=0) file_menu.add_command(label='Open', accelerator='Ctrl+O', compound='left', image=open_file_icon, underline=0) file_menu.add_command(label='Save', accelerator='Ctrl+S', compound='left', image=save_file_icon, underline=0) file_menu.add_command(label='Save as', accelerator='Shift+Ctrl+S') file_menu.add_separator() file_menu.add_command(label='Exit', accelerator='Alt+F4')
# Exit GUI cleanly def _quit(): win.quit() win.destroy() exit() # Creating a Menu Bar menu_bar = Menu(win) win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=_quit) menu_bar.add_cascade(label="File", menu=file_menu) # Display a Message Box def _msgBox(): msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2019.') # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label="About", command=_msgBox) # display messagebox when clicked
def __init__(self, menubar, image_io): border_menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Border Detection", menu=border_menu) border_menu.add_command( label="Prewitt operator", command=UnaryWithParamsImageOperation( image_io, "Prewitt", lambda image: display_linear_adj_image_wrapper( border_detection.prewitt_detector(image) ), params=[], ).generate_interface, ) border_menu.add_command( label="Sobel operator", command=UnaryWithParamsImageOperation( image_io, "Sobel", lambda image: display_linear_adj_image_wrapper( border_detection.sobel_detector(image)[0] ), params=[], ).generate_interface, ) border_menu.add_command( label="Laplacian operator", command=UnaryWithParamsImageOperation( image_io, "Laplace", lambda image: display_linear_adj_image_wrapper( border_detection.laplacian_border_detection(image) ), params=[], ).generate_interface, ) border_menu.add_command( label="Gaussian laplacian operator", command=UnaryWithParamsImageOperation( image_io, "Gauss", lambda image, threshold, sigma, kernel_size: display_linear_adj_image_wrapper( border_detection.gaussian_laplacian_detection( image, threshold, sigma, kernel_size ) ), params=["threshold", "sigma", "kernel_size"], ).generate_interface, ) border_menu.add_command( label="Prewitt multi dir operator", command=UnaryWithParamsImageOperation( image_io, "Prewitt", lambda image, rotation_angle: display_linear_adj_image_wrapper( multi_direction_border_detection.prewitt_border_detection( image, rotation_angle ) ), params=["rotation_angle"], ).generate_interface, ) border_menu.add_command( label="Sobel multi dir operator", command=UnaryWithParamsImageOperation( image_io, "Sobel", lambda image, rotation_angle: display_linear_adj_image_wrapper( multi_direction_border_detection.sobel_border_detection( image, rotation_angle ) ), params=["rotation_angle"], ).generate_interface, ) border_menu.add_command( label="ITBA multi dir operator", command=UnaryWithParamsImageOperation( image_io, "ITBA", lambda image, rotation_angle: display_linear_adj_image_wrapper( multi_direction_border_detection.itba_border_detection( image, rotation_angle ) ), params=["rotation_angle"], ).generate_interface, ) border_menu.add_command( label="Kirish multi dir operator", command=UnaryWithParamsImageOperation( image_io, "Kirish", lambda image, rotation_angle: display_linear_adj_image_wrapper( multi_direction_border_detection.kirish_border_detection( image, rotation_angle ) ), params=["rotation_angle"], ).generate_interface, ) border_menu.add_command( label="Canny Border Detector", command=UnaryWithBoolParamsOperation( image_io, "Canny", lambda image, sigma_s, sigma_r, kernel_size, four_neighbours, high_threshold, low_threshold: display_linear_adj_image_wrapper( border_detection.canny_detection( image, kernel_size, sigma_s, sigma_r, high_threshold, low_threshold, four_neighbours, ) ), params=[ "sigma_s", "sigma_r", "kernel_size", "high_threshold", "low_threshold", ], bool_params=[("four_neighbours", "eight_neighbours")], ).generate_interface, ) border_menu.add_command( label="Susan Border Detector", command=UnaryWithParamsImageOperation( image_io, "susan", lambda image, threshold, low_filter, high_filter, color: display_linear_adj_image_wrapper( border_detection.susan_detection( image, threshold, low_filter, high_filter, int(color) ) ), params=["threshold", "low_filter", "high_filter", "color"], ).generate_interface, )
class StockAnalysis(): """ stock analysis class """ def __init__(self, master): self.master = master self.master.title("Stock Analysis") self.master.geometry("250x120") self.master.resizable(False, False) self.filename = "" self.filenamesave = "" #menu self.menu = Menu(self.master) self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Insert a csv", accelerator='Ctrl + O', command=self.insert_csv) self.file_menu.add_command(label="Close csv", accelerator='Ctrl+F4', command=self.closef) self.file_menu.add_command(label="Save Range Data", accelerator='Ctrl+T', command=self.save_range_data) self.file_menu.add_command(label="Exit", accelerator='Alt+F4', command=self.exitmenu) self.menu.add_cascade(label="File", menu=self.file_menu) self.show_menu = Menu(self.menu, tearoff=0) self.show_menu.add_command(label="Show Graph Summary", accelerator='Ctrl+S', command=lambda: self.graph(None)) self.show_menu.add_command(label="Show csv", accelerator='Alt+S', command=self.showcsv) self.show_menu.add_command(label="Show Open Graph", accelerator='Alt + T', command=lambda: self.graph('Open')) self.show_menu.add_command(label="Show High Graph", accelerator='Alt + U', command=lambda: self.graph('High')) self.show_menu.add_command(label="Show Low Graph", accelerator='Alt + Q', command=lambda: self.graph('Low')) self.show_menu.add_command(label="Show Close Graph", accelerator='Alt + C', command=lambda: self.graph('Close')) self.show_menu.add_command(label="Show Adj Close Graph", accelerator='Alt + D', command=lambda: self.graph('Adj Close')) self.show_menu.add_command(label="Show Volume Graph", accelerator='Alt + B', command=lambda: self.graph('Volume')) self.menu.add_cascade(label="Show", menu=self.show_menu) self.range_menu = Menu(self.menu, tearoff=0) self.range_menu.add_command(label="Date Range", accelerator='Ctrl + D', command=lambda: self.range('Date')) self.range_menu.add_command(label="Open Range", accelerator='Alt + O', command=lambda: self.range('Open')) self.range_menu.add_command(label="High Range", accelerator='Alt + H', command=lambda: self.range('High')) self.range_menu.add_command(label="Low Range", accelerator='Alt + L', command=lambda: self.range('Low')) self.range_menu.add_command(label="Close Range", accelerator='Alt + C', command=lambda: self.range('Close')) self.range_menu.add_command(label="Adj Close Range", accelerator='Alt + A', command=lambda: self.range('Adj Close')) self.range_menu.add_command(label="Volume Range", accelerator='Alt + V', command=lambda: self.range('Volume')) self.menu.add_cascade(label="Range", menu=self.range_menu) self.about_menu = Menu(self.menu, tearoff=0) self.about_menu.add_command(label="About", accelerator='Ctrl+I', command=aboutmenu) self.menu.add_cascade(label="About", menu=self.about_menu) self.help_menu = Menu(self.menu, tearoff=0) self.help_menu.add_command(label="Help", accelerator='Ctrl+F1', command=helpmenu) self.menu.add_cascade(label="Help", menu=self.help_menu) self.master.config(menu=self.menu) self.master.bind('<Control-t>', lambda event: self.save_range_data()) self.master.bind('<Control-o>', lambda event: self.insert_csv()) self.master.bind('<Alt-s>', lambda event: self.showcsv()) self.master.bind('<Control-d>', lambda event: self.range('Date')) self.master.bind('<Alt-F4>', lambda event: self.exitmenu()) self.master.bind('<Control-F1>', lambda event: helpmenu()) self.master.bind('<Control-i>', lambda event: aboutmenu()) self.master.bind('<Alt-o>', lambda event: self.range('Open')) self.master.bind('<Alt-h>', lambda event: self.range('High')) self.master.bind('<Alt-l>', lambda event: self.range('Low')) self.master.bind('<Alt-c>', lambda event: self.range('Close')) self.master.bind('<Alt-a>', lambda event: self.range('Adj Close')) self.master.bind('<Alt-v>', lambda event: self.range('Volume')) self.master.bind('<Alt-t>', lambda event: self.graph('Open')) self.master.bind('<Alt-u>', lambda event: self.graph('High')) self.master.bind('<Alt-q>', lambda event: self.graph('Low')) self.master.bind('<Alt-c>', lambda event: self.graph('Close')) self.master.bind('<Alt-d>', lambda event: self.graph('Adj Close')) self.master.bind('<Alt-b>', lambda event: self.graph('Volume')) self.master.bind('<Control-s>', lambda event: self.graph(None)) self.master.bind('<Control-F4>', lambda event: self.closef()) def savefile(self): """ save file function """ if self.filenamesave is None or self.filenamesave == "": msg.showerror("ERROR", "NO FILE SAVED") else: self.saverange() def saverange(self): """ save ranges to a csv file """ with open(str(self.filenamesave) + '.csv', 'a+') as f: thewriter = csv.writer(f) thewriter.writerow([ 'Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume' ]) thewriter.writerow([ str(self.df.iloc[0]['Date']), str(max(self.df['Open'])), str(max(self.df['High'])), str(max(self.df['Low'])), str(max(self.df['Close'])), str(max(self.df['Adj Close'])), str(max(self.df['Volume'])) ]) thewriter.writerow([ str(self.df.iloc[-1]['Date']), str(min(self.df['Open'])), str(min(self.df['High'])), str(min(self.df['Low'])), str(min(self.df['Close'])), str(min(self.df['Adj Close'])), str(min(self.df['Volume'])) ]) msg.showinfo("SUCCESS", "CSV FILE SAVED SUCCESSFULLY") def save_range_data(self): """ saves a csv data with the max min values""" if self.filename == "": msg.showerror("ERROR", "NO CSV FILE") else: self.filenamesave = filedialog.asksaveasfilename( initialdir="/", title="Select file", filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) self.savefile() def graph(self, graphname): """ shows a graph named by the graphname parameter """ if self.filename == "": msg.showerror("ERROR", "NO CSV FILE") elif graphname is None: self.df.plot(title="Summary Graph") plt.show() else: self.df[graphname].plot(title=graphname + " Graph") plt.show() def showcsv(self): """ shows the whole dataset """ if self.filename == "": msg.showerror("ERROR", "NO CSV FILE") else: msg.showinfo("DATA FRAME", str(self.df)) def range(self, rangename): """ shows the range of the rangename parameter """ if self.filename == "": msg.showerror("ERROR", "NO CSV FILE") else: if rangename == 'Date': msg.showinfo( "Date Range", "From: " + str(self.df.iloc[0]['Date']) + "\nTo: " + str(self.df.iloc[-1]['Date'])) else: msg.showinfo( str(rangename) + " Range", "Max: " + str(max(self.df[rangename])) + "\nMin: " + str(min(self.df[rangename]))) def closef(self): """ closes file """ if self.filename == "": msg.showerror("ERROR", "NO CSV FILE") else: self.filename = "" msg.showinfo("SUCCESS", "CSV FILE SUCCESSFULLY CLOSED") def column_validation(self): """ checks the columns of the inserted csv file """ if all([ item in self.df.columns for item in ['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'] ]): msg.showinfo("SUCCESS", "CSV FILE ADDED SUCCESSFULLY") else: self.filename = "" msg.showerror("ERROR", "NO PROPER CSV ") def inputvalidation(self): """ input validation""" # csv file stracture : Date,Open,High,Low, # Close,Adj Close,Volume if ".csv" in self.filename: self.df = pd.read_csv(self.filename) self.column_validation() else: self.filename = "" msg.showerror("ERROR", "NO CSV IMPORTED") def insert_csv(self): """ insert csv function """ if self.filename == "": self.filename = filedialog.askopenfilename( initialdir="/", title="Select csv file", filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) self.inputvalidation() else: msg.showerror("ERROR", " A CSV FILE IS ALREADY OPEN") def exitmenu(self): """ exit menu function """ if msg.askokcancel("Quit?", "Really quit?"): self.master.destroy()
def student(): stud = Toplevel() stud.title("Welcome To Library") stud.geometry("1500x800+0+0") stud.iconbitmap('images/logo.ico') stud.minsize(400, 500) pic = ImageTk.PhotoImage(file="images/pexels-cottonbro-4855428.jpg") label = Label(stud, image=pic) label.pack() ###################### CONTENT FRAME ############ frame_dash = Frame(stud, bg='#f7f1e3') frame_dash.place(width=400, height=320, x=560, y=180) ################### HEADING PORTION ########## heading_bookadd = Frame(stud, bg="lightcyan", bd=10, relief="groove") heading_bookadd.place(x=510, y=60, width=480, height=100) ################### HEADING PORTION END ########## #################### HEADING PORTION Data ########## heading_bookadd_content = Label(heading_bookadd, text="Welcome To \nLibrary", bg='#EAF0F1', fg='black', font=("Goudy old style", 26, "bold")) heading_bookadd_content.place(x=0, y=0, width=460) ################### HEADING PORTION END ########## ###################### CONTENT FRAME END ############ ###################### CONTENT in FRAME ############ def bookstock(): global frame_bookview global heading_bookview frame_bookview = Frame(stud) frame_bookview.place(width=600, height=470, x=450, y=170) e = Label(frame_bookview, width=21, text=' BookId', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 10, 'bold ')) e.grid(row=0, column=0) e = Label(frame_bookview, width=21, text=' BookName', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 10, 'bold ')) e.grid(row=0, column=1) e = Label(frame_bookview, width=21, text=' BookAuthor', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 10, 'bold ')) e.grid(row=0, column=2) e = Label(frame_bookview, width=21, text=' BookStock', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 10, 'bold ')) e.grid(row=0, column=3) concommand.execute("select * from addbook") i = 1 res = concommand.fetchall() for display in res: for columns in range(len(display)): e = Label(frame_bookview, text=display[columns], width=21, height=2, borderwidth=2, relief='ridge') e.grid(row=i, column=columns) i = i + 1 button_view_back = Button(frame_bookview, text="< Back", bg='black', command=view_back, cursor="hand2", fg='white', font=('Consolas', 21, 'bold ')) button_view_back.place(x=50, y=400) ################################ BOOK VIEW ENDS ###################################################### def view_back(): frame_bookview.destroy() def bookview(): global frame_bookview global heading_bookview frame_bookview = Frame(stud) frame_bookview.place(width=600, height=470, x=450, y=170) e = Label(frame_bookview, width=22, text=' BookId', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 12, 'bold ')) e.grid(row=0, column=0) e = Label(frame_bookview, width=22, text=' BookName', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 13, 'bold ')) e.grid(row=0, column=1) e = Label(frame_bookview, width=22, text=' BookAuthor', height=1, borderwidth=2, relief='ridge', anchor='w', bg='lightgray', font=('Consolas', 12, 'bold ')) e.grid(row=0, column=2) concommand.execute("select bookid,bookname,bookauthor from addbook") i = 1 res = concommand.fetchall() for display in res: for columns in range(len(display)): e = Label(frame_bookview, text=display[columns], width=28, height=2, borderwidth=2, relief='ridge') e.grid(row=i, column=columns) i = i + 1 button_view_back = Button(frame_bookview, text="< Back", bg='black', command=view_back, cursor="hand2", fg='white', font=('Consolas', 21, 'bold ')) button_view_back.place(x=50, y=400) ################################ BOOK VIEW ENDS ###################################################### def subs(): subs_entry = entry_user.get() pattern = regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if re.search(pattern, subs_entry): if subs_entry.strip() != "": concommand.execute( "insert into subscribe (email) values ('{}')".format( subs_entry)) con.commit() msg.showinfo("Sucessfull", "Thankyou for Subscribing!!") frame_bookview.focus() s = smtplib.SMTP('smtp.gmail.com', 587) ### FOR PORT NUMBER s.starttls() s.login("*****@*****.**", "8607696626") message = f"Hey {subs_entry},\n Thankyou for Subscribing us!\n\n\n Get Ready To Recieve all news and important announcement of your Favourite library at you fingertips.\n\n\n\n\nThankyou:)\nHave a Good One!!!" subject = "Library" mess = 'subject:{}\n\n{}'.format( subject, message) ### IT WILL ADD SUBJECT.. s.sendmail("*****@*****.**", subs_entry, mess) s.quit() print("Mail Sent") labelclass.set('') entryclass.set('') else: print("blank") else: labelclass.set("****** Invalid Email Id") def subscribe(): global frame_bookview frame_bookview = Frame(stud) frame_bookview.place(width=600, height=320, x=450, y=170) label = Label( frame_bookview, text= "Enter Your Email in\n order to Catch\n our all new Announcements.", bg="white", fg="green", font=("aerial", 18, 'bold italic')) label.pack(pady=10) label1 = Label(frame_bookview, text="Email:", fg="black", font=("Goudy old style", 22, "bold")) label1.place(x=50, y=150) global entry_user global entryclass entryclass = StringVar() entry_user = Entry(frame_bookview, fg='black', textvariable=entryclass, bg='lightgray', font=("Helvetica", 16)) entry_user.place(x=160, y=155, width=350, height=30) global labelclass labelclass = StringVar() labelclass.set('') Label(frame_bookview, fg='red', textvariable=labelclass, font="calibiri 14 bold italic").place(x=160, y=210) Button(frame_bookview, text="Subscribe", fg='green', command=subs, cursor="hand2", font=('aerial', 20, 'bold')).place(x=420, y=260) Button(frame_bookview, text="< Back", fg='green', command=view_back, cursor="hand2", font=('aerial', 20, 'bold')).place(x=20, y=260) def quitt(): c = msg.askyesno("Logout", "Are you sure you want to Logout") if c == True: stud.destroy() else: stud.focus() btn1 = Button(frame_dash, text="View Books", bg='black', fg='white', command=bookview, cursor="hand2", font=('Consolas', 22)) btn1.place(x=0, y=0, width=400) btn2 = Button(frame_dash, text="Availability of Books", bg='black', fg='white', command=bookstock, cursor="hand2", font=('Consolas', 22)) btn2.place(x=0, y=80, width=400) btn3 = Button(frame_dash, text="Subscribe", bg='black', fg='white', command=subscribe, cursor="hand2", font=('Consolas', 22)) btn3.place(x=0, y=160, width=400) btn4 = Button(frame_dash, text="Logout", bg='black', fg='white', command=quitt, cursor="hand2", font=('Consolas', 22)) btn4.place(x=0, y=240, width=400) menubar = Menu(stud) m1 = Menu(menubar, tearoff=0, font=('Calibiri', 11)) m1.add_command(label="View Books", command=bookview) menubar.add_cascade(label='View', menu=m1) m2 = Menu(menubar, tearoff=0, font=('Calibiri', 11)) m2.add_command(label="Availability of Books", command=bookstock) menubar.add_cascade(label='Availability', menu=m2) m3 = Menu(menubar, tearoff=0, font=('Calibiri', 11)) m3.add_command(label="Subscribe Us", command=subscribe) menubar.add_cascade(label='Subscribe', menu=m3) m4 = Menu(menubar, tearoff=0) m4.add_command(label="Logout", command=quitt) menubar.add_cascade(label='Logout', menu=m4) stud.config(menu=menubar) ###################### CONTENT in FRAME END ############ stud.mainloop()
from tkinter import Tk, Menu, Frame root = Tk() root.title("практика 7") root.geometry('500x300+700+300') fr = Frame(root) fr.pack(expand=1, fill='both') mainmenu = Menu(root) root.config(menu=mainmenu) filemenu = Menu(mainmenu, tearoff=0) filemenu.add_command(label="Открыть...") filemenu.add_command(label="Новый") filemenu.add_command(label="Сохранить...") filemenu.add_command(label="Выход") helpmenu = Menu(mainmenu, tearoff=0) helpmenu.add_command(label="Помощь") helpmenu.add_command(label="О программе") mainmenu.add_cascade(label="Файл", menu=filemenu) mainmenu.add_cascade(label="Справка", menu=helpmenu) root.mainloop()
msg.showinfo( 'Contacts information', 'Here you can see all contacts.\nCreate new contact.\nDelete contact.\nUpdate contact' ) def _quit(): answer = msg.askyesno('Python Message', 'Do you really want to exit?') if answer == 1: contacts.quit() menu_bar = Menu(contacts) contacts.config(menu=menu_bar) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='Exit', command=_quit) menu_bar.add_cascade(label='File', menu=file_menu) help_menu = Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label="Help", menu=help_menu) help_menu.add_command(label='About', command=msgBox) a_lable = ttk.Label(contacts, text='Url:') a_lable.grid(column=0, row=0, sticky=tk.E, padx=3, pady=3) main_url = tk.StringVar() main_url_entered = ttk.Entry(contacts, width=70, textvariable=main_url) main_url_entered.grid(column=1, row=0, sticky=tk.W, padx=3, pady=3) mighty = tk.LabelFrame(contacts, text='Contact information') mighty.grid(row=1, padx=8, pady=8, columnspan=2) mighty.configure(background='ivory')
class EditorWindow: def __init__(self): self.root = Tk(className="EDITOR") self.python_files = PythonFiles(self) self.root.geometry("%dx%d+%d+%d" % ( self.root.winfo_screenwidth() * 0.5, self.root.winfo_screenheight() * 0.4, # self.root.winfo_screenwidth() * 0.1, self.root.winfo_screenheight() * 0.1 0,0 )) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.base_title = "PyEditor v%s" % __version__ self.root.title(self.base_title) self.text_frame = Frame(master=self.root) self.text = ScrolledText(master=self.root, background="white") self.text.bind("<Tab>", self.tab_event) self.text.grid(row=0, column=0, sticky=NSEW) #TODO: find a right height self.exec_output = ScrolledText( master=self.root, height=10, state=DISABLED, background="#dddddd" ) # for information text like load/save/run: self.exec_output.tag_config("info", foreground="#0000ff", #background="#eeeeee" ) self.exec_output.grid(row=1, column=0, sticky=NSEW) self.text.focus_set() # self.script_list = ScriptList(self) p = Percolator(self.text) d = ColorDelegator() p.insertfilter(d) # add statusbar to window self.init_statusbar() # add menu to window self.init_menu() # Add special RPi/Minecraft features, if available self.rpi = MinecraftSpecials(self) if self.rpi.mcpi_available: # minecraft is available self.set_content(DEFAULT_MCPI_SCRIPT) if not self.rpi.is_running: self.rpi.startup_minecraft() else: # no minecraft available self.set_content(DEFAULT_SCRIPT) self.root.update() ########################################################################### # Status bar FILENAME_LABEL="filename" def get_filename(self): filename = self.status_bar.get_textEntry(self.FILENAME_LABEL) return filename def set_filename(self, filename): filename = os.path.split(filename)[-1] self.status_bar.set_textEntry(self.FILENAME_LABEL, filename) def update_filename(self, event=None): filename = self.get_filename() if filename and not filename.endswith(".py"): filename = "%s.py" % filename self.set_filename(filename) def init_statusbar(self): self.status_bar = MyMultiStatusBar(self.root) if sys.platform == "darwin": # Insert some padding to avoid obscuring some of the statusbar # by the resize widget. self.status_bar.set_label('_padding1', ' ', side=RIGHT) self.status_bar.grid(row=2, column=0) self.text.bind("<<set-line-and-column>>", self.set_line_and_column) self.text.event_add("<<set-line-and-column>>", "<KeyRelease>", "<ButtonRelease>") self.text.after_idle(self.set_line_and_column) self.status_bar.new_textEntry( self.FILENAME_LABEL, 'unnamed.py', callback=self.update_filename ) def set_line_and_column(self, event=None): line, column = self.text.index(INSERT).split('.') self.status_bar.set_label('column', 'Column: %s' % column) self.status_bar.set_label('line', 'Line: %s' % line) ########################################################################### # Menu def init_menu(self): self.menubar = Menu(self.root) filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_command(label="Run", command=self.command_run) self.menubar.add_command(label="Load", command=self.command_load_file) # filemenu.add_command(label="Load", command=self.command_load_file) self.menubar.add_command(label="Save", command=self.command_save_file) self.menubar.add_command(label="Exit", command=self.root.quit) # # self.menubar.add_cascade(label="File", menu=filemenu) self.root.config(menu=self.menubar) def command_run(self): source_listing = self.get_content() self.exec_output.config(state=NORMAL) self.exec_output.delete("1.0", END) filename = self.get_filename() self.python_files.run_source_listing(source_listing, filename) log.debug("Adding to terminal out") #self.exec_output.insert(END, "Run Script") self.exec_output.config(state=DISABLED) def command_load_file(self): infile = askopenfile( parent=self.root, mode="r", title="Select a Python file to load", filetypes=DEFAULT_FILETYPES, initialdir=BASE_PATH, ) if infile is not None: source_listing = infile.read() infile.close() self.set_content(source_listing) self.set_filename(infile.name) # FIXME: insert only name! self.append_feedback_to_output("Script %r loaded." % infile.name) def command_save_file(self): self.update_filename() # FIXME: add .py if missing content = self.get_content() filename = self.get_filename() filepath = os.path.join(BASE_PATH, filename) if os.path.isfile(filepath): self.python_files.move_to_backup(filepath) with open(filepath, "w") as f: f.write(content) self.append_feedback_to_output("Save to: %r" % filepath) ########################################################################### def get_content(self): content = self.text.get("1.0", END) content = content.strip() return content def set_content(self, source_listing): self.text.delete("1.0", END) log.critical("insert %i Bytes listing.", len(source_listing)) self.text.insert(END, source_listing) self.text.mark_set(INSERT, '1.0') # Set cursor at start self.text.focus() def append_exec_output(self, text): self.exec_output.config(state=NORMAL) self.exec_output.insert(END, text) self.exec_output.config(state=DISABLED) def append_feedback_to_output(self, text): text = "%s\n" % text.rstrip() self.exec_output.config(state=NORMAL) self.exec_output.insert(END, text, "info") self.exec_output.config(state=DISABLED) ########################################################################### indent_pad=" "*4 def tab_event(self, event): log.debug("Tab event") self.text.insert("insert", self.indent_pad) return BREAK
def __init__(self, master): self.app_variables = AppVariables() self.master = master master_frame = tkinter.Frame(master) AbstractWidgetPanel.__init__(self, master_frame) widgets_list = ["frequency_vs_degree_panel", "filtered_panel"] self.init_w_horizontal_layout(widgets_list) self.frequency_vs_degree_panel.pack(expand=tkinter.Y, fill=tkinter.BOTH) self.filtered_panel.pack() self.filtered_panel.canvas.set_canvas_size(900, 700) self.frequency_vs_degree_panel.canvas.on_left_mouse_motion(self.callback_frequency_vs_degree_left_mouse_motion) self.image_info_popup_panel = tkinter.Toplevel(self.master) self.image_info_panel = ImageInfoPanel(self.image_info_popup_panel) self.image_info_panel.pack() self.image_info_popup_panel.withdraw() self.image_info_panel.file_selector.select_file.on_left_mouse_click(self.callback_select_file) self.ph_popup_panel = tkinter.Toplevel(self.master) self.phase_history = PhaseHistoryPanel(self.ph_popup_panel) self.phase_history.pack() self.ph_popup_panel.withdraw() self.metaicon_popup_panel = tkinter.Toplevel(self.master) self.metaicon = MetaIcon(self.metaicon_popup_panel) self.metaicon.set_canvas_size(800, 600) self.metaicon.pack() # self.metaicon_popup_panel.withdraw() self.metaviewer_popup_panel = tkinter.Toplevel(self.master) self.metaviewer = Metaviewer(self.metaviewer_popup_panel) self.metaviewer.pack() self.metaviewer_popup_panel.withdraw() self.animation_popup_panel = tkinter.Toplevel(self.master) self.animation_panel = AnimationPanel(self.animation_popup_panel) self.animation_panel.pack() self.animation_popup_panel.withdraw() # callbacks for animation self.animation_panel.animation_settings.play.on_left_mouse_click(self.callback_play_animation_fast_slow) self.animation_panel.animation_settings.step_forward.on_left_mouse_click(self.callback_step_forward) self.animation_panel.animation_settings.step_back.on_left_mouse_click(self.callback_step_back) self.animation_panel.animation_settings.stop.on_left_mouse_click(self.callback_stop_animation) # self.animation_panel.mode_panel.resolution_mode.on_left_mouse_click(self.callback_select_resolution_mode) menubar = Menu() filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open", command=self.select_file) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.exit) # create more pulldown menus popups_menu = Menu(menubar, tearoff=0) popups_menu.add_command(label="Main Controls", command=self.main_controls_popup) popups_menu.add_command(label="Phase History", command=self.ph_popup) popups_menu.add_command(label="Metaicon", command=self.metaicon_popup) popups_menu.add_command(label="Metaviewer", command=self.metaviewer_popup) popups_menu.add_command(label="Animation", command=self.animation_fast_slow_popup) save_menu = Menu(menubar, tearoff=0) save_menu.add_command(label="Save Meticon", command=self.save_metaicon) menubar.add_cascade(label="File", menu=filemenu) menubar.add_cascade(label="Popups", menu=popups_menu) menubar.add_cascade(label="Save", menu=save_menu) master.config(menu=menubar) master_frame.pack() self.pack()
def __init__(self): self.root = Tk() self.root.title("Folder security") self.path_to_image = [] # Main window self.mainframe = ttk.Frame(self.root, padding="4 4 12 12", width=480, height=320) self.mainframe.pack() # menu bar menubar = Menu(self.root, background='orange') menubar.add_command(label='Take picture', command=TakePicture) menubar.add_command(label='Use existing image', command=self.use_existing_image) menubar.add_command(label='Exit', command=self.close_program) menubar.add_command(label='Help', command=HelpPage) self.root.config(menu=menubar) # Labels folder_label = ttk.Label(self.mainframe, text='Choose folder:', font=16) listbox_label = ttk.Label(self.mainframe, text='List of secured folder:', font=16) # Entries self.folder_entry = ttk.Entry(self.mainframe, width=50, text='', background='white') # List box self.folders_listbox = Listbox(self.mainframe, width=50, background='white') self.data = get_paths_from_dir() for path in self.data: self.folders_listbox.insert(1, path.strip('\n')) # Buttons self.browse = ttk.Button(self.mainframe, text='Browse...', command=self.get_folder_path) lock_btn = ttk.Button(self.mainframe, text='Lock', command=self.lock_directory) unlock_btn = ttk.Button(self.mainframe, text='Unlock', command=self.unlock_dir) # Grigds # folder grid folder_label.grid(column=1, row=1) self.folder_entry.grid(column=2, row=1) # browser button grid self.browse.grid(column=3, row=1, padx=10, pady=10) # lock button grid lock_btn.grid(column=3, row=2) # unlock unlock_btn.grid(column=3, row=3) # list box grid listbox_label.grid(column=1, row=2) self.folders_listbox.grid(column=2, row=3)
def create_window_help(): top = Toplevel() top.title("Help ") top.geometry('700x450') menu = Menu(top) # add submenu below three lines new_item = Menu(menu, tearoff=0) new_item.add_command(label='New', command=create_window) new_item.add_command(label='Exit', command=top.quit) new_item2 = Menu(menu, tearoff=0) new_item2.add_command(label='Helical', command=create_window) new_item2.add_command(label='Belleville', command=create_window_2) new_item2.add_command(label='Torsion') new_item2.add_command(label='Constant Force') menu.add_cascade(label='File', menu=new_item) menu.add_cascade(label='Start', menu=new_item2) menu.add_command(label='Save') menu.add_command(label='About', command=about_click) menu.add_command(label='Help') top.config(menu=menu) aakFrame = Frame(top) imageAak = Frame(top) aadFrame = Frame(top) lbl = Label(aakFrame, text="SpriD", font=("Arial B", 16)) lbl.pack(padx=2, pady=2) lbl = Label( aakFrame, wraplength=600, font=("Arial", 12), text= "Sprid is a an open source project currently in beta stage. The complete source can be found at GitHub. Please visit the GitHub documentation of Sprid in case you have any queries or if you want to report a BUG. " ) lbl.pack(padx=2, pady=20) aakFrame.pack() # # TODO: add Image # img = ImageTk.PhotoImage(Image.open("spr2_2.png")) # panel = Label(imageAak, image = img) # panel.pack() # imageAak.pack() lbl = Label(aadFrame, text="Open-Source is love", font=("Arial B", 20)) lbl.pack(padx=2, pady=20) lbl = Label(aadFrame, wraplength=600, font=("Arial", 14), text="https://github.com/AakashSYadav/DME") lbl.pack(padx=2, pady=8) aadFrame.pack()
class ShiftReduceApp: """ A graphical tool for exploring the shift-reduce parser. The tool displays the parser's stack and the remaining text, and allows the user to control the parser's operation. In particular, the user can shift tokens onto the stack, and can perform reductions on the top elements of the stack. A "step" button simply steps through the parsing process, performing the operations that ``nltk.parse.ShiftReduceParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingShiftReduceParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title("Shift Reduce Parser Application") # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animating_lock = 0 self._animate = IntVar(self._top) self._animate.set(10) # = medium # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Initialize fonts. self._init_fonts(self._top) # Set up key bindings. self._init_bindings() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # A popup menu for reducing. self._reduce_menu = Menu(self._canvas, tearoff=0) # Reset the demo, and set the feedback frame to empty. self.reset() self._lastoper1["text"] = "" ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget("size")) self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get()) self._font = Font(family="helvetica", size=self._size.get()) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill="both", side="left", padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text="Available Reductions") self._prodlist_label.pack() self._prodlist = Listbox( self._prodframe, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._prodlist.pack(side="right", fill="both", expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert("end", (" %s" % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if 1: # len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient="vertical") self._prodlist.config(yscrollcommand=listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side="left", fill="y") # If they select a production, apply it. self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select) # When they hover over a production, highlight it. self._hover = -1 self._prodlist.bind("<Motion>", self._highlight_hover) self._prodlist.bind("<Leave>", self._clear_hover) def _init_bindings(self): # Quit self._top.bind("<Control-q>", self.destroy) self._top.bind("<Control-x>", self.destroy) self._top.bind("<Alt-q>", self.destroy) self._top.bind("<Alt-x>", self.destroy) # Ops (step, shift, reduce, undo) self._top.bind("<space>", self.step) self._top.bind("<s>", self.shift) self._top.bind("<Alt-s>", self.shift) self._top.bind("<Control-s>", self.shift) self._top.bind("<r>", self.reduce) self._top.bind("<Alt-r>", self.reduce) self._top.bind("<Control-r>", self.reduce) self._top.bind("<Delete>", self.reset) self._top.bind("<u>", self.undo) self._top.bind("<Alt-u>", self.undo) self._top.bind("<Control-u>", self.undo) self._top.bind("<Control-z>", self.undo) self._top.bind("<BackSpace>", self.undo) # Misc self._top.bind("<Control-p>", self.postscript) self._top.bind("<Control-h>", self.help) self._top.bind("<F1>", self.help) self._top.bind("<Control-g>", self.edit_grammar) self._top.bind("<Control-t>", self.edit_sentence) # Animation speed control self._top.bind("-", lambda e, a=self._animate: a.set(20)) self._top.bind("=", lambda e, a=self._animate: a.set(10)) self._top.bind("+", lambda e, a=self._animate: a.set(4)) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill="none", side="bottom") Button( buttonframe, text="Step", background="#90c0d0", foreground="black", command=self.step, ).pack(side="left") Button( buttonframe, text="Shift", underline=0, background="#90f090", foreground="black", command=self.shift, ).pack(side="left") Button( buttonframe, text="Reduce", underline=0, background="#90f090", foreground="black", command=self.reduce, ).pack(side="left") Button( buttonframe, text="Undo", underline=0, background="#f0a0a0", foreground="black", command=self.undo, ).pack(side="left") def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del") filemenu.add_command( label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p", ) filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x") menubar.add_cascade(label="File", underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command( label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g", ) editmenu.add_command( label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t", ) menubar.add_cascade(label="Edit", underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space") rulemenu.add_separator() rulemenu.add_command(label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s") rulemenu.add_command(label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r") rulemenu.add_separator() rulemenu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u") menubar.add_cascade(label="Apply", underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton( label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar, ) viewmenu.add_separator() viewmenu.add_radiobutton( label="Tiny", variable=self._size, underline=0, value=10, command=self.resize, ) viewmenu.add_radiobutton( label="Small", variable=self._size, underline=0, value=12, command=self.resize, ) viewmenu.add_radiobutton( label="Medium", variable=self._size, underline=0, value=14, command=self.resize, ) viewmenu.add_radiobutton( label="Large", variable=self._size, underline=0, value=18, command=self.resize, ) viewmenu.add_radiobutton( label="Huge", variable=self._size, underline=0, value=24, command=self.resize, ) menubar.add_cascade(label="View", underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0) animatemenu.add_radiobutton( label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator="-", ) animatemenu.add_radiobutton( label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator="=", ) animatemenu.add_radiobutton( label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator="+", ) menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", underline=0, command=self.about) helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1") menubar.add_cascade(label="Help", underline=0, menu=helpmenu) parent.config(menu=menubar) def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text="Last Operation:", font=self._font) self._lastoper_label.pack(side="left") lastoperframe = Frame(feedbackframe, relief="sunken", border=1) lastoperframe.pack(fill="x", side="right", expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font) self._lastoper2 = Label( lastoperframe, anchor="w", width=30, foreground="#004040", background="#f0f0f0", font=self._font, ) self._lastoper1.pack(side="left") self._lastoper2.pack(side="left", fill="x", expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame( parent, background="white", width=525, closeenough=10, border=2, relief="sunken", ) self._cframe.pack(expand=1, fill="both", side="top", pady=2) canvas = self._canvas = self._cframe.canvas() self._stackwidgets = [] self._rtextwidgets = [] self._titlebar = canvas.create_rectangle(0, 0, 0, 0, fill="#c0f0f0", outline="black") self._exprline = canvas.create_line(0, 0, 0, 0, dash=".") self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080") size = self._size.get() + 4 self._stacklabel = TextWidget(canvas, "Stack", color="#004040", font=self._boldfont) self._rtextlabel = TextWidget(canvas, "Remaining Text", color="#004040", font=self._boldfont) self._cframe.add_widget(self._stacklabel) self._cframe.add_widget(self._rtextlabel) ######################################### ## Main draw procedure ######################################### def _redraw(self): scrollregion = self._canvas["scrollregion"].split() (cx1, cy1, cx2, cy2) = (int(c) for c in scrollregion) # Delete the old stack & rtext widgets. for stackwidget in self._stackwidgets: self._cframe.destroy_widget(stackwidget) self._stackwidgets = [] for rtextwidget in self._rtextwidgets: self._cframe.destroy_widget(rtextwidget) self._rtextwidgets = [] # Position the titlebar & exprline (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4) self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10) # Position the titlebar labels.. (x1, y1, x2, y2) = self._stacklabel.bbox() self._stacklabel.move(5 - x1, 3 - y1) (x1, y1, x2, y2) = self._rtextlabel.bbox() self._rtextlabel.move(cx2 - x2 - 5, 3 - y1) # Draw the stack. stackx = 5 for tok in self._parser.stack(): if isinstance(tok, Tree): attribs = { "tree_color": "#4080a0", "tree_width": 2, "node_font": self._boldfont, "node_color": "#006060", "leaf_color": "#006060", "leaf_font": self._font, } widget = tree_to_treesegment(self._canvas, tok, **attribs) widget.label()["color"] = "#000000" else: widget = TextWidget(self._canvas, tok, color="#000000", font=self._font) widget.bind_click(self._popup_reduce) self._stackwidgets.append(widget) self._cframe.add_widget(widget, stackx, y) stackx = widget.bbox()[2] + 10 # Draw the remaining text. rtextwidth = 0 for tok in self._parser.remaining_text(): widget = TextWidget(self._canvas, tok, color="#000000", font=self._font) self._rtextwidgets.append(widget) self._cframe.add_widget(widget, rtextwidth, y) rtextwidth = widget.bbox()[2] + 4 # Allow enough room to shift the next token (for animations) if len(self._rtextwidgets) > 0: stackx += self._rtextwidgets[0].width() # Move the remaining text to the correct location (keep it # right-justified, when possible); and move the remaining text # label, if necessary. stackx = max(stackx, self._stacklabel.width() + 25) rlabelwidth = self._rtextlabel.width() + 10 if stackx >= cx2 - max(rtextwidth, rlabelwidth): cx2 = stackx + max(rtextwidth, rlabelwidth) for rtextwidget in self._rtextwidgets: rtextwidget.move(4 + cx2 - rtextwidth, 0) self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0) midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) (x1, y1, x2, y2) = self._stacklabel.bbox() # Set up binding to allow them to shift a token by dragging it. if len(self._rtextwidgets) > 0: def drag_shift(widget, midx=midx, self=self): if widget.bbox()[0] < midx: self.shift() else: self._redraw() self._rtextwidgets[0].bind_drag(drag_shift) self._rtextwidgets[0].bind_click(self.shift) # Draw the stack top. self._highlight_productions() def _draw_stack_top(self, widget): # hack.. midx = widget.bbox()[2] + 50 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) def _highlight_productions(self): # Highlight the productions that can be reduced. self._prodlist.selection_clear(0, "end") for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Button Callbacks ######################################### def destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._parser.initialize(self._sent) self._lastoper1["text"] = "Reset App" self._lastoper2["text"] = "" self._redraw() def step(self, *e): if self.reduce(): return True elif self.shift(): return True else: if list(self._parser.parses()): self._lastoper1["text"] = "Finished:" self._lastoper2["text"] = "Success" else: self._lastoper1["text"] = "Finished:" self._lastoper2["text"] = "Failure" def shift(self, *e): if self._animating_lock: return if self._parser.shift(): tok = self._parser.stack()[-1] self._lastoper1["text"] = "Shift:" self._lastoper2["text"] = "%r" % tok if self._animate.get(): self._animate_shift() else: self._redraw() return True return False def reduce(self, *e): if self._animating_lock: return production = self._parser.reduce() if production: self._lastoper1["text"] = "Reduce:" self._lastoper2["text"] = "%s" % production if self._animate.get(): self._animate_reduce() else: self._redraw() return production def undo(self, *e): if self._animating_lock: return if self._parser.undo(): self._redraw() def postscript(self, *e): self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) ######################################### ## Menubar callbacks ######################################### def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) # self._stacklabel['font'] = ('helvetica', -size-4, 'bold') # self._rtextlabel['font'] = ('helvetica', -size-4, 'bold') # self._lastoper_label['font'] = ('helvetica', -size) # self._lastoper1['font'] = ('helvetica', -size) # self._lastoper2['font'] = ('helvetica', -size) # self._prodlist['font'] = ('helvetica', -size) # self._prodlist_label['font'] = ('helvetica', -size-2, 'bold') self._redraw() def help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText( self._top, "Help: Shift-Reduce Parser Application", (__doc__ or "").strip(), width=75, font="fixed", ) except: ShowText( self._top, "Help: Shift-Reduce Parser Application", (__doc__ or "").strip(), width=75, ) def about(self, *e): ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper" TITLE = "About: Shift-Reduce Parser Application" try: from tkinter.messagebox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, "end") for production in self._productions: self._prodlist.insert("end", (" %s" % production)) def edit_sentence(self, *e): sentence = " ".join(self._sent) title = "Edit Text" instr = "Enter a new sentence to parse." EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sent): self._sent = sent.split() # [XX] use tagged? self.reset() ######################################### ## Reduce Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill="both", side="left", padx=2, after=self._feedbackframe) self._lastoper1["text"] = "Show Grammar" else: self._prodframe.pack_forget() self._lastoper1["text"] = "Hide Grammar" self._lastoper2["text"] = "" def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) production = self._parser.reduce(self._productions[index]) if production: self._lastoper1["text"] = "Reduce:" self._lastoper2["text"] = "%s" % production if self._animate.get(): self._animate_reduce() else: self._redraw() else: # Reset the production selections. self._prodlist.selection_clear(0, "end") for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) def _popup_reduce(self, widget): # Remove old commands. productions = self._parser.reducible_productions() if len(productions) == 0: return self._reduce_menu.delete(0, "end") for production in productions: self._reduce_menu.add_command(label=str(production), command=self.reduce) self._reduce_menu.post(self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()) ######################################### ## Animations ######################################### def _animate_shift(self): # What widget are we shifting? widget = self._rtextwidgets[0] # Where are we shifting from & to? right = widget.bbox()[0] if len(self._stackwidgets) == 0: left = 5 else: left = self._stackwidgets[-1].bbox()[2] + 10 # Start animating. dt = self._animate.get() dx = (left - right) * 1.0 / dt self._animate_shift_frame(dt, widget, dx) def _animate_shift_frame(self, frame, widget, dx): if frame > 0: self._animating_lock = 1 widget.move(dx, 0) self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx) else: # but: stacktop?? # Shift the widget to the stack. del self._rtextwidgets[0] self._stackwidgets.append(widget) self._animating_lock = 0 # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() def _animate_reduce(self): # What widgets are we shifting? numwidgets = len(self._parser.stack()[-1]) # number of children widgets = self._stackwidgets[-numwidgets:] # How far are we moving? if isinstance(widgets[0], TreeSegmentWidget): ydist = 15 + widgets[0].label().height() else: ydist = 15 + widgets[0].height() # Start animating. dt = self._animate.get() dy = ydist * 2.0 / dt self._animate_reduce_frame(dt / 2, widgets, dy) def _animate_reduce_frame(self, frame, widgets, dy): if frame > 0: self._animating_lock = 1 for widget in widgets: widget.move(0, dy) self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy) else: del self._stackwidgets[-len(widgets):] for widget in widgets: self._cframe.remove_widget(widget) tok = self._parser.stack()[-1] if not isinstance(tok, Tree): raise ValueError() label = TextWidget(self._canvas, str(tok.label()), color="#006060", font=self._boldfont) widget = TreeSegmentWidget(self._canvas, label, widgets, width=2) (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 if not self._stackwidgets: x = 5 else: x = self._stackwidgets[-1].bbox()[2] + 10 self._cframe.add_widget(widget, x, y) self._stackwidgets.append(widget) # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() # # Delete the old widgets.. # del self._stackwidgets[-len(widgets):] # for widget in widgets: # self._cframe.destroy_widget(widget) # # # Make a new one. # tok = self._parser.stack()[-1] # if isinstance(tok, Tree): # attribs = {'tree_color': '#4080a0', 'tree_width': 2, # 'node_font': bold, 'node_color': '#006060', # 'leaf_color': '#006060', 'leaf_font':self._font} # widget = tree_to_treesegment(self._canvas, tok.type(), # **attribs) # widget.node()['color'] = '#000000' # else: # widget = TextWidget(self._canvas, tok.type(), # color='#000000', font=self._font) # widget.bind_click(self._popup_reduce) # (x1, y1, x2, y2) = self._stacklabel.bbox() # y = y2-y1+10 # if not self._stackwidgets: x = 5 # else: x = self._stackwidgets[-1].bbox()[2] + 10 # self._cframe.add_widget(widget, x, y) # self._stackwidgets.append(widget) # self._redraw() self._animating_lock = 0 ######################################### ## Hovering. ######################################### def _highlight_hover(self, event): # What production are we hovering over? index = self._prodlist.nearest(event.y) if self._hover == index: return # Clear any previous hover highlighting. self._clear_hover() # If the production corresponds to an available reduction, # highlight the stack. selection = [int(s) for s in self._prodlist.curselection()] if index in selection: rhslen = len(self._productions[index].rhs()) for stackwidget in self._stackwidgets[-rhslen:]: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.label()["color"] = "#00a000" else: stackwidget["color"] = "#00a000" # Remember what production we're hovering over. self._hover = index def _clear_hover(self, *event): # Clear any previous hover highlighting. if self._hover == -1: return self._hover = -1 for stackwidget in self._stackwidgets: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.label()["color"] = "black" else: stackwidget["color"] = "black"
def create_window_about(): top = Toplevel() top.title("About Us ") top.geometry('700x450') menu = Menu(top) # add submenu below three lines new_item = Menu(menu, tearoff=0) new_item.add_command(label='New', command=create_window) new_item.add_command(label='Exit', command=top.quit) new_item2 = Menu(menu, tearoff=0) new_item2.add_command(label='Helical', command=create_window) new_item2.add_command(label='Belleville', command=create_window_2) new_item2.add_command(label='Torsion') new_item2.add_command(label='Constant Force') menu.add_cascade(label='File', menu=new_item) menu.add_cascade(label='Start', menu=new_item2) menu.add_command(label='Save') menu.add_command(label='About', command=about_click) menu.add_command(label='Help') top.config(menu=menu) aakFrame = Frame(top) imageAak = Frame(top) aadFrame = Frame(top) lbl = Label(aakFrame, text="Mr. Aakash Yadav", font=("Arial B", 16)) lbl.pack(padx=2, pady=2) lbl = Label( aakFrame, wraplength=600, font=("Arial", 12), text= "He is a tech enthusiast and is associated with app development (UI/UX), IoT, Robotics to name a few. He is currently pursuing Mechanical Engineering at Indian Institute of Technology Tirupati. He belives that consumer experience is most important pillar in developement of a product" ) lbl.pack(padx=2, pady=2) aakFrame.pack() # TODO: add Image img = ImageTk.PhotoImage(Image.open("spr2_2.png")) panel = Label(imageAak, image=img) panel.pack() imageAak.pack() lbl = Label(aadFrame, text="Mr. Aditya Kumar Choudhary", font=("Arial B", 16)) lbl.pack(padx=2, pady=2) lbl = Label( aadFrame, wraplength=600, font=("Arial", 12), text= "He is currently pursuing B.Tech in Mechanical engineering from IIT Tirupati. He is very interested in physics and specially in mechanics. He is also a gaming enthusiast and play a lot of e-games. Currently his favourite game is Dota 2. After his under-grad he wishes to go for a research oriented job in mechanical engineering. He is currently doing a research project with prof. Shree Ram Valluri of University of Western Ontario, Canada." ) lbl.pack(padx=2, pady=2) aadFrame.pack()
def createWidgets(self): # Tab Control introduced here -------------------------------------- tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab # tabControl.add(tab1, text='MySQL') # Add the tab -- COMMENTED OUT FOR CH08 tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Widgets') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # ~ Tab Control introduced here ----------------------------------------- # We are creating a container frame to hold all other widgets self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ') self.mySQL.grid(column=0, row=0, padx=8, pady=4) # Creating a Label ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget book = tk.StringVar() self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book) self.bookTitle.grid(column=0, row=1, sticky='W') # Adding a Textbox Entry widget book1 = tk.StringVar() self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1) self.bookTitle1.grid(column=0, row=2, sticky='W') # Adding a Textbox Entry widget book2 = tk.StringVar() self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2) self.bookTitle2.grid(column=0, row=3, sticky='W') # Creating a Label ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber.grid(column=1, row=1, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber1.grid(column=1, row=2, sticky='W') # Adding a Textbox Entry widget page = tk.StringVar() self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page) self.pageNumber2.grid(column=1, row=3, sticky='W') # Adding a Button self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.callBacks.insertQuote) self.action.grid(column=2, row=1) # Adding a Button self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.callBacks.getQuote) self.action1.grid(column=2, row=2) # Adding a Button self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.callBacks.modifyQuote) self.action2.grid(column=2, row=3) # Add some space around each widget for child in self.mySQL.winfo_children(): child.grid_configure(padx=2, pady=4) quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ') quoteFrame.grid(column=0, row=1, padx=8, pady=4) # Using a scrolled Text control quoteW = 40 quoteH = 6 self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD) self.quote.grid(column=0, row=8, sticky='WE', columnspan=3) # Add some space around each widget for child in quoteFrame.winfo_children(): child.grid_configure(padx=2, pady=4) #====================================================================================================== # Tab Control 2 #====================================================================================================== # We are creating a container frame to hold all other widgets -- Tab2 self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL) self.widgetFrame.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons self.chVarDis = tk.IntVar() self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled') self.check1.select() self.check1.grid(column=0, row=0, sticky=tk.W) self.chVarUn = tk.IntVar() self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn) self.check2.deselect() self.check2.grid(column=1, row=0, sticky=tk.W) self.chVarEn = tk.IntVar() self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn) self.check3.deselect() self.check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons self.chVarUn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) self.chVarEn.trace( 'w', lambda unused0, unused1, unused2: self.checkCallback()) # Radiobutton list colors = self.i18n.colors self.radVar = tk.IntVar() # Selecting a non-existing index value for radVar self.radVar.set(99) # Creating all three Radiobutton widgets within one loop for col in range(3): self.curRad = 'rad' + str(col) self.curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.callBacks.radCall) self.curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3) # And now adding tooltips tt.createToolTip(self.curRad, 'This is a Radiobutton control.') # Create a container to hold labels labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame) labelsFrame.grid(column=0, row=7, pady=6) # Place labels into the container element - vertically ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0) self.lbl2 = tk.StringVar() self.lbl2.set(self.i18n.label2) ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1) # Add some space around each label for child in labelsFrame.winfo_children(): child.grid_configure(padx=6, pady=1) number = tk.StringVar() self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number) self.combo['values'] = (1, 2, 4, 42, 100) self.combo.grid(column=1, row=7, sticky=tk.W) self.combo.current(0) self.combo.bind('<<ComboboxSelected>>', self.callBacks._combo) # Adding a Spinbox widget using a set of values self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self.callBacks._spin) self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1) # Using a scrolled Text control scrolW = 40 scrolH = 1 self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD) self.scr.grid(column=0, row=8, sticky='WE', columnspan=3) # Adding a TZ Button self.allTZs = ttk.Button(self.widgetFrame, text=self.i18n.timeZones, command=self.callBacks.allTimeZones) self.allTZs.grid(column=0, row=9, sticky='WE') # Adding local TZ Button self.localTZ = ttk.Button(self.widgetFrame, text=self.i18n.localZone, command=self.callBacks.localZone) self.localTZ.grid(column=1, row=9, sticky='WE') # Adding getTime TZ Button self.dt = ttk.Button(self.widgetFrame, text=self.i18n.getTime, command=self.callBacks.getDateTime) self.dt.grid(column=2, row=9, sticky='WE') # Create Manage Files Frame ------------------------------------------------ mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles) mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print(fName) self.fileEntry.config(state='enabled') self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) if len(fName) > self.entryLen: self.fileEntry.config(width=len(fName) + 3) # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) #----------------------------------------------------- file = tk.StringVar() self.entryLen = scrolW - 4 self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.grid(column=1, row=0, sticky=tk.W) #----------------------------------------------------- logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() file = src.split('/')[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Succes: File copied.') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as ex: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex)) cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) # Creating a Menu Bar ========================================================== menuBar = Menu(tab1) self.win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label=self.i18n.new) fileMenu.add_separator() fileMenu.add_command(label=self.i18n.exit, command=self.callBacks._quit) menuBar.add_cascade(label=self.i18n.file, menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label=self.i18n.about) menuBar.add_cascade(label=self.i18n.help, menu=helpMenu) # Change the main windows icon self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico') # Using tkinter Variable Classes strData = tk.StringVar() strData.set('Hello StringVar') # It is not necessary to create a tk.StringVar() strData = tk.StringVar() strData = self.spin.get() # Place cursor into name Entry self.bookTitle.focus() # Add a Tooltip to the Spinbox tt.createToolTip(self.spin, 'This is a Spin control.') # Add Tooltips to more widgets tt.createToolTip(self.bookTitle, 'This is an Entry control.') tt.createToolTip(self.action, 'This is a Button control.') tt.createToolTip(self.scr, 'This is a ScrolledText control.')
def create_window_2(): top = Toplevel() top.title("SpriD") top.geometry('700x450') lbl = Label(top, text="Come back soon !", font=("Arial Bold", 30)) # button1.pack(fill=X,pady=5) lbl.grid(column=0, row=0, padx=160, pady=120) menu = Menu(top) # add submenu below three lines new_item = Menu(menu, tearoff=0) new_item.add_command(label='New', command=create_window) new_item.add_command(label='Exit', command=top.quit) new_item2 = Menu(menu, tearoff=0) new_item2.add_command(label='Helical', command=create_window) new_item2.add_command(label='Belleville', command=create_window_2) new_item2.add_command(label='Torsion') new_item2.add_command(label='Constant Force') menu.add_cascade(label='File', menu=new_item) menu.add_cascade(label='Start', menu=new_item2) menu.add_command(label='Save') menu.add_command(label='About', command=about_click) menu.add_command(label='Help') top.config(menu=menu)
def create_widgets(self): tabControl = ttk.Notebook(self.win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Modify adding a Label using mighty as the parent instead of win a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') # Adding a Textbox Entry widget self.name = tk.StringVar() name_entered = ttk.Entry(mighty, width=24, textvariable=self.name) name_entered.grid(column=0, row=1, sticky='W') # Adding a Button self.action = ttk.Button(mighty, text="Click Me!", command=self.click_me) self.action.grid(column=2, row=1) ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) number = tk.StringVar() self.number_chosen = ttk.Combobox(mighty, width=14, textvariable=number, state='readonly') self.number_chosen['values'] = (1, 2, 4, 42, 100) self.number_chosen.grid(column=1, row=1) self.number_chosen.current(0) # Adding a Spinbox widget self.spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) # using range self.spin.grid(column=0, row=2, sticky='W') # Using a scrolled Text control scrol_w = 40 scrol_h = 10 self.scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) # Tab Control 2 ---------------------------------------------------------------------- # We are creating a container frame to hold all other widgets -- Tab2 self.mighty2 = ttk.LabelFrame(tab2, text=' The Snake ') self.mighty2.grid(column=0, row=0, padx=8, pady=4) # Creating three checkbuttons chVarDis = tk.IntVar() check1 = tk.Checkbutton(self.mighty2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=0, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(self.mighty2, text="UnChecked", variable=chVarUn) check2.deselect() check2.grid(column=1, row=0, sticky=tk.W) chVarEn = tk.IntVar() check3 = tk.Checkbutton(self.mighty2, text="Enabled", variable=chVarEn) check3.deselect() check3.grid(column=2, row=0, sticky=tk.W) # trace the state of the two checkbuttons chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback()) # First, we change our Radiobutton global variables into a list colors = ["Blue", "Gold", "Red"] # create three Radiobuttons using one variable self.radVar = tk.IntVar() # Next we are selecting a non-existing index value for radVar self.radVar.set(99) # Now we are creating all three Radiobutton widgets within one loop for col in range(3): curRad = tk.Radiobutton(self.mighty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall) curRad.grid(column=col, row=1, sticky=tk.W) # row=6 # Add a Progressbar to Tab 2 self.progress_bar = ttk.Progressbar(tab2, orient='horizontal', length=286, mode='determinate') self.progress_bar.grid(column=0, row=3, pady=2) # Create a container to hold buttons buttons_frame = ttk.LabelFrame(self.mighty2, text=' ProgressBar ') buttons_frame.grid(column=0, row=2, sticky='W', columnspan=2) # Add Buttons for Progressbar commands ttk.Button(buttons_frame, text=" Run Progressbar ", command=self.run_progressbar).grid(column=0, row=0, sticky='W') ttk.Button(buttons_frame, text=" Start Progressbar ", command=self.start_progressbar).grid(column=0, row=1, sticky='W') ttk.Button(buttons_frame, text=" Stop immediately ", command=self.stop_progressbar).grid(column=0, row=2, sticky='W') ttk.Button(buttons_frame, text=" Stop after second ", command=self.progressbar_stop_after).grid(column=0, row=3, sticky='W') for child in buttons_frame.winfo_children(): child.grid_configure(padx=2, pady=2) for child in self.mighty2.winfo_children(): child.grid_configure(padx=8, pady=2) # Creating a Menu Bar menu_bar = Menu(self.win) self.win.config(menu=menu_bar) # Add menu items file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New") file_menu.add_separator() file_menu.add_command(label="Exit", command=self._quit) menu_bar.add_cascade(label="File", menu=file_menu) ############################################################################ # Create Manage Files Frame mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ') mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5) # Button Callback def getFileName(): print('hello from getFileName') # fDir = path.dirname(__file__) fName = fd.askopenfilename(parent=self.win, initialdir=fDir) print("fName: " + fName) self.fileEntry.delete(0, tk.END) self.fileEntry.insert(0, fName) self.fileEntry.config(width=len(fName) + 3) # self.fileEntry.config(state='readonly') # Add Widgets to Manage Files Frame lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName) lb.grid(column=0, row=0, sticky=tk.W) file = tk.StringVar() self.entryLen = scrol_w self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file) self.fileEntry.bind("<Return>", (lambda event: copyFile())) self.fileEntry.grid(column=1, row=0, sticky=tk.W) logDir = tk.StringVar() self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir) self.netwEntry.grid(column=1, row=1, sticky=tk.W) def copyFile(): import shutil src = self.fileEntry.get() if len(src.split('/')) > 2: file = src.split('/')[-1] else: file = src.split("\\")[-1] dst = self.netwEntry.get() + '\\' + file try: shutil.copy(src, dst) mBox.showinfo('Copy File to Network', 'Success: File copied') except FileNotFoundError as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) except Exception as err: mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err)) cb = ttk.Button(mngFilesFrame, text="Copy File To : ", command=copyFile) cb.grid(column=0, row=1, sticky=tk.E) # Add some space around each label for child in mngFilesFrame.winfo_children(): child.grid_configure(padx=6, pady=6) ########################################################################### # Display a Message Box def _msgBox(): msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.') # Add another Menu to the Menu Bar and an item help_menu = Menu(menu_bar, tearoff=0) help_menu.add_command(label="About", command=_msgBox) # display messagebox when clicked menu_bar.add_cascade(label="Help", menu=help_menu) # Change the main windows icon # self.win.iconbitmap('pyc.ico') # It is not necessary to create a tk.StringVar() # strData = tk.StringVar() strData = self.spin.get() print("Spinbox value: " + strData) # call function self.usingGlobal() #name_entered.focus() tabControl.select(1)
def create_window(): top = Toplevel() top.title("Helical Spring Design") top.geometry('700x450') #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESIGN.py DEFINITIONS function for static load def calcMain(): flag = 0 # def calcMain(fmax, ymax, freelength, solidlength, material, endCondition): # if inout in si if var.get() == 2: fmax = float(txt_fmax.get()) / 4.44822 ymax = float(txt_ymax.get()) / 25.4 freelength = float(txt_freelength.get()) / 25.4 solidlength = float(txt_solidlength.get()) / 25.4 # if input in US elif var.get() == 1: fmax = float(txt_fmax.get()) ymax = float(txt_ymax.get()) freelength = float(txt_freelength.get()) solidlength = float(txt_solidlength.get()) else: messagebox.showinfo('Error 207!', 'Please select the unit') #initial guess for 'd' d = 0.001 counter = 0 while d > 0: # factor of safety # TODO: take input ns = 1.2 # fixed pg510 zeta = 0.15 #for fom gama = 1 #for music wire ## TODO: reduce size material = combo_mat.get() if material == 'A228': if d < 0.033: E = 29.5 * 1000000 G = 12 * 1000000 elif d >= 0.033 and d <= 0.063: E = 29 * 1000000 G = 11.85 * 1000000 elif d > 0.063 and d <= 0.125: E = 28.5 * 1000000 G = 11.75 * 1000000 elif d > 0.125: E = 28 * 1000000 G = 11.6 * 1000000 A = A228[1] * 1000 m = A228[0] # E=A228[2]*1000000 # G=A228[3]*1000000 rc = A228[5] if material == 'A229': if d < 0.033: E = 28.8 * 1000000 G = 11.7 * 1000000 elif d >= 0.033 and d <= 0.063: E = 28.7 * 1000000 G = 11.6 * 1000000 elif d > 0.063 and d <= 0.125: E = 28.6 * 1000000 G = 11.5 * 1000000 elif d > 0.125: E = 28.5 * 1000000 G = 11.4 * 1000000 A = A229[1] * 1000 m = A229[0] # E=A229[2]*1000000 # G=A229[3]*1000000 rc = A229[5] if material == 'A227': A = A227[1] * 1000 m = A227[0] E = A227[2] * 1000000 G = A227[3] * 1000000 rc = A227[5] if material == 'A232': A = A232[1] * 1000 m = A232[0] E = A232[2] * 1000000 G = A232[3] * 1000000 rc = A232[5] if material == 'A401': A = A401[1] * 1000 m = A401[0] E = A401[2] * 1000000 G = A401[3] * 1000000 rc = A401[5] # A = 201000 ; # relative cost for mausc wire # rc = 2.6; # kpsi inch # m = 0.145; #E = 28.5; # G = 11750000; sut = A / (d**m) ssy = 0.45 * sut alpha = ssy / ns beta = (8 * (1 + zeta) * fmax) / (pi * (d**2)) C = (2 * alpha - beta) / (4 * beta) + (((2 * alpha - beta) / (4 * beta))**2 - (3 * alpha) / (4 * beta))**(0.5) D = d * C # kb = (4*C+ 2)/(4*C - 3); # taus = (kb*8*(1+zeta)*fmax*D)/(3.147*(d^3)); # OD = D+d; Na = (G * (d**4) * ymax) / (8 * (D**3) * fmax) # checking end condition combo_end['values'] = ('Plain', 'Plain-Ground', 'Square-Closed', 'Square-Ground') endCondition = combo_end.get() if endCondition == 'Plain': Nt = Na ls = d * (Nt + 1) if endCondition == 'Plain-Ground': Nt = Na + 1 ls = d * Nt if endCondition == 'Square-Closed': Nt = Na + 2 ls = d * (Nt + 1) if endCondition == 'Square-Ground': Nt = Na + 2 ls = d * Nt lo = ls + (1 + zeta) * ymax fom = -rc * gama * (pi**2) * (d**2) * Nt * D * 0.25 if isinstance(C, complex) or isinstance(Na, complex) or isinstance( ls, complex) or isinstance(lo, complex): print('complex values') elif (C >= 4 and C <= 12 and Na >= 3 and Na <= 15 and ls < solidlength and lo < freelength): # break # return D, d, Na, ls, lo, fom if counter == 0: if var.get() == 2: xD = round(D * 25.4, 3) xd = round(d * 25.4, 3) xls = round(ls * 25.4, 3) xlo = round(lo * 25.4, 3) elif var.get() == 1: xD = round(D, 3) xd = round(d, 3) xls = round(ls, 3) xlo = round(lo, 3) # fmax=float(txt_fmax.get()) # ymax=float(txt_ymax.get()) # freelength=float(txt_freelength.get()) # solidlength=float(txt_solidlength.get()) else: messagebox.showinfo('Error 208!', 'Please select the unit') # xD=D # xd=d flag = 1 xNa = round(Na, 3) # xls=ls # xlo=lo xfom = round(fom, 4) counter = counter + 1 d_ar.append(d) fom_ar.append(fom) f = open("res.txt", "a+") f.write("Wire diameter %f\r\n" % d) f.write("Spring diameter %f\r\n" % D) f.write("Na %f\r\n" % Na) f.write("ls %f\r\n" % ls) f.write("lo %f\r\n" % lo) f.write("Figure of merit %f\r\n" % fom) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') f.write("_______________________________\n") f.write(st) f.write("_______________________________\n") f.close() elif d > 1: print("iteration stopped") # messagebox.showinfo("Sorry! couldn't design the spring\nTIP:try different input") break d = d + 0.001 # print(xD, xd, xNa, xls, xlo, xfom) if flag == 0: messagebox.showinfo('Error 219!', 'Please try some other values') else: if var.get() == 2: res = "Spring diameter " + str( xD) + "mm\nWire diameter " + str(xd) + "mm\nNa " + str( xNa) + "\nls " + str(xls) + "mm\nlo " + str( xlo) + "mm\nFigure of merit " + str(xfom) if var.get() == 1: res = "Spring diameter " + str( xD) + "inch\nWire diameter " + str(xd) + "inch\nNa " + str( xNa) + "\nls " + str(xls) + "inch\nlo " + str( xlo) + "inch\nFigure of merit " + str(xfom) lbl_res.configure(text=res) # if var.get()==2: # res = "Spring diameter " + str(xD) + "mm\nWire diameter "+str(xd)+"mm\nNa "+str(xNa)+"\nls "+str(xls)+"mm\nlo "+str(xlo)+"mm\nFigure of merit "+str(xfom) # if var.get()==1: # res = "Spring diameter " + str(xD) + "inch\nWire diameter "+str(xd)+"inch\nNa "+str(xNa)+"\nls "+str(xls)+"inch\nlo "+str(xlo)+"inch\nFigure of merit "+str(xfom) # # res = "Spring diameter " + str(xD) + "\nWire diameter "+str(xd)+"\nNa "+str(xNa)+"\nls "+str(xls)+"\nlo "+str(xlo)+"\nFigure of merit "+str(xfom) # lbl_res.configure(text= res) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^from brain ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ def calcMain_d(): # def calcMain(fmax, ymax, freelength, solidlength, material, endCondition): # if inout in si flag = 0 print("cnjsd") if var_d.get() == 2: fmax = float(txt_d_fmax.get()) / 4.44822 fmin = float(txt_d_fmin.get()) / 4.44822 sprrt = float(txt_d_spr_rate.get()) / 25.4 # if input in US elif var_d.get() == 1: fmax = float(txt_d_fmax.get()) fmin = float(txt_d_fmin.get()) sprrt = float(txt_d_spr_rate.get()) else: messagebox.showinfo('Error 209!', 'Please select the unit') #initial guess for 'd' d = 0.001 counter = 0 while d > 0: print("while") print(d) # factor of safety # TODO: take input ns = 1.5 # fixed pg510 zeta = 0.15 #for fom gama = 1 famp = (fmax - fmin) * 0.5 fmean = (fmax + fmin) * 0.5 material = combo_d_mat.get() if material == 'A228': if d < 0.033: E = 29.5 * 1000000 G = 12 * 1000000 elif d >= 0.033 and d <= 0.063: E = 29 * 1000000 G = 11.85 * 1000000 elif d > 0.063 and d <= 0.125: E = 28.5 * 1000000 G = 11.75 * 1000000 elif d > 0.125: E = 28 * 1000000 G = 11.6 * 1000000 A = A228[1] * 1000 #201 m = A228[0] #0.145 # E=A228[2]*1000000 # G=A228[3]*1000000 rc = A228[5] if material == 'A229': if d < 0.033: E = 28.8 * 1000000 G = 11.7 * 1000000 elif d >= 0.033 and d <= 0.063: E = 28.7 * 1000000 G = 11.6 * 1000000 elif d > 0.063 and d <= 0.125: E = 28.6 * 1000000 G = 11.5 * 1000000 elif d > 0.125: E = 28.5 * 1000000 G = 11.4 * 1000000 A = A229[1] * 1000 m = A229[0] # E=A229[2]*1000000 # G=A229[3]*1000000 rc = A229[5] if material == 'A227': A = A227[1] * 1000 m = A227[0] E = A227[2] * 1000000 G = A227[3] * 1000000 rc = A227[5] if material == 'A232': A = A232[1] * 1000 m = A232[0] E = A232[2] * 1000000 G = A232[3] * 1000000 rc = A232[5] if material == 'A401': A = A401[1] * 1000 m = A401[0] E = A401[2] * 1000000 G = A401[3] * 1000000 rc = A401[5] sut = A / (d**m) print(sut) ssy = 0.45 * sut sse = 0.2 * sut ssu = 0.67 * sut # combo_d_fail['values']= ('Soderberg','Gerber','Gough','Yield','Goodman') critera = combo_d_fail.get() if critera == "Goodman": eqn = (((4 * x + 2) * 8 * (1 + zeta) * x * ns) / (pi * d * d)) * (famp / sse + fmean / sut) + 3 - 4 * x elif critera == "Yield": eqn = (((4 * x + 2) * 8 * (1 + zeta) * x * ns) / (pi * d * d)) * (famp / ssy + fmean / ssy) + 3 - 4 * x elif critera == "Gough": eqn = (((4 * x + 2) * (8 * x) / (pi * d * d))**2) * ((famp**2) / (sse**2) + (fmean**2) / (sut**2)) - ((4 * x - 3) * (4 * x - 3)) / ns elif critera == "Gerber": eqn = (1 + zeta) * (4 * x + 2) * 8 * (x / (pi * d * d)) * ( (famp / sse) * (4 * x - 3) + (1 + zeta) * (4 * x + 2) * 8 * (x / (pi * d * d)) * (fmean / sut)) - (4 * x - 3) * (4 * x - 3) / ns elif critera == "Soderberg": eqn = (((4 * x + 2) * 8 * (1 + zeta) * x * ns) / (pi * d * d)) * (famp / sse + fmean / ssy) + 3 - 4 * x # else: # eqn = (((4*x+2)*8*(1+zeta)*x*ns)/(pi*d*d))*(famp/sse+fmean/sut)+3-4*x # temp = ns*4*(1+zeta)*(famp/sse + fmean/ssy) # eqn = 4*(x**2)*temp + 2*temp*x-4*x+3 # eqn = (((4*x+2)*8*(1+zeta)*x*ns)/(pi*d*d))*(famp/sse+fmean/sut)+3-4*x c = solve(eqn, x) print(c) for tt in c: print(tt) hj = str(tt) # hj=hj.replace('*','') # uio=hj.find('I') # uio-=1 # io='' # while hj[uio]!='+' and hj[uio]!='-': # io+=hj[uio] # uio-=1 # io=io[::-1] # print("io",io) # if float(io)!=0: # print("complex") if 'I' in hj: print("complex") elif (tt >= 4 and tt <= 12): C = N(tt) # print(N(tt)) D = d * C # kb = (4*C+ 2)/(4*C - 3); # taus = (kb*8*(1+zeta)*fmax*D)/(3.147*(d^3)); # OD = D+d; Na = (G * (d**4)) / (8 * (D**3) * sprrt) # checking end condition combo_d_end['values'] = ('Plain', 'Plain-Ground', 'Square-Closed', 'Square-Ground') endCondition = combo_d_end.get() if endCondition == 'Plain': Nt = Na ls = d * (Nt + 1) if endCondition == 'Plain-Ground': Nt = Na + 1 ls = d * Nt if endCondition == 'Square-Closed': Nt = Na + 2 ls = d * (Nt + 1) if endCondition == 'Square-Ground': Nt = Na + 2 ls = d * Nt ymax = fmax / sprrt lo = ls + (1 + zeta) * ymax fom = -rc * gama * (pi**2) * (d**2) * Nt * D * 0.25 if isinstance(C, complex) or isinstance( Na, complex) or isinstance( ls, complex) or isinstance(lo, complex): print('complex values') elif (C >= 4 and C <= 12 and Na >= 3 and Na <= 15): # break # return D, d, Na, ls, lo, fom if counter == 0: if var_d.get() == 2: xD = round(D * 25.4, 3) xd = round(d * 25.4, 3) xls = round(ls * 25.4, 3) xlo = round(lo * 25.4, 3) if var_d.get() == 1: xD = round(D, 3) xd = round(d, 3) xls = round(ls, 3) xlo = round(lo, 3) # fmax=float(txt_fmax.get()) # ymax=float(txt_ymax.get()) # freelength=float(txt_freelength.get()) # solidlength=float(txt_solidlength.get()) # xD=D # xd=d xNa = round(Na, 3) flag = 1 # xls=ls # xlo=lo xfom = round(fom, 4) counter = counter + 1 f = open("res.txt", "a+") f.write("Wire diameter %f\r\n" % d) f.write("Spring diameter %f\r\n" % D) f.write("Na %f\r\n" % Na) f.write("ls %f\r\n" % ls) f.write("lo %f\r\n" % lo) f.write("Figure of merit %f\r\n" % fom) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') f.write("_______________________________\n") f.write(st) f.write("_______________________________\n") f.close() if d > 1: print("iteration stopped") # messagebox.showinfo("Sorry! couldn't design the spring\nTIP:try different input") break d = d + 0.01 print("while end") # print(xD, xd, xNa, xls, xlo, xfom) if flag == 0: messagebox.showinfo('Error 211!', 'Please try some other values') else: if var_d.get() == 2: res_d = "Spring diameter " + str( xD) + "mm\nWire diameter " + str(xd) + "mm\nNt " + str( xNa) + "\nls " + str(xls) + "mm\nlo " + str( xlo) + "mm\nFigure of merit " + str(xfom) if var_d.get() == 1: res_d = "Spring diameter " + str( xD) + "inch\nWire diameter " + str(xd) + "inch\nNt " + str( xNa) + "\nls " + str(xls) + "inch\nlo " + str( xlo) + "inch\nFigure of merit " + str(xfom) lbl_d_res.configure(text=res_d) # print(round(2.675, 2)) # res = "Spring diameter " + str(xD) + "\nWire diameter "+str(xd)+"\nNa "+str(xNa)+"\nls "+str(xls)+"\nlo "+str(xlo)+"\nFigure of merit "+str(xfom) #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^from brain ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ def callback(event): webbrowser.open_new(r"file://file/home/aakash/DME/res.txt") #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ radio units def rad_si(): lbl_ut_fmx.configure(text="N") lbl_ut_ymx.configure(text="mm") lbl_ut_freelen.configure(text="mm") lbl_ut_solidlen.configure(text="mm") def rad_us(): lbl_ut_fmx.configure(text="lbf") lbl_ut_ymx.configure(text="inch") lbl_ut_freelen.configure(text="inch") lbl_ut_solidlen.configure(text="inch") def rad_d_si(): lbl_d_ut_fmx.configure(text="N") lbl_d_ut_fmin.configure(text="N") lbl_d_ut_spring_rate.configure(text="N/mm") def rad_d_us(): lbl_d_ut_fmx.configure(text="lbf") lbl_d_ut_fmin.configure(text="lbf") lbl_d_ut_spring_rate.configure(text="lbf/inch") def showGraph(): plt.plot(d_ar, fom_ar, 'ro') plt.xlabel('Wire diameter') plt.ylabel('FoM') plt.title('FoM vs Wire diameter') plt.show() #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ radio units #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # adding a menu menu = Menu(top) # add submenu below three lines new_item = Menu(menu, tearoff=0) new_item.add_command(label='New', command=create_window) new_item.add_command(label='Exit', command=top.quit) new_item2 = Menu(menu, tearoff=0) new_item2.add_command(label='Helical', command=create_window) new_item2.add_command(label='Belleville', command=create_window_2) new_item2.add_command(label='Torsion') new_item2.add_command(label='Constant Force') menu.add_cascade(label='File', menu=new_item) menu.add_cascade(label='Start', menu=new_item2) menu.add_command(label='Save') menu.add_command(label='About', command=about_click) menu.add_command(label='Help') top.config(menu=menu) note = ttk.Notebook(top) tab1 = ttk.Frame(note) headFrame = Frame(tab1) toolbar1 = Frame(tab1) toolbar2 = Frame(tab1) toolbar3 = Frame(tab1) toolbar4 = Frame(tab1) calcFrame = Frame(tab1) toolbar5 = Frame(tab1) toolbar6 = Frame(tab1) toolbar7 = Frame(tab1) footFrame = Frame(tab1) lbl = Label(headFrame, text="Input the given params", font=("Arial B", 14)) lbl.pack(padx=2, pady=2) headFrame.pack(side=TOP, fill=X, padx=4, pady=20) lbl = Label(toolbar1, text="Maximum force", width=15) lbl.pack(side=LEFT, padx=2, pady=2) txt_fmax = Entry(toolbar1, width=10) txt_fmax.pack(side=LEFT, padx=2, pady=2) txt_fmax.focus() lbl_ut_fmx = Label(toolbar1, text="", font=("Arial B", 10), width=6) lbl_ut_fmx.pack(side=LEFT, padx=2, pady=2) lbl = Label(toolbar1, text="ymax", width=15) lbl.pack(side=LEFT, padx=2, pady=2) txt_ymax = Entry(toolbar1, width=10) txt_ymax.pack(side=LEFT, padx=2, pady=2) lbl_ut_ymx = Label(toolbar1, text="", font=("Arial B", 10), width=6) lbl_ut_ymx.pack(side=LEFT, padx=2, pady=2) toolbar1.pack(fill=X, padx=70) lbl = Label(toolbar2, text="Free Length", width=15) lbl.pack(side=LEFT, padx=2, pady=2) txt_freelength = Entry(toolbar2, width=10) txt_freelength.pack(side=LEFT, padx=2, pady=2) lbl_ut_freelen = Label(toolbar2, text="", font=("Arial B", 10), width=6) lbl_ut_freelen.pack(side=LEFT, padx=2, pady=2) lbl = Label(toolbar2, text="End condition", width=15) lbl.pack(side=LEFT, padx=2, pady=2) # txt = Entry(toolbar2,width=10) # txt.pack(side=LEFT, padx=2, pady=2) combo_end = Combobox(toolbar2, width=10) combo_end['values'] = ('Plain', 'Plain-Ground', 'Square-Closed', 'Square-Ground') combo_end.current(1) #set the selected item combo_end.pack(side=LEFT, padx=2, pady=2) # lbl = Label(toolbar2, text="m/s^2",font=("Arial B", 10), width=6) # lbl.pack(side=LEFT, padx=2, pady=2) toolbar2.pack(fill=X, padx=70) lbl = Label(toolbar3, text="Solid Length", width=15) lbl.pack(side=LEFT, padx=2, pady=2) txt_solidlength = Entry(toolbar3, width=10) txt_solidlength.pack(side=LEFT, padx=2, pady=2) lbl_ut_solidlen = Label(toolbar3, text="", font=("Arial B", 10), width=6) lbl_ut_solidlen.pack(side=LEFT, padx=2, pady=2) lbl = Label(toolbar3, text="Material", width=15) lbl.pack(side=LEFT, padx=2, pady=2) combo_mat = Combobox(toolbar3, width=5) combo_mat['values'] = ('A227', 'A228', 'A229', 'A232', 'A401') combo_mat.current(1) #set the selected item combo_mat.pack(side=LEFT, padx=2, pady=2) toolbar3.pack(fill=X, padx=70) lbl = Label(toolbar4, text="Output Units", width=15) lbl.pack(side=LEFT, padx=2, pady=2) rad1 = Radiobutton(toolbar4, text='US', value=1, variable=var, command=rad_us) rad1.pack(side=LEFT, padx=2, pady=2) rad2 = Radiobutton(toolbar4, text='SI', value=2, variable=var, command=rad_si) rad2.pack(side=LEFT, padx=2, pady=2) toolbar4.pack(fill=X, padx=70) b = Button(calcFrame, text="Calculate", command=calcMain) b.pack() b = Button(calcFrame, text="Show graph", command=showGraph) b.pack() calcFrame.pack(fill=X, pady=20) lbl = Label(toolbar5, text="Results", width=6, font=("Calibri", 10)) lbl.pack(padx=2, pady=2) link = Label(toolbar5, text="(more)", cursor="hand2") link.pack() link.bind("<Button-1>", callback) lbl_res = Label(toolbar5, text="", width=40) lbl_res.pack(padx=2, pady=2) toolbar5.pack(side=BOTTOM) note.add(tab1, text="Spring design for Static load", compound=TOP) tab2 = ttk.Frame(note) # tab2 starts 00000000000000000000000000000000000000000000000000000000000 headFrame_d = Frame(tab2) toolbar1_d = Frame(tab2) toolbar1_1_d = Frame(tab2) toolbar2_d = Frame(tab2) toolbar3_d = Frame(tab2) toolbar4_d = Frame(tab2) calcFrame_d = Frame(tab2) toolbar5_d = Frame(tab2) toolbar6_d = Frame(tab2) toolbar7_d = Frame(tab2) footFrame_d = Frame(tab2) lbl = Label(headFrame_d, text="Input the given params", font=("Arial B", 14)) lbl.pack(padx=2, pady=2) headFrame_d.pack(side=TOP, fill=X, padx=4, pady=20) lbl_d = Label(toolbar1_d, text="Maximum force", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) txt_d_fmax = Entry(toolbar1_d, width=10) txt_d_fmax.pack(side=LEFT, padx=2, pady=2) txt_d_fmax.focus() lbl_d_ut_fmx = Label(toolbar1_d, text="", font=("Arial B", 10), width=6) lbl_d_ut_fmx.pack(side=LEFT, padx=2, pady=2) lbl_d = Label(toolbar1_d, text="Spring Rate", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) txt_d_spr_rate = Entry(toolbar1_d, width=10) txt_d_spr_rate.pack(side=LEFT, padx=2, pady=2) lbl_d_ut_spring_rate = Label(toolbar1_d, text="", font=("Arial B", 10), width=6) lbl_d_ut_spring_rate.pack(side=LEFT, padx=2, pady=2) toolbar1_d.pack(fill=X, padx=70) lbl_d = Label(toolbar1_1_d, text="Minimum force", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) txt_d_fmin = Entry(toolbar1_1_d, width=10) txt_d_fmin.pack(side=LEFT, padx=2, pady=2) lbl_d_ut_fmin = Label(toolbar1_1_d, text="", font=("Arial B", 10), width=6) lbl_d_ut_fmin.pack(side=LEFT, padx=2, pady=2) lbl_d = Label(toolbar1_1_d, text="Failiure Criteria", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) combo_d_fail = Combobox(toolbar1_1_d, width=10) combo_d_fail['values'] = ('Soderberg', 'Gerber', 'Gough', 'Yield', 'Goodman') combo_d_fail.current(1) #set the selected item combo_d_fail.pack(side=LEFT, padx=2, pady=2) toolbar1_1_d.pack(fill=X, padx=70) lbl_d = Label(toolbar2_d, text="Material", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) combo_d_mat = Combobox(toolbar2_d, width=5) combo_d_mat['values'] = ('A227', 'A228', 'A229', 'A232', 'A401') combo_d_mat.current(1) #set the selected item combo_d_mat.pack(side=LEFT, padx=2, pady=2) lbl_d = Label(toolbar2_d, text="", font=("Arial B", 10), width=9) lbl_d.pack(side=LEFT, padx=2, pady=2) lbl_d = Label(toolbar2_d, text="End condition", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) # txt = Entry(toolbar2,width=10) # txt.pack(side=LEFT, padx=2, pady=2) combo_d_end = Combobox(toolbar2_d, width=10) combo_d_end['values'] = ('Plain', 'Plain-Ground', 'Square-Closed', 'Square-Ground') combo_d_end.current(1) #set the selected item combo_d_end.pack(side=LEFT, padx=2, pady=2) # lbl = Label(toolbar2, text="m/s^2",font=("Arial B", 10), width=6) # lbl.pack(side=LEFT, padx=2, pady=2) toolbar2_d.pack(fill=X, padx=70) # lbl_d = Label(toolbar3_d, text="Solid Length", width=15) # lbl_d.pack(side=LEFT, padx=2, pady=2) # txt_d_solidlength = Entry(toolbar3_d,width=10) # txt_d_solidlength.pack(side=LEFT, padx=2, pady=2) # lbl_d_ut_solidlen = Label(toolbar3_d, text="",font=("Arial B", 10), width=6) # lbl_d_ut_solidlen.pack(side=LEFT, padx=2, pady=2) # lbl_d = Label(toolbar3_d, text="Material", width=15) # lbl_d.pack(side=LEFT, padx=2, pady=2) # combo_d_mat = Combobox(toolbar3_d,width=5) # combo_d_mat['values']= ('A227','A228','A229','A232','A401') # combo_d_mat.current(1) #set the selected item # combo_d_mat.pack(side=LEFT, padx=2, pady=2) # toolbar3_d.pack(fill=X, padx=70) lbl_d = Label(toolbar4_d, text="Output Units", width=15) lbl_d.pack(side=LEFT, padx=2, pady=2) rad1_d = Radiobutton(toolbar4_d, text='US', value=1, variable=var_d, command=rad_d_us) rad1_d.pack(side=LEFT, padx=2, pady=2) rad2_d = Radiobutton(toolbar4_d, text='SI', value=2, variable=var_d, command=rad_d_si) rad2_d.pack(side=LEFT, padx=2, pady=2) toolbar4_d.pack(fill=X, padx=70) b_d = Button(calcFrame_d, text="Calculate", command=calcMain_d) b_d.pack() calcFrame_d.pack(fill=X, pady=20) lbl_d = Label(toolbar5_d, text="Results", width=6, font=("Calibri", 10)) lbl_d.pack(padx=2, pady=2) link = Label(toolbar5_d, text="(more)", cursor="hand2") link.pack() link.bind("<Button-1>", callback) lbl_d_res = Label(toolbar5_d, text="", width=40) lbl_d_res.pack(padx=2, pady=2) toolbar5_d.pack(side=BOTTOM) note.add(tab2, text="Spring design for Dynamic load") note.pack()
root.destroy() else: root.destroy() def about(): label = messagebox.showinfo("About", "Lame text editor lol.") def faq(): label = messagebox.showinfo("FAQ", "Srsly? , Pls get a life.") #menu menu = Menu(root) root.config(menu=menu) fileMenu = Menu(menu) menu.add_cascade(label="File", menu=fileMenu) fileMenu.add_command(label="New", command=newFile) fileMenu.add_command(label="Open", command=openFile) fileMenu.add_command(label="Save", command=saveFile) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=exit) helpMenu = Menu(menu) menu.add_cascade(label="Help", menu=helpMenu) helpMenu.add_command(label="FAQ", command=faq) helpMenu.add_command(label="About", command=about) textArea.pack() root.mainloop()
rowspan=3, padx=1, pady=1, sticky="WESN") ''' /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// ''' mainmenu = Menu(root) root.config(menu=mainmenu) mode_draw_menu = Menu(mainmenu, tearoff=0) mode_draw_menu.add_command(label="Рисование окружностей", command=circle_frame_construct) mode_draw_menu.add_command(label="Рисование эллипсов", command=ellipse_frame_contruct) mode_analyse_menu = Menu(mainmenu, tearoff=0) mode_analyse_menu.add_command(label="Анализ для окружностей", command=circle_analyse_frame_constructor) mode_analyse_menu.add_command(label="Анализ для эллипсов", command=ellipse_analyse_frame_constructor) mainmenu.add_cascade(label="Рисование", menu=mode_draw_menu) mainmenu.add_cascade(label="Анализ методов", menu=mode_analyse_menu) def main(): circle_frame_construct()