def draw_control_buttons(self, parent): buttons_frame = Frame(parent) buttons_frame.grid(column=0, row=2, padx=5, pady=3, sticky=(E, S)) #buttons_frame.columnconfigure(0, weight=1) Button(buttons_frame, text='Default Config', command=self.restore_defaults).grid(column=1, row=0, sticky=(W, E)) Button(buttons_frame, text='Load Saved Config', command=self.load_config_button).grid(column=2, row=0, sticky=(W, E)) Button(buttons_frame, text='Save Config', command=self.save_config).grid(column=3, row=0, sticky=(W, E)) Button(buttons_frame, text='Minimize', command=self.minimize).grid(column=2, row=5, sticky=(W, E)) Button(buttons_frame, text='Quit', command=self.quit).grid(column=3, row=5, sticky=(W, E)) for child in buttons_frame.winfo_children(): child.grid_configure(padx=2, pady=1) return buttons_frame
class Widget_: def __init__(self, parent_frame, row, column, width=50, height=50): self.widget_frame = Frame(parent_frame, width=width, height=height) self.widget_frame.grid(row=row, column=column) self.width, self.height = width, height return def add_tag(self, tag_library, string): tag_library[string] = self def delete_widget(self): for child in self.widget_frame.winfo_children(): child.destroy() self.widget_frame.destroy() def hide_widget(self): self.widget_frame.grid_forget() def get_info(self): return def set_field(self): return pass
def set_state(frame_widget: tk.Frame, value: int): _state = "normal" if value else "disabled" for child in frame_widget.winfo_children(): try: child.configure(state=_state) except: if type(child) == tk.Frame: set_state(child, value)
class GUI: def __init__(self, root, halloween): self.halloween = halloween self.root = root self.initialize() self.loop() def initialize(self): self.days = StringVar() self.initialize_window() self.initialize_mainframe() def initialize_mainframe(self): self.mainframe = Frame(root, bg="#FA8E0F") self.mainframe.grid(column=0, row=0, sticky="NEWS") self.mainframe.columnconfigure(0, weight=1) self.mainframe.rowconfigure(0, weight=1) self.headingFont = font.Font( family="TkHeadingFont", size=32, weight="bold", ) self.label = Label(self.mainframe, textvariable=self.days, anchor="center", font=self.headingFont, foreground="#9601D4", bg="#05CD1D") self.label.grid(column=0, row=0, sticky="NEWS") for child in self.mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) def initialize_window(self): self.set_icon() self.root.resizable(0, 0) self.root.title("Silver Shamrock") self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) def set_icon(self): if getattr(sys, 'frozen', False): icon = path.join(sys._MEIPASS, 'pumpkin.ico') else: icon = path.join( path.dirname(path.abspath(__file__)), 'pumpkin.ico', ) self.root.iconbitmap(icon) def loop(self): until = self.halloween.until days = until.days minutes, seconds = divmod(until.seconds, 60) hours, minutes = divmod(minutes, 60) fmt = "{} Days\n{} Hours\n{} Minutes\n{} Seconds\n\n'Til Halloween!" self.days.set(fmt.format(days, hours, minutes, seconds)) self.root.after(1000, self.loop)
def addApp(): for widget in Frame.winfo_children(): widget.destroy() filename= filedialog.askopenfilename(initialdir="/", title="Select File", filetypes=(("executables", "*.exe"), ("allFiles", "*.*"))) apps.append(filename) print(filename) for app in apps: label = tk.Label(Frame, text=app, bg="gray") label.pack()
def clear_frame(frame: tk.Frame) -> None: """ Deletes all children in given frame Parameters ---------- frame : tk.Frame frame object. Returns ------- None. """ for child in frame.winfo_children(): child.destroy()
def disable_frame(frame: tk.Frame) -> None: """ Set all children's status as disable in given frame Parameters ---------- frame : tk.Frame frame object. Returns ------- None. """ for child in frame.winfo_children(): child.configure(state='disable')
def _connect_home_and_q_and_a_frames(home_frame: tkinter.Frame, q_and_a_frame: tkinter.Frame) -> None: q_type_checkbuttons: typing.List[tkinter.ttk.Checkbuttons] = [] q_type_indexed_q_and_a_generators: typing.Dict[ str, MM_QAndAGenerators. Q_AND_A_GENERATOR_SIGNATURE] = MM_QAndAGenerators.get_q_type_indexed_generators( ) cur_home_frame_checkbutton_row: int = 0 cur_home_frame_checkbutton_col: int = 0 for (q_index, q_type) in enumerate(q_type_indexed_q_and_a_generators): cur_home_frame_checkbutton_row += q_index // 2 cur_home_frame_checkbutton_col += q_index % 2 home_frame.grid_rowconfigure(cur_home_frame_checkbutton_row, weight=1) home_frame.grid_columnconfigure(cur_home_frame_checkbutton_col, weight=1) q_type_checkbutton: tkinter.ttk.Checkbutton = tkinter.ttk.Checkbutton( master=home_frame, text=q_type, ) q_type_checkbutton.state(["!alternate"]) q_type_checkbutton.grid(row=cur_home_frame_checkbutton_row, column=cur_home_frame_checkbutton_col, sticky="nsew") q_type_checkbuttons.append(q_type_checkbutton) home_frame_start_btn: tkinter.Button = tkinter.Button( master=home_frame, text="Start", command=lambda: _activate_frame(q_and_a_frame)) home_frame_start_btn.grid(row=cur_home_frame_checkbutton_row + 1, column=0, columnspan=2) (q_and_a_frame_q_textbox, q_and_a_frame_a_textbox) = q_and_a_frame.winfo_children() show_q_or_a: typing.Callable[ [tkinter.Event], None] = lambda event: _show_q_or_a( q_and_a_frame_a_textbox, q_and_a_frame_q_textbox, q_type_checkbuttons, q_type_indexed_q_and_a_generators) q_and_a_frame.bind("<space>", show_q_or_a) q_and_a_frame.bind("<Escape>", lambda event: _activate_frame(home_frame))
def __reset_config(self, master: tk.Frame): for w in master.winfo_children(): w.destroy() # clean-up before reset config_opts = { "MODE": [ tk.Label(master, text="mode:"), tk.Label(master, text=f"({self.__modes[self.__mode_select]})"), tk.Button(master, text="change") ], "DIFF": [ tk.Label(master, text="difficulty:"), tk.Label(master, text=f"({self.__diffs[self.__diff_select]})"), tk.Button(master, text="change") ] } # iterable enum(config_opts) where the final result is len(config_opts) n_config_opts = 0 for (config, w_lst) in config_opts.items(): # dynamic gen of settings (hdr, cur, chg) = range(len(w_lst)) # enum of widgets # ( formatting ) w_lst[hdr].config(**TBL_HDR) w_lst[cur].config(**TBL_DEFAULT_CVAL) w_lst[chg].config(**CMD_UPDATE, command=partial(self.__change_config, master, n_config_opts, len(w_lst))) # ( painting onto options layout ) w_lst[hdr].grid( # header padx=(0, 16), pady=(2, 6), sticky="nw", row=n_config_opts, column=hdr) w_lst[cur].grid( # current selection padx=(0, 16), pady=(2, 6), sticky="nw", row=n_config_opts, column=cur) w_lst[chg].grid(padx=(0, 64), pady=(2, 6), row=n_config_opts, column=chg, sticky="ne") # ( next setting ) n_config_opts += 1
def main(path=None, flags=None): """Build the GUI and run it.""" from tkinter import Tk root = Tk() root.title(f"Run {__PROGNAME__} .gpx processing") root.geometry("524x524+100+100") master = Frame(root) master.grid(column=0, row=0, sticky=(N, E, S, W)) app = App(master, path=path, flags=flags) root.config(menu=app.menubar) for child in master.winfo_children(): child.grid_configure(padx=5, pady=5) app.mainloop()
def render(self): mainframe = Frame(self.__root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) self.__root.columnconfigure(0, weight=1) self.__root.rowconfigure(0, weight=1) self.answer = StringVar() Label(mainframe, text="Login: "******"Hasło:").grid(column=1, row=2, sticky=E) Entry(mainframe, show="*", width=50, textvariable=self.password).grid(column=2, row=2, sticky=(W, E)) Label(mainframe, text="Liczba maili:").grid(column=1, row=3, sticky=E) Entry(mainframe, textvariable=self.size).grid(column=2, row=3, sticky=(W, E)) Label(mainframe, text="Offset:").grid(column=1, row=4, sticky=E) Entry(mainframe, textvariable=self.offset).grid(column=2, row=4, sticky=(W, E)) Label(mainframe, text="Host:").grid(column=1, row=5, sticky=E) Entry(mainframe, textvariable=self.host).grid(column=2, row=5, sticky=(W, E)) Label(mainframe, text="Port:").grid(column=1, row=6, sticky=E) Entry(mainframe, textvariable=self.port).grid(column=2, row=6, sticky=(W, E)) Button(mainframe, text=" Pobierz! ", command= lambda : self.__controller.load())\ .grid(column=3, row=7, sticky=W) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
class CurrentPileFrame: def __init__(self, parent): self.frame = Frame(parent.window, relief=GROOVE, bd=2, width=640, height=140) self.parent = parent labelCurrentPile = Label(self.frame, text="Current Pile") labelCurrentPile.place(relx=0.9, rely=0.01) self.labels = [] def selectNewPile(self, cards): labelCurrentPile = Label(self.frame, text="Current Pile") labelCurrentPile.place(relx=0.9, rely=0.01) for card in cards: label = Label(self.frame, image=card.image) label.bind("<Button-1>", self.playCard) label.place(x=4 + (40 * (cards.index(card))), y=4) self.labels.append(label) if self.parent.playArea.currentPile > 0: self.parent.pilesFrame.labels[self.parent.playArea.currentPile - 1].configure(text=str(len(cards))) def clear(self): for widget in self.frame.winfo_children(): widget.destroy() self.labels = [] def playCard(self, e): index = self.labels.index(e.widget) if self.parent.playArea.playCardFromCurrentPile(index): self.parent.currentPileFrame.clear() cards = self.parent.playArea.piles[ self.parent.playArea.currentPile] self.selectNewPile(cards) self.parent.playedFrameAsc.updateAllImages() self.parent.playedFrameDesc.updateAllImages() self.parent.pilesFrame.labels[self.parent.playArea.currentPile - 1].configure(text=str(len(cards)))
def main(): """Main function.""" from tkinter import Tk root = Tk() root.title("Run quint .gpx processing") root.geometry("450x300+200+200") # root.minsize(400, 200) # master = Frame(root, padding=(3, 3, 12, 12)) master = Frame(root) master.grid(column=0, row=0, sticky=(N, E, S, W)) app = App(master) root.config(menu=app.menubar) for child in master.winfo_children(): child.grid_configure(padx=5, pady=5) app.mainloop()
def __change_config(self, master: tk.Frame, select: int, span: int): # disallow multiple change states if self.__delta_state: self.__reset_config(master) self.__delta_state = True # entering change-config mode # clear selected configuration-row delta_prop = master.winfo_children()[select * span + 1:span * (select + 1)] for w in delta_prop: w.destroy() # options span right-hand side of config header frm_delta = tk.Frame(master, **TRANSPARENT) frm_delta.grid(row=select, column=1, sticky="ew", columnspan=2) delta_opts = { 0: { "USER": tk.Button(frm_delta, text="user"), "COMP": tk.Button(frm_delta, text="computer") }, 1: { "EASY": tk.Button(frm_delta, text="easy"), "HARD": tk.Button(frm_delta, text="hard"), "MAGI": tk.Button(frm_delta, text="magic") } }.get(select) n_delta_opts = 0 for (name, o) in delta_opts.items(): o.config(width=(9 if select else 12), **CMD_UPDATE) o.config(command=partial( self.diff_invoke if select else self.mode_invoke, master, n_delta_opts)) o.grid(padx=(0, 6), pady=(2, 6), row=0, column=n_delta_opts, sticky="w") n_delta_opts += 1
class myApp: def __init__(self): self.root = Tk() style = ttk.Style() style.configure("Treeview.Heading", font=(None, 11), background="green") self.config = ST.Setting(self.root) self.SelDriver = SeleniumProcessor.SeleniumDriver(self.config) self.POMTreeView = TreeProcessor.POMTree(self.config) self.XML = XMLProcessor.XML() self.treeFrame = None self.tree = None self.treeValues = None self.ScreenCoverWindow = None self.root.title("POM Manager") self.root.geometry('700x600') #MENU SECTION : to create Menu # File Menu menu = Menu(self.root) self.root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Create New POM..", command=self.NewFile) filemenu.add_command(label="Open POM...", command=self.OpenFile) filemenu.add_command(label="Save POM...", command=self.SaveFile) filemenu.add_command(label="Save as POM...", command=self.SaveFileAs) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.root.destroy) toolmenu = Menu(menu) menu.add_cascade(label="Tool", menu=toolmenu) toolmenu.add_command(label="Settings", command=self.Settings) helpmenu = Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.About) self.root.grid_columnconfigure(0, weight=1) self.root.grid_rowconfigure(1, weight=1) top = ttk.Frame(self.root, height=200) top.grid_columnconfigure(1, weight=1) top.grid(column=0, row=0, pady=10, sticky='nsew') bottom = ttk.Frame(self.root) bottom.grid(column=0, row=1, sticky='nsew') bottom.grid_columnconfigure(0, weight=1, uniform="group1") bottom.grid_columnconfigure(1, weight=1, uniform="group1") bottom.grid_rowconfigure(0, weight=1) footer = ttk.Frame(bottom, height=120) Label(top, text='Enter Base URL :').grid(column=0, row=0) self.txtURL = Entry(top) self.txtURL.grid(column=1, row=0, sticky='we') browserCombo = ttk.Combobox(top, values=['Chrome', 'IE', 'Edge', 'FireFox'], state='readonly') browserCombo.set('Chrome') browserCombo.grid(column=2, row=0, padx=5) self.Launchbtn = ttk.Button( top, text="Launch", command=lambda: self.SelDriver.LaunchBrowser( browserCombo.get(), self.txtURL.get())) self.Launchbtn.grid(column=1, row=1, pady=5) self.root.bind("<Control-s>", lambda event: self.XML.saveXML(self.POMTreeView)) self.AddNewObjectButton = ttk.Button( footer, text='Add New Object ', command=lambda: self.enable_mouseposition()) self.AddNewObjectButton.grid(column=0, row=1, padx=5, pady=20) self.ManuallyAddobject = ttk.Button( footer, text='Add Object Manually', command=lambda: self.addobjectPropertiesManually()) self.ManuallyAddobject.grid(column=2, row=1, padx=5, pady=20) self.savebutton = ttk.Button( footer, text='Save', command=lambda: self.XML.saveXML(self.tree, self.POMTreeView)) self.savebutton.grid(column=3, row=1, padx=5, pady=20) self.AddToPageButton = ttk.Button( footer, text='Add With Delay', command=lambda: self.getDelayCoordinates()) self.AddToPageButton.grid(column=1, row=1, padx=5, pady=20) self.CancelButton = ttk.Button(footer, text='Cancel', command=self.root.destroy) self.CancelButton.grid(column=4, row=1, padx=5, pady=20) self.treeFrame = Frame(bottom, borderwidth=1, relief="solid") self.treeValues = Frame(bottom, borderwidth=1, relief="solid") self.treeFrame.grid_rowconfigure(0, weight=1) self.treeFrame.grid_columnconfigure(0, weight=1) self.treeFrame.grid(row=0, column=0, sticky='nsew') self.treeValues.grid(row=0, column=1, sticky='nsew') bottom.grid_rowconfigure(0, weight=1) footer.grid(column=0, row=1, columnspan=2) mainloop() try: self.SelDriver.quit() except AttributeError: None def NewFile(self): files = [('ORFile', '*.xml.')] file = asksaveasfile(title="Select folder", filetypes=files, defaultextension=files) self.XML.filePath = file.name self.XML.fileName = ((file.name).split('/')[-1]).split('.')[0] self.createPOMTree('newfile') def OpenFile(self): filePath = filedialog.askopenfilename() if len(filePath) > 4: self.XML = XMLProcessor.XML(filePath) if self.tree != None: self.tree.destroy() self.createPOMTree() self.AddToPageButton['state'] = 'normal' def About(self): print('This is a simple example of a menu!') def SaveFile(self): self.XML.saveXML(self.tree, self.POMTreeView) def SaveFileAs(self): self.XML.saveXML(self.tree, self.POMTreeView, 'newfile') #======================================================================= # self.tree.heading('#0', text=self.XML.fileName) #======================================================================= def Settings(self): self.config.displaySettingPanel() def cancelAddObject(self, topWindow): topWindow.destroy() def getDelayCoordinates(self): try: self.root.iconify() top = Toplevel() top.geometry("+%d+%d" % (0, 0)) top.title("Counter") top.attributes('-alpha', 0.5) v = Tkinter.IntVar() ttk.Label(top, text="**hover mouse to the object you want to add", font=('Arial', 8)).pack() text = ttk.Label(top, textvariable=v) text.config(font=("Courier", 50)) text.pack() for i in range(5, -1, -1): v.set(i) text.update() time.sleep(1) top.destroy() self.SelDriver.set_webElement(PYAUTO.position()) self.createAttributePanel('delayadd') except AttributeError: messagebox.showinfo( 'Driver Not Initiated', 'Driver is not initiated.\nPlease make sure browser is Launched using tool.' ) def enable_mouseposition(self, actionType=None): try: driver = self.SelDriver.driver driver.switch_to.window( driver.window_handles[len(driver.window_handles) - 1]) self.root.after(100, self.get_WebObject(actionType)) except AttributeError: Tkinter.messagebox.showinfo( 'Driver Not Initiated', 'Driver is not initiated. \nPlease make sure browser is launched using tool.' ) def get_WebObject(self, actionType): self.ScreenCoverWindow = Toplevel() self.root.iconify() self.ScreenCoverWindow.attributes('-topmost', True) self.ScreenCoverWindow.title("Object Properties") self.ScreenCoverWindow.attributes('-alpha', 0.2) self.ScreenCoverWindow.attributes("-fullscreen", True) self.ScreenCoverWindow.focus_force() self.ScreenCoverWindow.bind( "<Button-1>", lambda event: self.createAttributePanel(actionType, event)) def createAttributePanel(self, actionType=None, event=None): if actionType != 'delayadd': self.SelDriver.set_webElement((event.x, event.y), self.ScreenCoverWindow) attributePanelWindow = Toplevel() attributePanelWindow.geometry("600x500") attributePanelWindow.attributes('-topmost', True) attributePanelWindow.title("Object Properties") attributePanelWindow.grid_columnconfigure(0, weight=1) attributePanelWindow.grid_rowconfigure(0, weight=1) top = ttk.Frame(attributePanelWindow) top.grid(column=0, row=0, sticky='nsew') top.grid_columnconfigure(0, weight=1, uniform="group1") top.grid_columnconfigure(1, weight=1, uniform="group1") top.grid_rowconfigure(0, weight=1) self.attributeTreeFrame = Frame(top, borderwidth=1, relief="solid") self.attributetreeValues = Frame(top, borderwidth=1, relief='solid') self.attributeTreeFrame.grid_rowconfigure(0, weight=1) self.attributeTreeFrame.grid_columnconfigure(0, weight=1) self.attributeTreeFrame.grid(row=0, column=0, sticky='nsew') self.attributetreeValues.grid(row=0, column=1, sticky="nsew") footer = ttk.Frame(top, height=120) footer.grid(column=0, row=1, columnspan=2) ttk.Button(footer, text='Cancel', command=attributePanelWindow.destroy).grid(column=2, row=1, padx=5, pady=10) ttk.Button(footer, text='Add Object', command=lambda: self.updatePOMTree( attributePanelWindow, self.ObjectPropertyTree.getObjectDict())).grid(column=1, row=1, padx=5, pady=10) self.createAttributeTree(self.SelDriver.attributeList, actionType) def createAttributeTree(self, attrsList, processType=None): self.attributeTree = ttk.Treeview(self.attributeTreeFrame) self.yscrollbar = Util.AutoScrollbar(self.attributeTreeFrame, orient='vertical', command=self.attributeTree.yview) self.attributeTree.configure(yscrollcommand=self.yscrollbar.set) self.attributeTree.grid(row=0, column=0, sticky='nsew') self.yscrollbar.grid(row=0, column=1, sticky='ns') self.ObjectPropertyTree = TreeProcessor.ObjectPropertyTree( self.attributeTree, attrsList, processtype=processType) self.attributeTree.bind( "<<TreeviewSelect>>", lambda event: self.displayProperties( self.attributetreeValues, self.ObjectPropertyTree.getObjectDict())) def displayProperties(self, attributes, newObjectTreeDict, actiontype=None): propertyNum = 0 for widget in attributes.winfo_children(): widget.destroy() currentItem = self.attributeTree.focus() currObject = newObjectTreeDict[currentItem] attributes.grid_columnconfigure(1, weight=1) ttk.Label(attributes, text='Display Name', justify='left').grid(column=0, row=0, padx=5, pady=1, sticky='w') DefaultVal = StringVar(attributes, value=currObject.DisplayName) Entry(attributes, textvariable=DefaultVal).grid(column=1, row=0, padx=5, pady=1, sticky='we', columnspan=1) for oProperty in currObject.propertyList: isPropSelected = oProperty.Selected isUsed = Tkinter.IntVar() propertyCheckButton = ttk.Checkbutton(attributes, text=oProperty.propertyName, variable=isUsed) propertyCheckButton.is_selected = isUsed propertyCheckButton.grid(column=0, row=propertyNum + 1, padx=5, pady=1, sticky='w') DefaultVal = StringVar(attributes, value=oProperty.Value) PropertyVal = Entry(attributes, textvariable=DefaultVal) PropertyVal.grid(column=1, row=propertyNum + 1, padx=5, pady=1, sticky='we', columnspan=2) if isPropSelected == '1' or isPropSelected == 1: propertyCheckButton.var = isUsed propertyCheckButton.var.set(1) else: propertyCheckButton.var = isUsed propertyCheckButton.var.set(0) propertyNum = propertyNum + 1 UpdateButton = ttk.Button(attributes, text='Update') UpdateButton.grid(column=1, row=propertyNum + 1, padx=10, pady=20, sticky='w') if actiontype == 'manual': AddChildButton = ttk.Button(attributes, text='Add child Object ') AddChildButton['command'] = lambda: self.AddChildToAttributeTree() AddChildButton.grid(column=0, row=propertyNum + 1, padx=10, pady=20, sticky='w') UpdateButton['command'] = lambda: self.UpdateProperties( self.scrollable_frame, currentItem) else: UpdateButton['command'] = lambda: self.UpdateProperties( self.attributetreeValues, currentItem) def UpdateProperties(self, treeVal, key): self.ObjectPropertyTree.updateObjectDict(treeVal, key) def updatePOMTree(self, propertyWindow, objDict, actionType=None): currItem = self.attributeTree.focus() objectToAdd = objDict[currItem] currObject = objectToAdd addToObject = '' objList = [currObject.ObjectID] if self.tree == None: self.createPOMTree() propertyWindow.attributes('-topmost', False) if self.tree.exists(currObject.ObjectID): messagebox.showinfo( 'Object Present with ID: =' + currObject.ObjectID, 'Object Present with ID: ' + currObject.ObjectID + '. \nPlease Change the Name or Update object Directly from Attribute Window' ) else: self.POMTreeView.treeDict[currObject.ObjectID] = currObject while currObject.ParentID != None and len(currObject.ParentID) > 0: if self.tree.exists(currObject.ParentID): addToObject = currObject.ParentID self.POMTreeView.treeDict[addToObject].childList.append( currObject) break else: currObject = objDict[currObject.ParentID] self.POMTreeView.treeDict[currObject.ObjectID] = currObject objList.insert(0, currObject.ObjectID) for childtree in objList: childObj = objDict[childtree] self.tree.insert(addToObject, 'end', iid=childObj.ObjectID, text=childObj.DisplayName) addToObject = childObj.ObjectID propertyWindow.destroy() Util.focusTree(self.tree, objectToAdd.ObjectID) print('Object to Focus :' + currObject.ObjectID) def AddChildToAttributeTree(self): for widget in self.scrollable_frame.winfo_children(): widget.destroy() self.addObjectIndentificationFields(self.attributeTree, self.scrollable_frame, 'child') def addobjectPropertiesManually(self): self.attributePanelWindow = Toplevel() self.attributePanelWindow.geometry("600x500") self.attributePanelWindow.attributes('-topmost', True) self.attributePanelWindow.title("Object Properties") self.attributePanelWindow.grid_columnconfigure(0, weight=1) self.attributePanelWindow.grid_rowconfigure(0, weight=1) top = ttk.Frame(self.attributePanelWindow) top.grid(column=0, row=0, sticky='nsew') top.grid_columnconfigure(0, weight=1, uniform="group1") top.grid_columnconfigure(1, weight=1, uniform="group1") top.grid_rowconfigure(0, weight=1) self.attributeTreeFrame = Frame(top, borderwidth=1, relief="solid") self.attributetreeValues = Frame(top, borderwidth=1, relief="solid") self.attributeTreeFrame.grid_rowconfigure(0, weight=1) self.attributeTreeFrame.grid_columnconfigure(0, weight=1) self.attributeTreeFrame.grid(row=0, column=0, sticky='nsew') self.attributetreeValues.grid_rowconfigure(0, weight=1) self.attributetreeValues.grid_columnconfigure(0, weight=1) self.attributetreeValues.grid(row=0, column=1, sticky='nsew') self.scrollable_frame = Util.ScrollableFrame(self.attributetreeValues, 'both') self.attributeTree = ttk.Treeview(self.attributeTreeFrame) self.attributeTree.grid(row=0, column=0, sticky="nsew") self.attributeTree.bind( "<<TreeviewSelect>>", lambda event: self.displayProperties( self.scrollable_frame, self.ObjectPropertyTree.getObjectDict(), 'manual')) footer = ttk.Frame(top, height=120) footer.grid(column=0, row=1, columnspan=2) ttk.Button(footer, text='Cancel', command=self.attributePanelWindow.destroy).grid(column=0, row=1, padx=5, pady=10) ttk.Button(footer, text='Add Object', command=lambda: self.updatePOMTree( self.attributePanelWindow, self.ObjectPropertyTree.getObjectDict())).grid(column=1, row=1, padx=5, pady=10) self.addObjectIndentificationFields(self.attributeTree, self.scrollable_frame) def addObjectIndentificationFields(self, objTree, Scrollableframe, objtype=None): objectTypeList = ['POM_Page'] if len( objTree.get_children()) == 0 else ['POM_frame', 'POM_Object'] ttk.Label(Scrollableframe, text='Object Type', justify='left').grid(column=0, row=0, padx=5, sticky='w') ObjectTypeCombo = ttk.Combobox(Scrollableframe, values=objectTypeList, state='readonly') ObjectTypeCombo.grid(column=1, row=0, sticky='we') ttk.Label(Scrollableframe, text='Display Name', justify="left").grid(column=0, row=1, padx=5, sticky='w') comboExample = ttk.Combobox(Scrollableframe, values=[]) comboExample.grid(column=1, row=1, sticky='we') ObjectTypeCombo.bind( "<<ComboboxSelected>>", lambda event: self.getObjectList( Scrollableframe, ObjectTypeCombo, comboExample)) self.addPropertywidget(Scrollableframe, 2, objtype) def getObjectList(self, Scrollableframe, ObjectTypeCombo, comboExample): listObjectName = [] if ObjectTypeCombo.get() == 'POM_Page': if self.tree != None: for child in self.tree.get_children(): listObjectName.append(child) comboExample['values'] = listObjectName def addPropertywidget(self, propertyWindow, addPropRow, objtype=None): ttk.Label(propertyWindow, text=' ', justify='left').grid(column=0, row=addPropRow, padx=5, sticky='w') ttk.Label(propertyWindow, text='Property Name:', justify='left').grid(column=0, row=addPropRow + 1, padx=5, sticky='w') PropertyType = Entry(propertyWindow) PropertyType.grid(column=1, row=addPropRow + 1, sticky='we') ttk.Label(propertyWindow, text='Property Value:', justify='left').grid(column=0, row=addPropRow + 2, padx=5, sticky='w') PropertyValue = Entry(propertyWindow) PropertyValue.grid(column=1, row=addPropRow + 2, sticky='we') AddPropButton = ttk.Button(propertyWindow, text='Add Property.. ') AddPropButton.grid(row=addPropRow + 3, column=0, padx=5, pady=5, sticky='e') AddPropButton['command'] = lambda: self.addAttribute( propertyWindow, addPropRow, objtype) buttonFrame = Frame(propertyWindow) buttonFrame.grid(column=0, row=addPropRow + 4, columnspan=2) if objtype == 'child': ttk.Button(buttonFrame, text='Add to Tree', command=lambda: self.AddManualobjectToTree( propertyWindow, objtype)).grid(column=0, row=0, padx=5, pady=20) else: ttk.Button(buttonFrame, text='Add to Tree', command=lambda: self.AddManualobjectToTree( propertyWindow)).grid(column=0, row=0, padx=5, pady=20) cancelbutton = ttk.Button( buttonFrame, text='Cancel ', command=lambda: self.refreshAddManualobjectPanel()) cancelbutton.grid(column=1, row=0, padx=5, pady=20) def refreshAddManualobjectPanel(self): for widget in self.scrollable_frame.winfo_children(): widget.destroy() if len(self.attributeTree.get_children()) > 0: currItem = self.attributeTree.focus() Util.focusTree(self.attributeTree, currItem) else: self.addObjectIndentificationFields(self.attributeTree, self.scrollable_frame) def addAttribute(self, propertyWindow, addProp, objtype=None): PropertyName = (propertyWindow.grid_slaves(addProp + 1, 1)[0]).get() PropertyVal = (propertyWindow.grid_slaves(addProp + 2, 1)[0]).get() v = Tkinter.IntVar() for i in range(addProp, addProp + 5): for w in propertyWindow.grid_slaves(row=i): w.grid_forget() c = Checkbutton(propertyWindow, text=PropertyName, variable=v) c.grid(column=0, row=addProp, padx=5, sticky='w') c.is_selected = v DefaultVal = StringVar(self.root, value=PropertyVal) Entry(propertyWindow, textvariable=DefaultVal).grid(column=1, row=addProp, sticky='we') self.addPropertywidget(propertyWindow, addProp + 1, objtype) def AddManualobjectToTree(self, treeManual, objtype=None): if (treeManual.grid_slaves( 0, 1)[0]).get() == '' or (treeManual.grid_slaves( 0, 1)[0]).get() == None or (treeManual.grid_slaves( 1, 1)[0]).get() == '' or (treeManual.grid_slaves( 1, 1)[0]).get() == None: messagebox.showinfo( 'Object Not Created', 'Please provide Object Name and at least one property to add object.' ) else: if objtype == 'child': currentItem = self.attributeTree.focus() currParentObj = self.ObjectPropertyTree.objectDict[currentItem] currObj = self.ObjectPropertyTree.createTreeObject( currParentObj)[1] else: self.ObjectPropertyTree = TreeProcessor.ObjectPropertyTree( self.attributeTree, treevals=treeManual) currObj = self.ObjectPropertyTree.createTreeObject()[1] Util.focusTree(self.attributeTree, currObj.ObjectID) def createPOMTree(self, processType=None): if self.tree != None: self.tree.destroy() self.tree = Util.scrollableTree(self.treeFrame, 'both') self.tree.heading('#0', anchor='w') self.tree.grid(row=0, column=0, sticky="nsew") if self.POMTreeView == None: print('IT IS NULL') self.POMTreeView.setTree(self.tree) if self.XML.filePath != None: self.POMTreeView.createTree(self.XML, self.tree, processType) self.tree.bind("<<TreeviewSelect>>", lambda event: self.displayObjectProperties(event)) def displayObjectProperties(self, currentItem=None): propertyNum = 1 for widget in self.treeValues.winfo_children(): widget.destroy() self.currentItem = self.tree.focus() self.POMTreeView.ORObject = self.currentItem currObject = self.POMTreeView.ORObject ttk.Label(self.treeValues, text='Display Name', justify='left').grid(column=0, row=0, padx=5, sticky='w') DefaultVal = StringVar(self.treeValues, value=currObject.DisplayName) Entry(self.treeValues, textvariable=DefaultVal, state='readonly').grid(column=1, row=0, sticky='we', columnspan=2) ttk.Label(self.treeValues, text='Object ID', justify='left').grid(column=0, row=propertyNum, padx=5, sticky='w') DefaultVal = StringVar(self.treeValues, value=currObject.ObjectID) Entry(self.treeValues, textvariable=DefaultVal, state='readonly').grid(column=1, row=propertyNum, sticky='we', columnspan=2) self.treeValues.grid_columnconfigure(1, weight=1) for oProperty in currObject.propertyList: isPropSelected = oProperty.Selected isUsed = Tkinter.IntVar() propertyCheckButton = ttk.Checkbutton(self.treeValues, text=oProperty.propertyName, variable=isUsed, state='disabled') propertyCheckButton.is_selected = isUsed propertyCheckButton.grid(column=0, row=propertyNum + 1, padx=5, sticky='w') DefaultVal = StringVar(self.treeValues, value=oProperty.Value) PropertyVal = Entry(self.treeValues, textvariable=DefaultVal, state='readonly') PropertyVal.grid(column=1, row=propertyNum + 1, sticky='we', columnspan=2) if isPropSelected == '1' or isPropSelected == 1: propertyCheckButton.var = isUsed propertyCheckButton.var.set(1) else: propertyCheckButton.var = isUsed propertyCheckButton.var.set(0) propertyNum = propertyNum + 1 EditButton = ttk.Button(self.treeValues, text=' Edit ') EditButton['command'] = lambda: self.editProperties( EditButton, propertyNum + 1) EditButton.grid(column=1, row=propertyNum + 1, padx=10, pady=20, sticky='w') def editProperties(self, EditButton, propertyNum): EditButton['text'] = 'Update' EditButton.grid(column=2) ttk.Button(self.treeValues, text='Add Custom Property', command=lambda: self.addCutomProperty()).grid( column=1, row=propertyNum, pady=20, sticky='w') for widget in self.treeValues.winfo_children(): widget['state'] = 'normal' self.treeValues.grid_slaves(1, 1)[0]['state'] = 'readonly' self.isPropertySaved = False EditButton['command'] = lambda: self.updateObjectProperty(EditButton) def addCutomProperty(self): addPropRow = 0 customAttributeWindow = Toplevel() customAttributeWindow.geometry("300x100") customAttributeWindow.attributes("-topmost", True) customAttributeWindow.title("Add Property") customAttributeWindow.grid_columnconfigure(1, weight=1) ttk.Label(customAttributeWindow, text='Property Name:', justify='left').grid(column=0, row=addPropRow, padx=5, pady=5, sticky='w') PropertyType = Entry(customAttributeWindow) PropertyType.grid(column=1, row=addPropRow, sticky='we') ttk.Label(customAttributeWindow, text='Property Value:', justify='left').grid(column=0, row=addPropRow + 1, padx=5, pady=5, sticky='w') PropertyValue = Entry(customAttributeWindow) PropertyValue.grid(column=1, row=addPropRow + 1, sticky='we') AddPropButton = ttk.Button(customAttributeWindow, text='Add Property') AddPropButton.grid(row=addPropRow + 2, column=1, padx=5, pady=10, sticky='w') currentItem = self.tree.focus() AddPropButton['command'] = lambda: self.POMTreeView.addProperty( self.tree, currentItem, customAttributeWindow) def updateObjectProperty(self, actionType=None): currObj = self.POMTreeView.updateObjectProperty( self.tree, self.treeValues, self.currentItem) self.currentItem = currObj.ObjectID Util.focusTree(self.tree, currObj.ObjectID) self.displayObjectProperties()
class TicTacToe: win = [['0', '1', '2'], ['3', '4', '5'], ['6', '7', '8'], ['0', '3', '6'], ['1', '4', '7'], ['2', '5', '8'], ['0', '4', '8'], ['2', '4', '6']] def __init__(self): self.root = Tk() self.root.wm_title("2-player Extended TicTacToe") #self.root.state('zoomed') self.draw() self.root.mainloop() def draw(self): screen_width, screen_height = self.root.winfo_screenwidth()*0.7, self.root.winfo_screenheight()*0.7 self.main_frame = Frame(self.root, width=screen_width, height=screen_height) self.main_frame.grid(row=0, column=0) header = Frame(self.main_frame, width=screen_width, relief=RAISED) header.grid(row=0, columnspan=3) Label(header, text='EXTENDED TIC-TAC-TOE', font=("times", 25, "bold")).grid(row=0) self.conq = [] # Check for conquered blocks self.player = "X" self.board_status = dict() # Draw Board self.sub_frame = [] for row in range(1, 4): for col in range(3): self.sub_frame.append(Frame(self.main_frame, width=screen_width / 3, height=screen_height / 3, highlightbackground='black', highlightthickness=2)) self.sub_frame[-1].grid(row=row, column=col) # # Draw Buttons self.buttons = dict() for i in range(9): for j in range(9): self.buttons[str(i) + str(j)] = Button(self.sub_frame[i], width=int(screen_width / 100), height=int(screen_height / 255), cursor='tcross', font=40, command=partial(self.move, i, j), text=" ") self.buttons[str(i) + str(j)].grid(row=int(j / 3), column=int(j % 3)) self.board_status[str(i) + str(j)] = 0 # Status Bar footer = Frame(self.main_frame, width=screen_width) footer.grid(row=4, columnspan=3) self.turn = Label(footer, text='Player ' + self.player+' plays first', font=('times', 20, 'italic')) self.turn.grid(row=0) def shift_focus(self, frame_no): if frame_no in self.conq: for i in range(9): if i in self.conq: for j in range(9): self.buttons[str(i) + str(j)].configure(state=DISABLED, cursor='pirate') self.sub_frame[i].configure(highlightbackground='black') else: for j in range(9): self.buttons[str(i) + str(j)].configure(state=NORMAL, cursor=('circle', 'tcross')[self.player == 'X']) self.sub_frame[i].configure(highlightbackground='red') else: for i in range(9): if i == frame_no and i not in self.conq: for j in range(9): self.buttons[str(i) + str(j)].configure(state=NORMAL, cursor=('circle', 'tcross')[self.player == 'X']) self.sub_frame[i].configure(highlightbackground='red') else: for j in range(9): self.buttons[str(i)+str(j)].configure(state=DISABLED, cursor='pirate') self.sub_frame[i].configure(highlightbackground='black') def check_small(self, i): i = str(i) for wins in self.win: if self.board_status[i + wins[0]] + self.board_status[i + wins[1]] + self.board_status[i + wins[2]] == 3: for j in range(9): self.buttons[i + str(j)].configure(text=self.player, state=DISABLED) self.conq.append(int(i)) break elif self.board_status[i + wins[0]] + self.board_status[i + wins[1]] + self.board_status[i + wins[2]] == -3: for j in range(9): self.buttons[i + str(j)].configure(text=self.player, state=DISABLED) self.conq.append(int(i)) break if len(self.conq) > 2: self.check_win() def check_win(self): for wins in self.win: flag = True for t in wins: if int(t) not in self.conq: flag = False break if flag is True: break if flag is True: # Disable Current Frame for child in self.main_frame.winfo_children(): child.configure(state='disable') # Notify Winner t = Toplevel(self.root) self.over_frame = Frame(t) self.over_frame.grid(row=0) Label(self.over_frame, text=self.player+' Wins').grid(row=0) Button(self.over_frame, text='New game', command=self.draw).grid(row=1) def move(self, i, j): if self.buttons[str(i)+str(j)]['text'].strip() == "": self.buttons[str(i)+str(j)].configure(text=self.player) if self.player == "X": self.board_status[str(i) + str(j)] = 1 self.check_small(i) self.player = "O" else: self.board_status[str(i) + str(j)] = -1 self.check_small(i) self.player = "X" # Shift focus to corresponding cell self.shift_focus(j) self.turn.configure(text='Player ' + self.player + ' turn')
def update_frame(frame: Frame): if frame.winfo_children(): if isinstance(frame.winfo_children()[-1], (Canvas, Frame)): frame.winfo_children()[-1].destroy()
class Tagging(Frame): def __init__(self, parent, options): if options == None: options = {} DefaultOptions = {'colorspace':'RGB', 'K':6, 'km_init':'first', 'verbose':False, 'single_thr':0.6, 'metric':'basic'} for op in DefaultOptions: if not op in options: options[op] = DefaultOptions[op] self.options = options self.K_ant = 0 self.num_im=-1 Frame.__init__(self, parent) self.parent = parent self.parent.title("TAGGING") self.F1 = Frame(parent, width=150,borderwidth=2,relief=GROOVE) self.F2 = Frame(parent, width=150,borderwidth=2,relief=GROOVE) self.F3 = Frame(parent) self.F4 = Frame(parent,borderwidth=2,relief=GROOVE) self.F5 = Frame(parent,borderwidth=2,relief=GROOVE) self.F1.pack(side=LEFT, fill=Y, pady = 4, padx=4) self.F2.pack(side=LEFT, fill=Y, pady = 4) self.F3.pack(side=TOP, expand=True, fill=BOTH, pady = 4, padx = 4) self.F4.pack(side=TOP, fill=BOTH, expand=0, padx = 4) self.F5.pack(side=BOTTOM, fill=BOTH, expand=0, pady = 4, padx = 4) self.F1.pack_propagate(0) self.F2.pack_propagate(0) self.F3.pack_propagate(0) lbl = Label(self.F1, text="Groundtruth") lbl.grid(row=0,sticky=W) Frame(self.F1,borderwidth=1,relief=GROOVE,height=2).grid(row=1,sticky=W) lbl = Label(self.F2, text="Detected") lbl.grid(row=0,sticky=W, columnspan=2) Frame(self.F2,borderwidth=1,relief=GROOVE,height=2).grid(row=1,sticky=W, columnspan=2) self.filename = Button(self.F3,text="filename",command=self.ChooseFile) self.filename.pack(side=TOP,expand=0) # #matplotlib setup # plt.ion() self.figure=plt.figure(figsize=(2,2), frameon=False) self.axes=self.figure.add_subplot(111) self.Canvas=FigureCanvasTkAgg(self.figure, master=self.F3) # self.Canvas.show() self.Canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=1 ) plt.axis('off') b = Button(self.F4,text=" <<<10 ",command=self.PreviousFast) b.pack(side=LEFT, padx=(20,2), pady=3) b = Button(self.F4,text=" <<1 ",command=self.Previous) b.pack(side=LEFT, pady=3) self.im_name = Button(self.F4,text="image",bd=0, command=self.Results) self.im_name.pack(side=LEFT, expand=True) b = Button(self.F4,text=" 1>> ",command=self.Next) b.pack(side=LEFT) b = Button(self.F4,text=" 10>>> ",command=self.NextFast) b.pack(side=LEFT, padx=(2,20)) F51 = Frame(self.F5) F52 = Frame(self.F5) F53 = Frame(self.F5) F51.pack(fill=BOTH, expand=1, side=LEFT) Frame(self.F5,borderwidth=1,relief=GROOVE,width=2).pack(side=LEFT, fill=Y) F52.pack(fill=BOTH, expand=1, side=LEFT) Frame(self.F5,borderwidth=1,relief=GROOVE,width=2).pack(side=LEFT, fill=Y) F53.pack(fill=BOTH, expand=1, side=LEFT) Label(F51, text="Color space").pack() Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F52, text="K-Means").pack() Frame(F52,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F53, text="Labelling").pack() Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.ColorMode = StringVar() self.ColorMode.set(self.options[COLORSSPACE['key']]) for text, mode in COLORSSPACE['options_gui']: b = Radiobutton(F51, text=text, variable=self.ColorMode, value=mode, command=self.Results) b.pack(anchor=W) Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F51, text="Grouping", padx=20).pack() Frame(F51,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.Group = BooleanVar() self.Group.set(True) b = Checkbutton(F51, text='Group same label colors', variable=self.Group, command=self.Results) b.pack(anchor=W) F521 = Frame(F52) F522 = Frame(F52) F521.pack(fill=BOTH) F522.pack(fill=BOTH) # F523 = Frame(F52) # F523.pack(fill=BOTH) self.K = StringVar() self.K.set(self.options['K']) # f = Frame(F52) # f.pack(side=TOP, fill=BOTH, expand=0) Label(F521, text="K : ").pack(side=LEFT) Entry(F521, textvariable=self.K, width=3, justify=CENTER).pack(side=LEFT, padx=4) # Label(F52, text="Init", padx=20).pack(anchor=W) # Frame(F521,borderwidth=1,relief=GROOVE,width=2).pack(side=RIGHT, fill=Y, padx=2) self.Fitting = StringVar() self.Fitting.set(self.options[FITTING['key']]) # f = Frame(F52) # f.pack(side=RIGHT, fill=BOTH, expand=0) for text, mode in FITTING['options_gui']: b = Radiobutton(F521, text=text, variable=self.Fitting, value=mode, command=self.Results) b.pack(anchor=W,padx=4) Frame(F522,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F522, text="Centroid Init", padx=20).pack() Frame(F522,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) # IM = [('First points','first'),('Randomize', 'random'),('Distribtued','distributed'),('Other','Other')] self.KMInit = StringVar() self.KMInit.set(self.options[CENTROIDSINIT['key']]) for text, mode in CENTROIDSINIT['options_gui']: b = Radiobutton(F522, text=text, variable=self.KMInit, value=mode, command=self.Results) b.pack(anchor=W) self.Thr = StringVar() self.Thr.set(self.options['single_thr']) f = Frame(F53) f.pack(side=TOP, fill=BOTH, expand=0) Label(f, text="single\nbasic >\ncolor", justify=LEFT).pack(side=LEFT) Entry(f, textvariable=self.Thr, width=4, justify=CENTER).pack(side=LEFT) # self.Synonymous = BooleanVar() # self.Synonymous.set(self.options['synonyms']) # b = Checkbutton(F53, text='Synonymous', variable=self.Synonymous, command=self.Results) # b.pack(anchor=W) Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) Label(F53, text="Similarity Metric", padx=2).pack() Frame(F53,borderwidth=1,relief=GROOVE,height=2).pack(fill=X) self.Metric = StringVar() self.Metric.set(self.options[SIMILARITY['key']]) for text, mode in SIMILARITY['options_gui']: b = Radiobutton(F53, text=text, variable=self.Metric, value=mode, command=self.Results) b.pack(anchor=W) def ChooseFile(self): filename = filedialog.askopenfilename(initialdir='Images', filetypes=[("Text files","*.txt")]) if filename =='': return self.ImageFolder = os.path.dirname(filename) self.filename['text'] = os.path.basename(filename) self.GT = lb.loadGT(filename) self.num_im = 0 self.Results() def Previous(self): self.num_im -= 1 if self.num_im<-1: self.num_im=0 elif self.num_im<0: self.num_im=0 return self.Results() def PreviousFast(self): self.num_im -= 10 if self.num_im<0: self.num_im=0 self.Results() def Next(self): self.num_im += 1 if self.num_im>=len(self.GT): self.num_im=len(self.GT)-1 return self.Results() def NextFast(self): self.num_im += 10 if self.num_im>=len(self.GT): self.num_im=len(self.GT)-1 self.Results() def Results(self): if self.num_im<0 or self.num_im>=len(self.GT): return #self.parent.config(cursor="wait") self.parent.update() self.im_name['text'] = self.GT[self.num_im][0] im = io.imread(self.ImageFolder+"/"+self.GT[self.num_im][0]) self.options['K'] = int(self.K.get()) self.options['single_thr'] = float(self.Thr.get()) # self.options['synonyms'] = self.Synonymous.get() self.options[COLORSSPACE['key']] = self.ColorMode.get() self.options[CENTROIDSINIT['key']] = self.KMInit.get() self.options[SIMILARITY['key']] = self.Metric.get() self.options[FITTING['key']] = self.Fitting.get() if self.options['fitting'] != 'None': if self.K_ant==0: self.K_ant = self.options['K'] self.options['K'] = 0 self.K.set(0) pass else: if self.K_ant>0: self.K.set(self.K_ant) self.options['K'] = self.K_ant self.K_ant = 0 self.labels, self.which, self.km = lb.processImage(im, self.options) if self.options['K'] == 0: self.K.set(self.km.K) if not self.Group.get(): self.labels = [w for ww in [[w]*len(z) for w,z in zip(self.labels,self.which)] for w in ww] self.which = [[w] for ww in self.which for w in ww] # get percentages for every label percent = np.zeros((len(self.which),1)) for i,w in enumerate(self.which): for k in w: percent[i] += np.sum(self.km.clusters==k) percent = percent*100/self.km.clusters.size # get color for every label from image sh = im.shape; im = np.reshape(im, (-1, im.shape[2])) colors = np.zeros((len(self.which),3)) for i,w in enumerate(self.which): for k in [w[0]]: colors[i] += np.mean(im[self.km.clusters==k,:],0) colors[i] /= len(w) im = np.reshape(im, sh) self.im = im self.CBgt = self.CreateCheckList(self.F1, self.GT[self.num_im][1]) self.CBdetected = self.CreateCheckList(self.F2, self.labels, percent, colors) l = Label(self.F2,text='similarity: '+'%.2f' % (lb.similarityMetric(self.labels, self.GT[self.num_im][1], self.options)*100)+'%') l.grid(columnspan=2,sticky=W+E+N+S) self.F2.grid_rowconfigure(self.F2.grid_size()[1]-1, weight=1) self.CheckLabels() #self.parent.config(cursor="") self.parent.update() self.Segment() # self.ShowImage(im) def Segment(self): all_widgetes = self.F2.winfo_children() cb = [w for w in all_widgetes if w.winfo_class() == 'Checkbutton'] lab_colors = np.zeros((len(cb),3)) for i,c in enumerate(cb): lab_colors[i,0] = int(c.cget('bg')[1:3], 16) lab_colors[i,1] = int(c.cget('bg')[3:5], 16) lab_colors[i,2] = int(c.cget('bg')[5:7], 16) ims = np.empty_like(self.im) ims = np.reshape(ims, (-1, ims.shape[2])) for i,w in enumerate(self.which): for k in w: ims[self.km.clusters==k]=lab_colors[i] ims = np.reshape(ims, self.im.shape) self.ShowImage(np.hstack((ims,self.im))) def ShowImage(self,im): self.axes.imshow(im) plt.axis('off') self.Canvas.draw() def CreateCheckList(self, frame, labels, values=None, colors=None): all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Checkbutton'] for w in all_widgetes: w.destroy() all_widgetes = [w for w in frame.winfo_children() if w.winfo_class() == 'Label'] for w in all_widgetes[1:]: w.destroy() var = [] if values is not None: add_text = ["%5.1f" % (values[i]) +'%' for i in range(len(values))] for i in range(len(labels)): var.append(BooleanVar()) fgc = "black" if colors is not None: mycolor = '#%02x%02x%02x' % (int(colors[i,0]), int(colors[i,1]), int(colors[i,2])) if (colors[i,0]+colors[i,1]+colors[i,2])/3/255<=0.5: fgc = "#FFFFFF" else: mycolor = frame.cget('bg') cb = Checkbutton(frame, text=labels[i], state=DISABLED, variable=var[i], bg=mycolor, disabledforeground=fgc, anchor=W) # cb.pack(anchor=W, fill=X, padx=2) cb.grid(row=i+2,column=0,sticky=W+E) if values is not None: cb = Label(frame, text=add_text[i], bg=mycolor, fg=fgc, anchor=E) cb.grid(row=i+2,column=1,sticky=W+E+N+S) frame.grid_rowconfigure(i+2, weight=0) return var def CheckLabels(self): for i in range(len(self.labels)): if self.labels[i] in self.GT[self.num_im][1]: self.CBdetected[i].set(True) for i in range(len(self.GT[self.num_im][1])): if self.GT[self.num_im][1][i] in self.labels: self.CBgt[i].set(True)
class Component(Extendable, ABC): """ A blank base component which extends lifecycle methods to be overriden as necessary """ def __init__(self, container: Widget, get_data: Optional[Callable[["Component"], Any]] = None, on_change: Callable = lambda: None, update_interval: Optional[int] = None, styles: Optional[dict] = None): super().__init__() self._container = container self._outer_frame = Frame(self._container) self._frame = None # Add child elements to this frame in _render() # Allow the outer frame to expand to fill the container self._outer_frame.rowconfigure(0, weight=1) self._outer_frame.columnconfigure(0, weight=1) # All element styles should be stored here, as their own dicts self.styles = {} styles = {} if not styles else styles self.styles["frame"] = styles.get("frame", {}) # Use this space to keep hold of any elements that might need configuring in _update or _get_data self.children = {} self._update_interval = update_interval # Milliseconds """ This function should receive this component instance as a parameter and return any data from the application state that is needed by this component. If it is set to None rather than a function, this indicates that there is no outside data source. Other aspects of this component (styles, etc.) can be edited during the execution of this function. """ self._get_data = get_data """ When the state of this component changes, this function should be called and passed this component instance and any event data as parameters. The function should perform any additional external work needed. """ self._on_change = on_change @property def exists(self) -> bool: """ Should be used to check that the component has not been destroyed, before its state is altered in any way """ return self._outer_frame.winfo_exists() @property def is_rendered(self) -> bool: """ Used internally to check that a component has rendered its contained widgets, before checking their details """ if self._frame is None: return False self._frame.update() return self._frame.winfo_exists() @property def height(self) -> int: self._outer_frame.update() return self._outer_frame.winfo_height() @property def width(self) -> int: self._outer_frame.update() return self._outer_frame.winfo_width() @property def height_clearance(self) -> Optional[int]: """ Represents the amount of vertical space in the widget (values such as padding and border are removed) """ if not self.is_rendered: return None frame_padding = self.styles["frame"].get("pady", 0) frame_borderwidth = self.styles["frame"].get("borderwidth", 0) total_buffer = (2 * frame_padding) + (2 * frame_borderwidth) return self._frame.winfo_height() - total_buffer @property def width_clearance(self) -> Optional[int]: """ Represents the amount of horizontal space in the widget (values such as padding and border are removed) """ if not self.is_rendered: return None frame_padding = self.styles["frame"].get("padx", 0) frame_borderwidth = self.styles["frame"].get("borderwidth", 0) total_buffer = (2 * frame_padding) + (2 * frame_borderwidth) return self._frame.winfo_width() - total_buffer def render(self) -> Frame: """ This method should be invoked externally, and the returned frame have pack() or grid() called on it """ for child_element in self._outer_frame.winfo_children(): child_element.destroy() self._refresh_frame() self._render() if self._update_interval: self._frame.after(self._update_interval, self._update_loop) return self._outer_frame def _update_loop(self) -> None: """ Used internally to handle updating the component once per update interval (if update interval was provided) """ self._frame.after_cancel(self._update_loop) if not self.exists: return if self._update_interval: self._frame.after(self._update_interval, self._update_loop) self._update() if self._needs_render: self.render() # Overridable Methods @property def _needs_render(self) -> bool: """ Overridable method. Should return a True value only once per time a re-render is required. If the component will never need to poll for a re-render, this method need not be overridden """ return False def _refresh_frame(self) -> None: """ Overridable method. Handles creating a new blank frame to store in self._frame at the top of each render() call. Only needs overriding if this blank frame needs extra base functionality before any child components are rendered to it """ self._frame = Frame(self._outer_frame, **self.styles["frame"]) self._frame.grid(row=0, column=0, sticky="nswe") def _update(self) -> None: """ Overridable method. Handles updating the component state once per update interval (if update interval was provided). If the component will not need to directly update its state outside of a new render, this method need not be overridden """ pass def _render(self) -> None: """ Overridable method. Any child components should be rendered to self._frame in this method """ raise NotImplementedError
class ABSingleLickGui: def __init__(self, root=Tk()): self.root = root self.root.title("Apple/Banana Single Lick") self.root.configure(bg=BACKGROUND_COLOR) self.titleLabel = Label(self.root, text='AppleBanana Single Lick Experiment', font=STATUS_FONT, bg=BACKGROUND_COLOR) self.ard = None self.experiment = None self.isConfigLoaded = False self.isArdConnected = False self.isPumpOn = False self.estTime = StringVar() self.lickCount = IntVar() self.lickCount.set(0) self.isSoundOn = BooleanVar() self.stopUpdating = threading.Event() self.ardUpdater = threading.Thread(target=self.updateVariable) port = MouseArduino.getUnoPort() #Frames self.master = Frame(root, bg=BACKGROUND_COLOR) self.master.grid_rowconfigure(0) self.master.grid_rowconfigure(1) self.master.grid_rowconfigure(2, weight=5) self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) self.master.grid_columnconfigure(2, weight=1) self.ardInitFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.ardControlFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.initFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.argFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.finalControlFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) #ardInitFrame self.ardInitFrameLabel = Label(self.ardInitFrame, text="Connect to Hardware", bg=HEADER_COLOR, font=LARGE_FONT, fg='white', relief='solid', borderwidth=2, width=40) self.comLabel = Label(self.ardInitFrame, bg=BACKGROUND_COLOR, text="Com Port:", font=TEXT_FONT) self.comEntry = Entry(self.ardInitFrame, font=TEXT_FONT) self.baudrateLabel = Label(self.ardInitFrame, bg=BACKGROUND_COLOR, text="Baudrate:", font=TEXT_FONT) self.baudrateEntry = Entry(self.ardInitFrame, font=TEXT_FONT) self.connectButton = Button(self.ardInitFrame, text="Connect", font=STATUS_FONT, command=self.connect) self.ardInitFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.comLabel.grid(row=1, column=0, sticky=tk.E) self.comEntry.grid(row=1, column=1, sticky=tk.W) self.baudrateLabel.grid(row=2, column=0, sticky=tk.E) self.baudrateEntry.grid(row=2, column=1, sticky=tk.W) self.connectButton.grid(row=3, columnspan=2, pady=10) self.comEntry.insert(0, port) self.baudrateEntry.insert(0, 115200) #ardControlFrame self.ardControlFrameLabel = Label(self.ardControlFrame, text='Pre-experiment Control', bg=HEADER_COLOR, font=LARGE_FONT, fg='white', relief='solid', borderwidth=2, width=40) self.sendStringEntry = Entry(self.ardControlFrame, font=TEXT_FONT, width=20) self.sendStringButton = Button(self.ardControlFrame, text='Send String', font=TEXT_FONT, bg=BACKGROUND_COLOR, command=self.sendString) self.rewardButton = Button(self.ardControlFrame, text='Reward(R)', font=STATUS_FONT, width=10, bg=BACKGROUND_COLOR, command=self.deliverReward, height=1) self.pumpButton = Button(self.ardControlFrame, text='Pump Water(P)', font=STATUS_FONT, command=self.togglePump, bg=OFF_COLOR, width=12, height=1) self.lickLabel = Label(self.ardControlFrame, text='LICK', bg=LICK_OFF_COLOR, font=LICK_FONT, width=10, height=1) self.lickCountLabel = Label(self.ardControlFrame, text='Lick Count :', bg=BACKGROUND_COLOR, font=LARGE_FONT) self.lickCountButton = Button(self.ardControlFrame, textvariable=self.lickCount, font=LARGE_FONT, bg=BACKGROUND_COLOR, command=lambda: self.lickCount.set(0)) self.soundCheckButton = Checkbutton(self.ardControlFrame, text='Lick Sound', variable=self.isSoundOn, bg=BACKGROUND_COLOR) self.ardControlFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.sendStringEntry.bind('<Return>', self.sendString) self.sendStringEntry.grid(row=1, column=0, padx=5, sticky=tk.E) self.sendStringEntry.bind('<Escape>', lambda x: self.master.focus()) self.sendStringButton.grid(row=1, column=1, padx=5, sticky=tk.W) self.rewardButton.grid(row=2, column=0, pady=10) self.pumpButton.grid(row=2, column=1, pady=10) self.lickLabel.grid(row=3, columnspan=2, pady=15) self.lickCountLabel.grid(row=4, column=0, sticky=tk.E) self.lickCountButton.grid(row=4, column=1, sticky=tk.W) self.soundCheckButton.grid(row=5, columnspan=2) #initFrame self.initFrameLabel = Label(self.initFrame, text="Session Configuration", font=LARGE_FONT, bg=HEADER_COLOR, fg='white', relief='solid', borderwidth=2, width=40) self.loadButton = Button(self.initFrame, text="Load Config(L)", font=STATUS_FONT, command=self.selectFile) self.sessionNameLabel = Label(self.initFrame, text="Session Name:", font=TEXT_FONT, bg=BACKGROUND_COLOR) self.sessionNameEntry = Entry(self.initFrame, font=TEXT_FONT) self.numOfTrialsLabel = Label(self.initFrame, text="Number of Trials:", font=TEXT_FONT, bg=BACKGROUND_COLOR) self.numOfTrialsEntry = Entry(self.initFrame, font=TEXT_FONT) self.numOfTrialsEntry.bind('<KeyRelease>', self.updateTime) self.numOfTrialsEntry.bind('<Escape>', lambda x: self.master.focus()) self.initFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.sessionNameLabel.grid(row=1, column=0, sticky=tk.E) self.sessionNameEntry.grid(row=1, column=1, sticky=tk.W) self.sessionNameEntry.bind('<Escape>', lambda x: self.master.focus()) self.numOfTrialsLabel.grid(row=2, column=0, sticky=tk.E) self.numOfTrialsEntry.grid(row=2, column=1, sticky=tk.W) self.loadButton.grid(row=3, columnspan=2, pady=10) #finalControlFrame self.finalControlFrameLabel = Label(self.finalControlFrame, text='Experiment Control', bg=HEADER_COLOR, font=LARGE_FONT, fg='white', relief='solid', bd=2, width=40) self.estTimeLabel = Label(self.finalControlFrame, textvariable=self.estTime, font=STATUS_FONT, bg=BACKGROUND_COLOR) self.startButton = Button(self.finalControlFrame, text="START EXPERIMENT", font='Helvetica 20 bold', command=self.startExperiment) self.finalControlFrameLabel.grid(padx=40, pady=10) self.estTimeLabel.grid(pady=10) self.startButton.grid(pady=15) #master self.titleLabel.pack(pady=5) self.master.pack(padx=20, pady=20) self.initFrame.grid(row=0, column=0) self.ardInitFrame.grid(row=1, column=0) self.finalControlFrame.grid(row=2, column=0, sticky='NSWE') self.argFrame.grid(row=0, column=1, rowspan=3, sticky='NSWE') for frame in [ self.master, self.initFrame, self.ardInitFrame, self.finalControlFrame, self.argFrame ]: frame.bind('r', self.deliverReward) frame.bind('p', self.togglePump) frame.bind('l', self.selectFile) frame.bind('R', self.deliverReward) frame.bind('P', self.togglePump) frame.bind('L', self.selectFile) frame.bind("<Button-1>", lambda e: self.master.focus_set()) self.updateTime() def run(self): self.master.mainloop() def selectFile(self, event=None): fileName = filedialog.askopenfilename() self.configFileName = fileName for widget in self.argFrame.winfo_children(): widget.destroy() self.argFrameLabel = Label(self.argFrame, text="Experiment Configuration: " + os.path.basename(fileName), font=LARGE_FONT, bg=HEADER_COLOR, fg='white', relief='solid', bd=2, width=40).grid(columnspan=2, padx=40, pady=10) try: with open(fileName) as f: self.args = json.load(f) except Exception as e: print(e) argToLen = lambda x: len(str(x)) maxArgNameLength = argToLen( max(self.args.keys(), key=lambda x: argToLen(x))) maxArgValueLength = argToLen( max(self.args.values(), key=lambda x: argToLen(x))) correctTrialDuration = self.args["Cue duration"] + \ self.args["Correct response visual duration"] + \ (self.args["Stimulus duration"] if self.args["Give reward without lick"] == 0 else 0) wrongTrialDuration = self.args["Cue duration"] +\ self.args["Stimulus duration"] + \ self.args["Wrong response flash duration"] + \ self.args["Wrong response rest duration"] self.trialDuration = correctTrialDuration * self.args[ "A image probability"] + wrongTrialDuration * ( 1 - self.args["A image probability"]) for i, (argName, value) in enumerate( sorted(self.args.items(), key=lambda item: item[0])): lName = Label(self.argFrame, text=str(argName) + " :", font='Helvetica 12 bold', bg=BACKGROUND_COLOR).grid(row=i + 3, column=0, sticky=tk.E) lValue = Label(self.argFrame, text=str(value), bg=BACKGROUND_COLOR).grid( row=i + 3, column=1, sticky=tk.W, ) self.updateTime() self.isConfigLoaded = True def connect(self): try: comport = self.comEntry.get() baudrate = self.baudrateEntry.get() if comport == "" or baudrate == "": raise Exception("Please fill in all values") baudrate = int(baudrate) self.ard = MouseArduino(comport, baudrate) self.ard.start() self.ardInitFrame.destroy() self.ardUpdater.start() self.ardControlFrame.grid(row=1, column=0) self.isArdConnected = True except Exception as e: messagebox.showerror( "Error", "Could not connect to Arduino. Make sure port is correct or other program isn't grabbing the port :" + str(e)) def deliverReward(self, event=None): self.ard.deliverReward() def sendString(self, event=None): self.ard.write(self.sendStringEntry.get()) self.sendStringEntry.delete(0, 'end') def updateVariable(self): while not self.stopUpdating.is_set(): if self.ard.newMsg.wait(1): while not self.ard.msgQueue.empty(): self.ard.newMsg.clear() msg = self.ard.msgQueue.get() print(msg) args = Utilities.parse(msg) arg = args[1].strip() if arg == 'LK': self.lickCount.set(self.lickCount.get() + 1) self.lickLabel.configure(bg=ON_COLOR) if self.isSoundOn.get(): Sound.cue(0.05) time.sleep(0.2) self.lickLabel.configure(bg=LICK_OFF_COLOR) elif arg == 'startpump': self.pumpButton.configure(bg=ON_COLOR) self.isPumpOn = True elif arg == 'stoppump': self.pumpButton.configure(bg=OFF_COLOR) self.isPumpOn = False def togglePump(self, event=None): if self.isPumpOn: self.ard.stopPump() else: self.ard.startPump() def updateTime(self, event=None): numOfTrials = self.numOfTrialsEntry.get() try: totalDuration = self.trialDuration * int(numOfTrials) tmin = totalDuration // 60 tsec = totalDuration % 60 timeStr = "{:.0f} Min {:.0f} Sec".format(tmin, tsec) except Exception as e: timeStr = "" print(e) self.estTime.set("Estimated duration: {:>10}".format(timeStr)) def startExperiment(self): if not self.isConfigLoaded: messagebox.showerror("Error", "Please load configuration file") elif not self.isArdConnected: messagebox.showerror("Error", "Please connect Arduino") else: try: sessionName = self.sessionNameEntry.get() numOfTrials = self.numOfTrialsEntry.get() if sessionName == "" or numOfTrials == "": raise Exception("Please fill in all values") numOfTrials = int(numOfTrials) self.experiment = ABSingleLick(self.ard) self.experiment.startExperiment(sessionName, numOfTrials, self.configFileName) except Exception as e: messagebox.showerror("Error", e)
class TkMplSetup: def __init__(self, root): self.root = root self.root.geometry('800x500') self.root.protocol('WM_DELETE_WINDOW', self.quit) self.root.title("Sound Visualiser") self.root.columnconfigure(0, weight=1) self.volume = 0 self.duration = 100 self.running = False self.stopped = True self.error_message = '' self.plot_area() self.main_buttons() self.control_buttons() self.pause_time = None self.visualisation = None def plot_area(self): plot_frame = Frame(self.root) plot_frame.grid(row=0, column=0, sticky='nw') self.fig, self.ax = plt.subplots(figsize=(5, 4)) canvas = FigureCanvasTkAgg(self.fig, master=plot_frame) canvas.get_tk_widget().pack() def main_buttons(self): bottom_frame = Frame(self.root) bottom_frame.grid(row=1, column=0, rowspan=2, sticky='new') self.start_pause_button = Button( bottom_frame, text='Start', command=self.control_start_pause) self.start_pause_button.pack(side='left') self.stop_button = Button( bottom_frame, text='Stop', command=self.stop) self.stop_button.pack(side='left') self.quit_button = Button( bottom_frame, text='Quit', command=self.quit) self.quit_button.pack(side='left') def control_start_pause(self): if self.error_message: return if self.stopped: try: self.ax.lines.pop(0) except IndexError: pass if self.selected_type == SoundType.NOTE: try: self.frequency = int(self.frequency_entry.get()) except ValueError: self.frequency = DEFAULT_FREQUENCY self.frequency_entry.insert(0, DEFAULT_FREQUENCY) except TclError: self.frequency = DEFAULT_FREQUENCY if self.selected_type in [SoundType.NOTE, SoundType.DESIGN]: try: self.duration = float(self.duration_entry.get()) except ValueError: self.duration = DEFAULT_DURATION self.duration_entry.insert(0, DEFAULT_DURATION) except TclError: self.duration = DEFAULT_DURATION # TODO: the minus 1 second from self.duration is to align the playing of the # sound and the progress bar, under investigation self.time_progress['maximum'] = 1000 * (self.duration - 1.0) self.time_progress['value'] = 0 self.running = True self.stopped = False self.start_pause_button.config(text='Pause') self.start_visualisation() #pylint: disable=no-member return if self.running: self.visualisation.event_source.stop() self.pause_start_time = time.time() self.start_pause_button.config(text='Run') else: self.pause_time += time.time() - self.pause_start_time self.visualisation.event_source.start() self.start_pause_button.config(text='Pause') self.running = not self.running def stop(self): try: self.visualisation.event_source.stop() except AttributeError: # just pass as stop button was pressed before visualisation had # actually started pass self.stopped = True def quit(self): # TODO: check if all these delays are necessary for the processes to # stop in an orderly fashion self.stop() # TODO: check need for self.audo.terminate() time.sleep(1) self.root.after(3, self.root.destroy) sys.exit() def control_buttons(self): self.control_frame = Frame(self.root) self.control_frame.grid(row=0, column=1, sticky='nw') self.control_wave_type() self.control_sampling_rate() self.control_volume_time() self.r_type.set(1) self.select_type() def control_wave_type(self): type_outer_frame = Frame(self.control_frame, bd=1, relief='groove') type_outer_frame.grid(row=0, column=0, sticky='ew', pady=PADY_OUTER) self.r_type = IntVar() Label(type_outer_frame, text='Sound type').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) for column, mode in enumerate(SoundType): Radiobutton(type_outer_frame, text=mode.name.lower(), width=6, variable=self.r_type, value=mode.value, command=self.select_type).grid( row=1, column=column, stick='w', pady=PADY_INNER_2) self.type_frame = Frame(type_outer_frame) self.type_frame.grid( row=2, column=0, columnspan=3, sticky='w', pady=PADY_INNER_3) def select_type(self): self.error_message = '' self.selected_type = self.r_type.get() if self.selected_type == SoundType.NOTE: self.note_options() elif self.selected_type == SoundType.DESIGN: self.design_options() elif self.selected_type == SoundType.FILE: self.file_options() else: raise ValueError(f'check selected_type invalid value {self.selected_type}') self.select_sampling_display() def note_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() Label(self.type_frame, text='Frequency').pack(side='left') self.frequency_entry = Entry(self.type_frame, width=5) self.frequency_entry.insert(0, DEFAULT_FREQUENCY) self.frequency_entry.pack(side='left') Label(self.type_frame, text='Duration').pack(side='left') self.duration_entry = Entry(self.type_frame, width=5) self.duration_entry.insert(0, DEFAULT_DURATION) self.duration_entry.pack(side='left') def design_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() Label(self.type_frame, text='Duration').pack(side='left') self.duration_entry = Entry(self.type_frame, width=5) self.duration_entry.insert(0, DEFAULT_DURATION) self.duration_entry.pack(side='left') def file_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() sound_file = filedialog.askopenfile( title='Select sound file', filetypes=(('wav files', '*.wav'), ('all files', '*'))) try: file_name_text = f'Sound file: {Path(sound_file.name).name} ' except AttributeError: self.error_message = 'No file selected ...' Label(self.type_frame, text=self.error_message).pack(anchor='w') file_name_text = '' Label(self.type_frame, text=file_name_text).pack(anchor='w') if file_name_text: try: w = wave.open(sound_file.name) except (wave.Error, EOFError, AttributeError): self.error_message = 'Invalid wav file ...' Label(self.type_frame, text=self.error_message).pack(anchor='w') return frames = w.getnframes() channels = w.getnchannels() sample_width = w.getsampwidth() self.fs = w.getframerate() self.sound_byte_str = w.readframes(frames) self.duration = frames / self.fs * channels if sample_width == 1: self.fmt = f'{int(frames * channels)}B' else: self.fmt = f'{int(frames * channels)}h' print(f'frames: {frames}, channels: {channels}, ' f'sample width: {sample_width}, framerate: {self.fs}') def control_sampling_rate(self): sampling_outer_frame = Frame(self.control_frame, bd=1, relief='groove') sampling_outer_frame.grid( row=1, column=0, sticky='ew', pady=PADY_OUTER) Label(sampling_outer_frame, text='Sampling frequency').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) self.sampling_frame = Frame(sampling_outer_frame) self.sampling_frame.grid(row=1, column=0, stick='w', pady=PADY_INNER_3) def select_sampling_display(self): if self.selected_type in [SoundType.NOTE, SoundType.DESIGN]: self.display_sampling_options() elif self.selected_type == SoundType.FILE: self.display_sampling_rate() else: raise ValueError(f'check selected_type invalid value {self.selected_type}') def display_sampling_options(self): for widget in self.sampling_frame.winfo_children(): widget.destroy() self.r_fs = IntVar() self.r_fs.set(14) self.select_fs() for i, sampling_rate in enumerate(SamplingRate): Radiobutton(self.sampling_frame, text=sampling_rate.name[2:], width=6, variable=self.r_fs, value=sampling_rate.value, command=self.select_fs).grid( row=int(i / 3), column=(i % 3), sticky='w') def select_fs(self): self.fs = 2**self.r_fs.get() self.ax.set_xlim(1000 * PACKAGE_LENGTH / self.fs, 0) self.fig.canvas.draw() def display_sampling_rate(self): for widget in self.sampling_frame.winfo_children(): widget.destroy() Label(self.sampling_frame, text=f'Sampling rate: {self.fs} Hz').grid( row=0, column=0, stick='w') Label(self.sampling_frame, text=f'Duration: {self.duration:.1f} seconds').grid( row=1, column=0, stick='w') def control_volume_time(self): volume_outer_frame = Frame(self.control_frame, bd=1, relief='groove') volume_outer_frame.grid( row=2, column=0, sticky='ew', pady=PADY_OUTER) Label(volume_outer_frame, text='Volume').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) volume_slider = Scale(volume_outer_frame, from_=0, to_=1, resolution=VOLUME_RESOLUTION, orient='horizontal', command=self.set_volume, showvalue=0, ) volume_slider.set(self.volume) volume_slider.grid(row=1, column=0, sticky='w', pady=PADY_INNER_3) Label(volume_outer_frame, text='Time').grid( row=0, column=1, stick='w', pady=PADY_INNER_1, padx=(20, 0)) self.time_progress = ttk.Progressbar(volume_outer_frame, orient='horizontal', length=100, mode='determinate' ) self.time_progress.grid( row=1, column=1, sticky='w', pady=PADY_INNER_3, padx=(20, 0)) def set_volume(self, value): self.volume = float(value)
class NewNoteFrame(Frame): """"Window that provides UI(input fields and buttons) necessary for creating new note Derives from class Frame""" # class variables ipadx_val = 1 ipady_val = 10 label_font = '"Century Gothic" 10 bold' lbl_ctgr_text = 'Category:' lbl_dscr_text = 'Description:' lbl_date_text = 'Date:' lbl_prrt_text = 'Priority:' data_font = '"Segoe Print" 11' btn_width = 6 btn_conf_text = 'Confirm' btn_cancel_text = 'Cancel' btn_font = 'Arial 9' btn_padx = 25 btn_pady = 35 def __init__(self, master): """ctor""" super().__init__(master) self.pack(fill=BOTH, expand=True) # setting default priority to Normal, corresponding background color is lightyellow bgcolor = prrt2color_dict[ priority_names_lst[1]] # 'Normal':'lightyellow' self.create_widgets(master, bgcolor) def create_widgets(self, master, bg_color): """This method defines UI of the New Note window""" self.frm_main_newnote = Frame(self, bg=bg_color) self.frm_main_newnote.pack(fill=BOTH) self.lbl_category = Label(self.frm_main_newnote, bg=bg_color, font=__class__.label_font, text=__class__.lbl_ctgr_text) self.lbl_category.grid(row=0, column=0, sticky=W, ipadx=__class__.ipadx_val, ipady=__class__.ipady_val) self.cmbx_category = Combobox(self.frm_main_newnote, width=12, font=__class__.data_font) # ttk.Combobox self.cmbx_category.configure( values=category_names_lst ) # the values are: Personal, College, Work, Home self.cmbx_category.current(0) # i.e. default value is 'Personal' self.cmbx_category.grid(row=0, column=1, columnspan=2, sticky=W, ipadx=__class__.ipadx_val) self.lbl_description = Label(self.frm_main_newnote, bg=bg_color, font=__class__.label_font, text=__class__.lbl_dscr_text) self.lbl_description.grid(row=2, column=0, sticky=W, ipadx=__class__.ipadx_val, ipady=__class__.ipady_val) self.entry_description = Entry(self.frm_main_newnote, width=14, font=__class__.data_font) self.entry_description.grid(row=2, column=1, columnspan=2, sticky=W, ipadx=__class__.ipadx_val) self.lbl_date = Label(self.frm_main_newnote, bg=bg_color, font=__class__.label_font, text=__class__.lbl_date_text) self.lbl_date.grid(row=4, column=0, sticky=W, ipadx=__class__.ipadx_val, ipady=__class__.ipady_val) self.entry_date = Entry(self.frm_main_newnote, width=14, font=__class__.data_font) self.entry_date.grid(row=4, column=1, columnspan=2, sticky=W, ipadx=__class__.ipadx_val) self.lbl_priority = Label(self.frm_main_newnote, bg=bg_color, font=__class__.label_font, text=__class__.lbl_prrt_text) self.lbl_priority.grid(row=6, column=0, sticky=W, ipadx=__class__.ipadx_val, ipady=__class__.ipady_val) self.cmbx_priority = Combobox(self.frm_main_newnote, width=12, font=__class__.data_font) # ttk.Combobox self.cmbx_priority.configure( values=priority_names_lst) # the values are: High, Normal, Low self.cmbx_priority.current(1) # i.e. default value is 'Normal' self.cmbx_priority.bind("<<ComboboxSelected>>", self.action_priority2bgcolor) self.cmbx_priority.grid(row=6, column=1, columnspan=2, sticky=W, ipadx=__class__.ipadx_val) btn_confirm = Button( self.frm_main_newnote, font=__class__.btn_font, width=__class__.btn_width, text=__class__.btn_conf_text, command=master.destroy) # master is NewNote dialog btn_confirm.bind('<Button-1>', self.action_add_note) btn_confirm.grid(row=8, column=1, sticky=E, padx=__class__.btn_padx, pady=__class__.btn_pady) self.btn_cancel = Button( self.frm_main_newnote, font=__class__.btn_font, width=__class__.btn_width, text=__class__.btn_cancel_text, command=master.destroy ) # master = dlgNewNote #self.frm_buttons_view self.btn_cancel.grid(row=8, column=2, sticky=W, pady=__class__.btn_pady) def action_add_note(self, event): """This method registers new note; activated by click on button Confirm""" # reading note details from UI category_str = self.cmbx_category.get().strip() descr_str = self.entry_description.get().strip() date_str = self.entry_date.get().strip() priority_str = self.cmbx_priority.get().strip() new_note_obj = NotePureData( category_str, descr_str, date_str, priority_str) # object of class NotePureData notes_dict[ new_note_obj. id] = new_note_obj # adding new note object to the notes dictionary aux_filter_notes(category_filter_ctrlvar.get(), descr_filter_ctrlvar.get()) display_notes() db_insert_note(new_note_obj) # adding new note to the database def action_priority2bgcolor(self, event): """This method defines background color of the frame according to currently selected priority; activated by selection of a value from the Priority combo-box""" priority = self.cmbx_priority.get() # setting value of the background color according to the current task priority bgcolor = prrt2color_dict[ priority] # {'Low':'lightgreen', 'Normal':'lightyellow', 'High':'lightpink'} # setting background color of the NewNote frame and of the relevant widgets self.frm_main_newnote.configure(bg=bgcolor) widgets_lst = [ w for w in self.frm_main_newnote.winfo_children() if isinstance(w, Label) ] for w in widgets_lst: w.configure(bg=bgcolor)
def clear_frame(self, frame: tk.Frame): for child in frame.winfo_children(): child.destroy()
class LucteriosMainForm(Tk): def __init__(self): Tk.__init__(self) try: img = Image("photo", file=join( dirname(import_module('lucterios.install').__file__), "lucterios.png")) self.tk.call('wm', 'iconphoto', self._w, img) except: pass self.has_checked = False self.title(ugettext("Lucterios installer")) self.minsize(475, 260) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.running_instance = {} self.resizable(True, True) self.protocol("WM_DELETE_WINDOW", self.on_closing) self.ntbk = ttk.Notebook(self) self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W)) self.create_instance_panel() self.create_module_panel() stl = ttk.Style() stl.theme_use("default") stl.configure("TProgressbar", thickness=5) self.progress = ttk.Progressbar( self, style="TProgressbar", orient='horizontal', mode='indeterminate') self.progress.grid(row=1, column=0, sticky=(E, W)) self.btnframe = Frame(self, bd=1) self.btnframe.grid(row=2, column=0, columnspan=1) Button(self.btnframe, text=ugettext("Refresh"), width=20, command=self.refresh).grid( row=0, column=0, padx=3, pady=3, sticky=(N, S)) self.btnupgrade = Button( self.btnframe, text=ugettext("Search upgrade"), width=20, command=self.upgrade) self.btnupgrade.config(state=DISABLED) self.btnupgrade.grid(row=0, column=1, padx=3, pady=3, sticky=(N, S)) Button(self.btnframe, text=ugettext("Close"), width=20, command=self.on_closing).grid( row=0, column=2, padx=3, pady=3, sticky=(N, S)) def on_closing(self): all_stop = True instance_names = list(self.running_instance.keys()) for old_item in instance_names: if (self.running_instance[old_item] is not None) and self.running_instance[old_item].is_running(): all_stop = False if all_stop or askokcancel(None, ugettext("An instance is always running.\nDo you want to close?")): self.destroy() else: self.refresh() def destroy(self): instance_names = list(self.running_instance.keys()) for old_item in instance_names: if self.running_instance[old_item] is not None: self.running_instance[old_item].stop() del self.running_instance[old_item] Tk.destroy(self) def create_instance_panel(self): frm_inst = Frame(self.ntbk) frm_inst.grid_columnconfigure(0, weight=1) frm_inst.grid_rowconfigure(0, weight=1) frm_inst.grid_columnconfigure(1, weight=3) frm_inst.grid_rowconfigure(1, weight=0) self.instance_list = Listbox(frm_inst, width=20) self.instance_list.bind('<<ListboxSelect>>', self.select_instance) self.instance_list.pack() self.instance_list.grid(row=0, column=0, sticky=(N, S, W, E)) self.instance_txt = Text(frm_inst, width=75) self.instance_txt.grid(row=0, column=1, rowspan=2, sticky=(N, S, W, E)) self.instance_txt.config(state=DISABLED) self.btninstframe = Frame(frm_inst, bd=1) self.btninstframe.grid(row=1, column=0, columnspan=1) self.btninstframe.grid_columnconfigure(0, weight=1) Button(self.btninstframe, text=ugettext("Launch"), width=25, command=self.open_inst).grid( row=0, column=0, columnspan=2, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Modify"), width=10, command=self.modify_inst).grid(row=1, column=0, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Delete"), width=10, command=self.delete_inst).grid(row=1, column=1, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Save"), width=10, command=self.save_inst).grid(row=2, column=0, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Restore"), width=10, command=self.restore_inst).grid(row=2, column=1, sticky=(N, S)) Button(self.btninstframe, text=ugettext("Add"), width=25, command=self.add_inst).grid( row=3, column=0, columnspan=2, sticky=(N, S)) self.ntbk.add(frm_inst, text=ugettext('Instances')) def create_module_panel(self): frm_mod = Frame(self.ntbk) frm_mod.grid_columnconfigure(0, weight=1) frm_mod.grid_rowconfigure(0, weight=1) self.module_txt = Text(frm_mod) self.module_txt.grid(row=0, column=0, sticky=(N, S, W, E)) self.module_txt.config(state=DISABLED) self.ntbk.add(frm_mod, text=ugettext('Modules')) def do_progress(self, progressing): if not progressing: self.progress.stop() self.progress.grid_remove() else: self.progress.start(25) self.progress.grid(row=1, column=0, sticky=(E, W)) def enabled(self, is_enabled, widget=None): if widget is None: widget = self self.do_progress(not is_enabled) if is_enabled: widget.config(cursor="") else: widget.config(cursor="watch") if isinstance(widget, Button) and (widget != self.btnupgrade): if is_enabled and (not hasattr(widget, 'disabled') or not widget.disabled): widget.config(state=NORMAL) else: widget.config(state=DISABLED) else: for child_cmp in widget.winfo_children(): self.enabled(is_enabled, child_cmp) @ThreadRun def refresh(self, instance_name=None): if instance_name is None: instance_name = self.get_selected_instance_name() self.instance_txt.delete("1.0", END) self._refresh_instance_list() self.set_select_instance_name(instance_name) if not self.has_checked: self._refresh_modules() if self.instance_list.size() == 0: sleep(.3) self._refresh_modules() sleep(.3) self.after_idle(self.add_inst) def _refresh_modules(self): self.btnupgrade.config(state=DISABLED) self.module_txt.config(state=NORMAL) self.module_txt.delete("1.0", END) lct_glob = LucteriosGlobal() mod_lucterios, mod_applis, mod_modules = lct_glob.installed() self.module_txt.insert( END, ugettext("Lucterios core\t\t%s\n") % mod_lucterios[1]) self.module_txt.insert(END, '\n') self.module_txt.insert(END, ugettext("Application\n")) for appli_item in mod_applis: self.module_txt.insert( END, "\t%s\t%s\n" % (appli_item[0].ljust(30), appli_item[1])) self.module_txt.insert(END, ugettext("Modules\n")) for module_item in mod_modules: self.module_txt.insert( END, "\t%s\t%s\n" % (module_item[0].ljust(30), module_item[1])) extra_urls = lct_glob.get_extra_urls() if len(extra_urls) > 0: self.module_txt.insert(END, "\n") self.module_txt.insert(END, ugettext("Pypi servers\n")) for extra_url in extra_urls: self.module_txt.insert(END, "\t%s\n" % extra_url) self.module_txt.config(state=DISABLED) self.has_checked = True self.after(1000, lambda: Thread(target=self.check).start()) def _refresh_instance_list(self): self.instance_list.delete(0, END) luct_glo = LucteriosGlobal() instance_list = luct_glo.listing() for item in instance_list: self.instance_list.insert(END, item) if item not in self.running_instance.keys(): self.running_instance[item] = None instance_names = list(self.running_instance.keys()) for old_item in instance_names: if old_item not in instance_list: if self.running_instance[old_item] is not None: self.running_instance[old_item].stop() del self.running_instance[old_item] def set_select_instance_name(self, instance_name): cur_sel = 0 for sel_iter in range(self.instance_list.size()): if self.instance_list.get(sel_iter) == instance_name: cur_sel = sel_iter break self.instance_list.selection_set(cur_sel) self.select_instance(None) def get_selected_instance_name(self): if len(self.instance_list.curselection()) > 0: return self.instance_list.get(int(self.instance_list.curselection()[0])) else: return "" def set_ugrade_state(self, must_upgrade): if must_upgrade: self.btnupgrade.config(state=NORMAL) self.btnupgrade["text"] = ugettext("Upgrade needs") else: self.btnupgrade["text"] = ugettext("No upgrade") self.btnupgrade.config(state=DISABLED) def check(self): must_upgrade = False try: lct_glob = LucteriosGlobal() _, must_upgrade = lct_glob.check() finally: self.after(300, self.set_ugrade_state, must_upgrade) @ThreadRun def upgrade(self): self.btnupgrade.config(state=DISABLED) self.instance_list.config(state=DISABLED) try: from logging import getLogger admin_path = import_module( "lucterios.install.lucterios_admin").__file__ proc = Popen( [sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE) value = proc.communicate()[0] try: value = value.decode('ascii') except: pass six.print_(value) if proc.returncode != 0: getLogger("lucterios.admin").error(value) else: getLogger("lucterios.admin").info(value) showinfo(ugettext("Lucterios installer"), ugettext( "The application must restart")) python = sys.executable os.execl(python, python, *sys.argv) finally: self._refresh_modules() self.btnupgrade.config(state=NORMAL) self.instance_list.config(state=NORMAL) @ThreadRun def select_instance(self, evt): if self.instance_list['state'] == NORMAL: self.instance_list.config(state=DISABLED) try: instance_name = self.get_selected_instance_name() self.instance_txt.configure(state=NORMAL) self.instance_txt.delete("1.0", END) if instance_name != '': if instance_name not in self.running_instance.keys(): self.running_instance[instance_name] = None inst = LucteriosInstance(instance_name) inst.read() self.instance_txt.insert(END, "\t\t\t%s\n\n" % inst.name) self.instance_txt.insert( END, ugettext("Database\t\t%s\n") % inst.get_database_txt()) self.instance_txt.insert( END, ugettext("Appli\t\t%s\n") % inst.get_appli_txt()) self.instance_txt.insert( END, ugettext("Modules\t\t%s\n") % inst.get_module_txt()) self.instance_txt.insert( END, ugettext("Extra\t\t%s\n") % inst.get_extra_txt()) self.instance_txt.insert(END, '\n') if self.running_instance[instance_name] is not None and self.running_instance[instance_name].is_running(): self.instance_txt.insert(END, ugettext( "=> Running in http://%(ip)s:%(port)d\n") % {'ip': self.running_instance[instance_name].lan_ip, 'port': self.running_instance[instance_name].port}) self.btninstframe.winfo_children()[0]["text"] = ugettext( "Stop") else: self.running_instance[instance_name] = None self.instance_txt.insert(END, ugettext("=> Stopped\n")) self.btninstframe.winfo_children()[0]["text"] = ugettext( "Launch") else: self.btninstframe.winfo_children()[0]["text"] = ugettext( "Launch") self.btninstframe.winfo_children()[0].disabled = ( instance_name == '') self.btninstframe.winfo_children()[1].disabled = ( instance_name == '') self.btninstframe.winfo_children()[2].disabled = ( instance_name == '') self.btninstframe.winfo_children()[3].disabled = ( instance_name == '') self.btninstframe.winfo_children()[4].disabled = ( instance_name == '') self.instance_txt.configure(state=DISABLED) finally: setup_from_none() self.instance_list.config(state=NORMAL) @ThreadRun def add_modif_inst_result(self, result, to_create): inst = LucteriosInstance(result[0]) inst.set_extra("LANGUAGE_CODE='%s'" % result[5]) inst.set_appli(result[1]) inst.set_module(result[2]) inst.set_database(result[4]) if to_create: inst.add() else: inst.modif() inst = LucteriosInstance(result[0]) inst.set_extra(result[3]) inst.security() self.refresh(result[0]) def add_inst(self): self.enabled(False) try: self.do_progress(False) ist_edt = InstanceEditor() ist_edt.execute() ist_edt.transient(self) self.wait_window(ist_edt) finally: self.enabled(True) if ist_edt.result is not None: self.add_modif_inst_result(ist_edt.result, True) def modify_inst(self): self.enabled(False) try: self.do_progress(False) ist_edt = InstanceEditor() ist_edt.execute(self.get_selected_instance_name()) ist_edt.transient(self) self.wait_window(ist_edt) finally: self.enabled(True) if ist_edt.result is not None: self.add_modif_inst_result(ist_edt.result, False) @ThreadRun def delete_inst_name(self, instance_name): inst = LucteriosInstance(instance_name) inst.delete() self.refresh() def delete_inst(self): setup_from_none() instance_name = self.get_selected_instance_name() if askokcancel(None, ugettext("Do you want to delete '%s'?") % instance_name): self.delete_inst_name(instance_name) else: self.refresh() @ThreadRun def open_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': try: if instance_name not in self.running_instance.keys(): self.running_instance[instance_name] = None if self.running_instance[instance_name] is None: port = FIRST_HTTP_PORT for inst_obj in self.running_instance.values(): if (inst_obj is not None) and (inst_obj.port >= port): port = inst_obj.port + 1 self.running_instance[instance_name] = RunServer( instance_name, port) self.running_instance[instance_name].start() else: self.running_instance[instance_name].stop() self.running_instance[instance_name] = None finally: self.set_select_instance_name(instance_name) @ThreadRun def save_instance(self, instance_name, file_name): inst = LucteriosInstance(instance_name) inst.filename = file_name if inst.archive(): showinfo(ugettext("Lucterios installer"), ugettext( "Instance saved to %s") % file_name) else: showerror( ugettext("Lucterios installer"), ugettext("Instance not saved!")) self.refresh(instance_name) def save_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': file_name = asksaveasfilename( parent=self, filetypes=[('lbk', '.lbk'), ('*', '.*')]) if file_name != '': self.save_instance(instance_name, file_name) @ThreadRun def restore_instance(self, instance_name, file_name): if file_name[-4:] == '.bkf': rest_inst = MigrateFromV1(instance_name, withlog=True) else: rest_inst = LucteriosInstance(instance_name) rest_inst.filename = file_name if rest_inst.restore(): showinfo(ugettext("Lucterios installer"), ugettext( "Instance restore from %s") % file_name) else: showerror( ugettext("Lucterios installer"), ugettext("Instance not restored!")) self.refresh(instance_name) def restore_inst(self): instance_name = self.get_selected_instance_name() if instance_name != '': file_name = askopenfilename( parent=self, filetypes=[('lbk', '.lbk'), ('bkf', '.bkf'), ('*', '.*')]) if file_name != '': self.restore_instance(instance_name, file_name) def execute(self): self.refresh() center(self, (700, 300)) self.mainloop()
class Hangman: """Hangman Game MVP""" def __init__(self, root): """ - Save references for hangman game-stage images - Initalize widgets, layout - Populate GUI with secret word/phrase """ self.master = root self.master.title("Hangman") self.master.iconbitmap(f"{dirname(__file__)}/img/icon.ico") self.center_window() self.master.resizable(False, False) self.stages = [] self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/0.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/1.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/2.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/3.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/4.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/5.gif", master=self.master)) self.stages.append( PhotoImage(file=f"{dirname(__file__)}/img/6.gif", master=self.master)) # Widgets self.hangman = Label(self.master) self.current_guess = StringVar(self.master) self.current_guess.set("A") self.btn_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.option_menu = OptionMenu(self.btn_frame, self.current_guess, "") self.option_menu.config(font="Calibri 9", width=3) self.scale = Scale(self.btn_frame, orient="horizontal", from_=1, to=5, label=" Words") self.scale.set(3) self.new_game_btn = Button( self.btn_frame, text="New Game", command=self.new_game, width=20, ) self.guess_btn = Button( self.btn_frame, text="Guess", width=10, command=lambda: self.guess(self.current_guess.get())) self.letter_frame = Frame(self.master, borderwidth=2, relief="groove", padx=10, pady=10) self.result_label = Label(self.master, font="Calibri 20", foreground="red") # Layout self.master.columnconfigure(0, weight=1) self.hangman.grid(row=0, column=0) self.btn_frame.grid(row=1, column=0, pady=20) self.scale.grid(row=0, column=1, columnspan=2, pady=10) self.new_game_btn.grid(row=1, column=1, columnspan=2, pady=10) self.guess_btn.grid(row=2, column=1, padx=2) self.option_menu.grid(row=2, column=2) self.letter_frame.grid(row=2, column=0, pady=10) self.result_label.grid(row=3, column=0) # Initalize self.new_game() def __str__(self): """Return address of self""" return f"Hangman GUI @ {hex(id(self))}" def new_game(self): """ - Reset GUI & flags from previous round, fill optionmenu with a fresh alphabet - Populate self.secret and letter_frame with a new secret phrase, initalized to underscores (except for whitespace) """ self.hangman.config(image=self.stages[0]) self.result_label.config(text="") for widget in self.letter_frame.winfo_children(): widget.destroy() self.stage = 0 self.blanks = [] self.game_over = False # self.secret = generate_random_phrase() self.secret = generate_random_words(self.scale.get()) for i, letter in enumerate(self.secret): if letter == " ": letter_label = Label(self.letter_frame, text=" ") self.blanks.append(letter_label) else: letter_label = Label(self.letter_frame, text="_") self.blanks.append(letter_label) letter_label.config(font=('calibri', 15)) letter_label.grid(row=0, column=i, padx=1) self.option_menu["menu"].delete(0, "end") for char in ascii_uppercase: self.option_menu["menu"].add_command(label=char, command=_setit( self.current_guess, char)) self.current_guess.set("A") def guess(self, guessed: str): """ - Remove the guessed letter from the optionmenu - Increment the stage if the guess is incorrect, check if we're at last stage - If we reach final stage, game over & result_label set accordingly - Otherwise, reveal the guessed letter(s) in their respective label(s) - Finally, check if we reached the winning condition, in which no labels contain underscores - If so, game over & result_label set to "winner" message """ if self.game_over: return indices = [i for i, x in enumerate(self.secret) if x == guessed] r_index = self.option_menu["menu"].index(guessed) self.option_menu["menu"].delete(r_index) self.current_guess.set(self.option_menu["menu"].entrycget(0, "label")) if not indices: self.stage += 1 self.hangman.config(image=self.stages[self.stage]) if self.stage >= 6: self.game_over = True return self.result_label.config(text=f"Game Over.\n{self.secret}") for i in indices: self.blanks[i].config(text=guessed) winner = True for widget in self.letter_frame.winfo_children(): if (widget.cget("text") == "_"): winner = False if (winner): self.result_label.config(text="Winner!") self.game_over = True def center_window(self): self.master.geometry("600x800") self.master.update() (width_offset, height_offset) = self.get_offset(self.master) self.master.geometry(f"+{width_offset}+{height_offset}") @staticmethod def get_offset(tk_window): """ Returns an appropriate offset for a given tkinter toplevel, such that it always is created center screen on the primary display. """ width_offset = int((tk_window.winfo_screenwidth() / 2) - (tk_window.winfo_width() / 2)) height_offset = int((tk_window.winfo_screenheight() / 2) - (tk_window.winfo_height() / 2)) return (width_offset, height_offset)
class Gui(Frame): #============================================================================== # Metodos Basicos #============================================================================== def __init__(self, parent=None): Frame.__init__(self, parent) # Atributos GUI self.parent = parent self.file_opt = self.flopt = {} w, h = self.parent.winfo_screenwidth(), self.parent.winfo_screenheight( ) self.largura = w - 20 self.altura = h - 20 # Atributos funcionais self.img = None self.imgOld = None self.arqImg = StringVar() self.arqImg.set('') self.formatos = {} self.formatos['gif'] = 'GIF' self.formatos['jpg'] = 'JPEG' self.formatos['jpeg'] = 'JPEG' self.formatos['png'] = 'PNG' self.formatos['bmp'] = 'BMP' self.formatos['tif'] = 'TIFF' self.formatos['tiff'] = 'TIFF' self.formatos['ppm'] = 'PPM' self.formatos['pbm'] = 'PPM' self.formatos['pgm'] = 'PPM' self.tipos = [('Imagens', ('*.jpg', '*.png', '*.gif', '*.bmp', '*.ppm', '*.pgm', '*.pbm')), ('JPEG', '*.jpg'), ('PNG', '*.png'), ('GIF', '*.gif'), ('BMP', '*.bmp'), ('PPM', '*.ppm'), ('PGM', '*.pgm'), ('PBM', '*.pbm'), ('Todos arquivos', '*')] # Cria/atualiza GUI self.createWidgets() self.update_idletasks() #============================================================================== # Metodos relacionados ao comportamento da GUI #============================================================================== def createWidgets(self): self.canvas = Canvas(self.parent, width=1366, height=768) self.scroll = Scrollbar(self.parent, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.scroll.set) self.scroll.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) # Configura barra de menus self.menubar = Menu(self.parent) self.parent.config(menu=self.menubar) # Menu arquivo e suas opcoes self.menuArquivo = Menu(self.menubar) self.menuArquivo.add_command(label='Abrir', underline=0, command=self.abrir) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Salvar', underline=0, command=self.salvar) self.menuArquivo.add_command(label='Salvar Como...', underline=0, command=self.salvarComo) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Fechar imagem(ns)', underline=0, command=self.fecharArquivo) self.menuArquivo.add_command(label="Sair", underline=3, command=self.onExit) self.menubar.add_cascade(label="Arquivo", underline=0, menu=self.menuArquivo) # Menu editar e suas opcoes self.menuEditar = Menu(self.menubar) self.menuEditar.add_command(label='Desfazer', underline=0, command=self.desfazer) self.menubar.add_cascade(label="Editar", underline=0, menu=self.menuEditar) # Menu Imagem e suas opcoes self.menuImagem = Menu(self.menubar) self.submenuConverte = Menu(self.menuImagem) self.submenuConverte.add_command(label='Colorido RGB', underline=0, command=lambda: self.converte('RGB')) self.submenuConverte.add_command(label='Colorido RGBA', underline=0, command=lambda: self.converte('RGBA')) self.submenuConverte.add_command(label='Escala de cinza', underline=0, command=lambda: self.converte('L')) self.submenuConverte.add_command(label='Binario', underline=0, command=lambda: self.converte('1')) self.menuImagem.add_command(label='Informacoes gerais', underline=0, command=self.info) self.menuImagem.add_separator() self.menuImagem.add_cascade(label='Converter', underline=0, menu=self.submenuConverte) self.menubar.add_cascade(label="Imagem", underline=0, menu=self.menuImagem) # Menu de operacoes sobre cores e suas opcoes self.menuCores = Menu(self.menubar) self.submenuCinza = Menu(self.menuCores) self.submenuCinza.add_command(label='Decomposicao de Maximo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Decomposicao de Minimo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Average', underline=0, command=lambda: self.mudaCor('average')) self.submenuCinza.add_command(label='Lightness', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Luminosity', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente R', underline=11, command=lambda: self.mudaCor('r')) self.submenuCinza.add_command(label='Componente G', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente B', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Quantidade arbitraria de tons', underline=0, command=self.emConstrucao) self.submenuHalftone = Menu(self.menuCores) self.submenuHalftone.add_command( label='Bayer 2x2', underline=6, command=lambda: self.halftoning('bayer2')) self.submenuHalftone.add_command(label='Bayer 5x5', underline=6, command=self.emConstrucao) self.submenuHalftone.add_command(label='Atkinson', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Sierra Lite', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Jarvis, Judice, and Ninke', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command( label='Floyd-Steinberg', underline=0, command=lambda: self.halftoning('floyd')) self.menuCores.add_cascade(label='Tons de cinza', underline=0, menu=self.submenuCinza) self.menuCores.add_command(label='Inverter', underline=0, command=lambda: self.mudaCor('inv')) self.menuCores.add_command(label='Sepia', underline=0, command=self.emConstrucao) self.menuCores.add_separator() self.menuCores.add_command(label='Pseudo Binaria', underline=0, command=self.binaria) self.menuCores.add_cascade(label='Halftoning', underline=0, menu=self.submenuHalftone) self.menuCores.add_separator() self.menuCores.add_command(label='Cisalhamento de Cor', underline=0, command=self.emConstrucao) self.menuCores.add_command(label='Balanco de cores', underline=0, command=self.balancoCor) self.menuCores.add_command(label='Quantizacao de cores', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Cores", underline=0, menu=self.menuCores) # Menu de operacoes topologicas e suas opcoes self.menuTopologia = Menu(self.menubar) self.menuTopologia.add_command(label='Rotular Componentes', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Transformada da Distancia', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Esqueletizacao', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Topologia", underline=0, menu=self.menuTopologia) # Menu do trabalho e suas opcoes self.trabalho = Menu(self.menubar) self.trabalho.add_command(label='Tarefa 01', underline=20, command=self.abrir) # Grupo principal, onde serao atualizados os widgets self.grupoPrincipal = Frame(self.canvas, width=self.largura, height=self.altura, bd=1, padx=10, pady=10) self.grupoPrincipal.pack() #self.grupoPrincipal.grid_propagate(False) # Faz com que o Frame nao seja redimensionado com a mudanca dos widgets self.canvas.create_window((4, 20), window=self.grupoPrincipal, anchor="nw", tags="self.grupoPrincipal") self.grupoPrincipal.bind("<Configure>", self.OnFrameConfigure) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all")) def onExit(self): self.parent.destroy() def limpaTela(self): for widget in self.grupoPrincipal.winfo_children(): widget.destroy() def emConstrucao(self): tkm.showinfo(title="Em construcao", message="Recurso em Construcao...") def load_file(self, titulo, varFile, tipos): if os.path.isfile(varFile.get()): path = os.path.dirname(varFile.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = tipos arquivo = tkf.askopenfilename(title=titulo, **self.flopt) if arquivo: varFile.set(arquivo) def widgetFile(self, master, titulo, texto, varFile, tuplaFiletype): esteFrame = LabelFrame(master, text=titulo, padx=5, pady=5) j = 0 varFile.set("Nenhum arquivo informado") labelRotulo = Label(esteFrame, text=texto) labelRotulo.grid(row=j, column=0, sticky=cte.E) botao = Button( esteFrame, text="Procurar", command=lambda: self.load_file(texto, varFile, tuplaFiletype), width=10) botao.grid(row=j, column=1, pady=5, sticky=cte.W) j += 1 labelArq = Label(esteFrame, textvariable=varFile, bg='white') labelArq.grid(row=j, column=0, columnspan=2) return esteFrame def refreshImg(self): try: self.grupoPrincipal.photo = ImageTk.PhotoImage(self.img.img) if hasattr(self.grupoPrincipal, 'canvas'): self.grupoPrincipal.canvas.destroy() self.grupoPrincipal.canvas = Canvas(self.grupoPrincipal) self.grupoPrincipal.canvas.create_image( 0, 0, image=self.grupoPrincipal.photo, anchor=cte.NW) self.grupoPrincipal.canvas.config(bg='white', width=self.img.altura, height=self.img.largura) #self.grupoPrincipal.canvas.place(x=self.parent.winfo_screenwidth()/2, y=self.parent.winfo_screenheight()/2, anchor=cte.CENTER) self.grupoPrincipal.canvas.place(x=0, y=0, anchor=cte.NW) self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao meno Arquivo #============================================================================== def abrir(self): try: self.limpaTela() self.load_file('Arquivos de Imagem', self.arqImg, self.tipos) self.img = Imagem(self.arqImg.get()) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def saveFile(self): try: nome, extensao = os.path.splitext(self.arqImg.get()) extensao = extensao.replace('.', '') self.img.salva(self.arqImg.get(), self.formatos[extensao.lower()]) tkm.showinfo( 'Sucesso', 'Arquivo %s salvo com sucesso' % os.path.basename(self.arqImg.get())) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvar(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvarComo(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: if os.path.isfile(self.arqImg.get()): path = os.path.dirname(self.arqImg.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = self.tipos nomeArq = tkf.asksaveasfilename(title='Salvar imagem como...', **self.flopt) if nomeArq: self.arqImg.set(nomeArq) self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def fecharArquivo(self): if not hasattr( self.grupoPrincipal, 'canvas') or self.grupoPrincipal.canvas.find_all() == (): tkm.showwarning('Aviso', 'Nao ha imagens abertas') else: try: self.img = self.imgOld = None self.grupoPrincipal.canvas.delete('all') self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Editar #============================================================================== def desfazer(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') elif self.imgOld is None: tkm.showwarning('Aviso', 'Impossivel Desfazer') else: try: temp = self.img self.img = self.imgOld self.imgOld = temp self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Cores #============================================================================== def mudaCor(self, metodo): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.mudaCor(self.imgOld, metodo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def binaria(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.binaria(self.imgOld) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def getFatoresBalanco(self): self.fatores = [float(self.escalaFatorR.get())] self.fatores.append(float(self.escalaFatorG.get())) self.fatores.append(float(self.escalaFatorB.get())) self.w.destroy() def formBalanco(self): self.fator = None self.fatores = None self.w = Toplevel(self) self.w.wm_title("Informar os fatores de ajuste") self.w.geometry("+%d+%d" % (self.winfo_rootx() + 50, self.winfo_rooty() + 50)) self.w.focus_set() i = 0 self.labelFatorR = Label(self.w, text='Ajuste em R', width=25) self.labelFatorR.grid(row=i, column=0) self.escalaFatorR = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorR.set(0.5) self.escalaFatorR.grid(row=i, column=1) i += 1 self.labelFatorG = Label(self.w, text='Ajuste em G', width=25) self.labelFatorG.grid(row=i, column=0) self.escalaFatorG = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorG.set(0.5) self.escalaFatorG.grid(row=i, column=1) i += 1 self.labelFatorB = Label(self.w, text='Ajuste em B', width=25) self.labelFatorB.grid(row=i, column=0) self.escalaFatorB = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorB.set(0.5) self.escalaFatorB.grid(row=i, column=1) i += 1 self.botaoFator = Button(self.w, text='Ok', command=self.getFatoresBalanco, width=10) self.botaoFator.grid(row=i, column=0, columnspan=2) self.w.grid() def balancoCor(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.formBalanco() self.wait_window(self.w) if self.fatores is not None: self.imgOld = self.img self.img = cor.balanco(self.imgOld, self.fatores[0], self.fatores[1], self.fatores[2]) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def halftoning(self, metodo='bayer2'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img if metodo == 'bayer2': self.img = cor.bayer(self.imgOld) elif metodo == 'floyd': self.img = cor.floyd(self.imgOld) else: raise Exception('Metodo de halftoning desconhecido') self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Imagem #============================================================================== def converte(self, modo='RGB'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img.copia() self.img.converte(modo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def info(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: texto = 'Imagem %s, modo: %s (%d x %d pixels)' % ( self.img.img.format, self.img.img.mode, self.img.img.size[0], self.img.img.size[1]) tkm.showinfo('Aviso', texto) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args))
class AOTGui: def __init__(self): self.gui = Tk() self.gui.title(client_title) self.gui.geometry('800x500') self.numRow = 0 scrollbar = Scrollbar(self.gui) self.canvas = Canvas(self.gui, bg='pink', yscrollcommand=scrollbar.set) scrollbar.config(command=self.canvas.yview) scrollbar.pack(side=RIGHT, fill=Y) self.frame = Frame(self.canvas) self.canvas.pack(side=LEFT, fill=BOTH, expand=True) self.canvas.create_window(0, 0, window=self.frame, anchor=NW) self.var_city = StringVar(self.frame) self.var_file = StringVar(self.frame) self.var_city.set(city_list[0]) self.var_file.set(file_list[0]) Label(self.frame, text='Version '+str(client_version), bg='turquoise').grid(row=0, column=0) Label(self.frame, text='City').grid(row=1, column=0, sticky=W) OptionMenu(self.frame, self.var_city, *city_list).grid(row=1, column=1, sticky=W) Label(self.frame, text='Items', padx=15).grid(row=1, column=2, sticky=W) OptionMenu(self.frame, self.var_file, *file_list).grid(row=1, column=3, sticky=W) Button(self.frame, text='Search', command=self.cmd_search).grid(row=1, column=4, sticky=W) Label(self.frame, text='Item').grid(row=2, column=0, columnspan=2, sticky=W) Label(self.frame, text='Price', padx=15).grid(row=2, column=2, sticky=W) Label(self.frame, text='Black Market', padx=15).grid(row=2, column=3, sticky=W) Label(self.frame, text='Profit', padx=15).grid(row=2, column=4, sticky=W) self.gui.update() self.canvas.config(scrollregion=self.canvas.bbox('all')) self.gui.mainloop() def human_readable_value(self,value): if 1e3 <= value < 1e6: return str(round(value/1e3)) + ' k' elif 1e6 <= value: return str(round(value/1e6, 1)) + ' m' else: return str(value) def add_item(self, item_id, name, price, blackmarket, profit): img = PhotoImage(file='img/'+item_id+'.png') label = Label(self.frame, image=img) label.image = img label.grid(row=3+self.numRow, column=0, sticky=W) Label(self.frame, text=name).grid(row=3+self.numRow, column=1, sticky=W) Label(self.frame, text=self.human_readable_value(price), padx=15).grid(row=3+self.numRow, column=2, sticky=W) Label(self.frame, text=self.human_readable_value(blackmarket), padx=15).grid(row=3+self.numRow, column=3, sticky=W) Label(self.frame, text=self.human_readable_value(profit), padx=15).grid(row=3+self.numRow, column=4, sticky=W) self.numRow += 1 self.gui.update() self.canvas.config(scrollregion=self.canvas.bbox('all')) def reset(self): self.numRow = 0 for widget in self.frame.winfo_children()[10:]: widget.destroy() self.frame.pack_forget() def cmd_search(self): self.reset() city = self.var_city.get() item_file = 'items/' + self.var_file.get() item_query = open(item_file, 'r').read().replace('\n', ',')[:-1] item_array = open(item_file, 'r').read().split('\n') r = item_requests(item_array, city) if not item_query: return response_city= r[0] response_blackmarket = r[1] # response_city = requests.get(data_route + item_query + '?locations=' + city).json() # response_blackmarket = requests.get(data_route + item_query + '?locations=blackmarket').json() offer_dict = {} for entry in response_city: item = entry['item_id'] value = entry['sell_price_min'] quality = entry['quality'] name = item + "#" + str(quality) if value: offer_dict[name] = [value, 0] for entry in response_blackmarket: item = entry['item_id'] value = entry['buy_price_max'] time = entry['sell_price_min_date'] a = datetime.now() - datetime.strptime(time, '%Y-%m-%dT%H:%M:%S') qualities = [x for x in range(entry['quality'], 6)] items_to_purchase = [item+"#"+str(x) for x in qualities] city_values = [] for item_key in items_to_purchase: if item_key in offer_dict.keys(): item_city_value = offer_dict[item_key][0] city_values.append(item_city_value) if len(city_values) > 0: offer_dict[items_to_purchase[0]] = [min(city_values), value, a] full_list = sorted(offer_dict.items(), key=lambda x:(x[0], -x[1][1]+x[1][0], time)) profit_list = [] for item in full_list: name = item[0] values_pair = item[1] time = values_pair[2] profit = round(values_pair[1]*(1-tax) - values_pair[0]) if profit > 0 and (1 - values_pair[0] / profit) < 0.85: profit_list.append([name, values_pair, profit, time]) profit_list.sort(key=lambda x:(x[2])) i = 0 for item in profit_list[::-1]: _id, _quality = item[0].split('#') enchant = item[0][-3] if "@" in item[0] else '0' tier = _id[1] quality = quality_list[int(_quality) -1] if _id in id_to_name.keys(): translated_name = id_to_name[_id] else: tier = '' enchant = '' translated_name = _id name = f'{tier}.{enchant} {translated_name}, {quality}' item_id = item[0].split('#')[0] price = item[1][0] blackmarket = item[1][1] profit = item[2] time = item [3] self.add_item(item_id, name, price, blackmarket, profit) i += 1
)], ) root.style.configure("LabeledProgressbar", text="0 % ") # ('clam', 'alt', 'default', 'classic') root.style.theme_use("clam") root.style.configure("TButton", font="helvetica 24") root.style.configure("LabeledProgressbar", foreground="#666", background="#1da1f2", height=100) root.style.configure("TLabel", background="white") wrap = 1400 status = Frame(root) progressbar = ttk.Progressbar( status, orient="horizontal", length=w, mode="determinate", style="LabeledProgressbar", ) status.pack(side=BOTTOM, fill=X, expand=False) progressbar.pack(side=BOTTOM, ipady=10) progressbar["maximum"] = total_images for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) go_to_next_image() root.mainloop()
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((host, port)) self.grid() self.columnconfigure(0, minsize=100) self.columnconfigure(1, minsize=200) self.columnconfigure(2, minsize=200) self.columnconfigure(3, minsize=150) self.columnconfigure(4, minsize=150) self.columnconfigure(5, minsize=150) self.columnconfigure(6, minsize=150) self.create_widgets() self.settables = self.assemble_settables() self.gui_logger = logging.getLogger('gui') self.request_update() def create_widgets(self): self.create_monitor() self.create_check_buttons() self.create_ranges() self.create_scales() self.create_radio_buttons() self.create_voices() self.quitButton = Button(self, text='Quit', command=self.quit) self.quitButton.grid(columnspan=7, sticky=E + W) def assemble_settables(self): settables = self.winfo_children() for w in settables: settables += w.winfo_children() return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']] def create_radio_buttons(self): # Scale related entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR', 'GREEK_CHROMATIC', 'GREEK_ENHARMONIC'] self.scale = StringVar() self.scale.set('DIATONIC') self.rb_frame = Frame(self) for e in entries: rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W, command=self.send_scale, variable=self.scale) rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W) self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3) def create_monitor(self): self.monitor_frame = LabelFrame(self, text="Monitor and Transport") this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL, from_=1, to=16, resolution=1) this_cycle.disable, this_cycle.enable = (None, None) this_cycle.ref = 'cycle_pos' this_cycle.grid(column=0, row=0, sticky=E + W) self.updateButton = Button(self.monitor_frame, text='Reload all Settings', command=self.request_update) self.updateButton.grid(row=1, sticky=E + W) self.ForceCaesuraButton = Button(self.monitor_frame, text='Force Caesura', command=self.force_caesura) self.ForceCaesuraButton.grid(row=2, sticky=E + W) self.saveBehaviourButton = Button(self.monitor_frame, text='Save current behaviour', command=self.request_saving_behaviour) self.saveBehaviourButton.grid(row=3, sticky=E + W) self.saveBehaviourNameEntry = Entry(self.monitor_frame) self.saveBehaviourNameEntry.grid(row=4, sticky=E + W) self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour) self.selected_behaviour = StringVar() self.selected_behaviour.trace('w', self.new_behaviour_chosen) self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, None,) self.savedBehavioursMenu.grid(row=5, sticky=E + W) self.monitor_frame.grid(column=0, row=10, sticky=E + W) def request_update(self): self.send({'sys': 'update'}) def request_saving_behaviour(self, event=None): """callback for save behaviour button and textentry""" if event and event.widget == self.saveBehaviourNameEntry: if event.keysym == 'Return': name = self.saveBehaviourNameEntry.get() self.saveBehaviourNameEntry.delete(0, len(name)) else: return else: # button was pressed name = self.saveBehaviourNameEntry.get() if name: self.send({'sys': ['save_behaviour', name]}) def force_caesura(self): self.send({'force_caesura': True}) def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb if isinstance(options, dict) and 'label' in list(options.keys()): label = options['label'] else: label = cb[9:] if cb[:9] == 'automate_' else cb setattr(self, name, IntVar( value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W) def wt_handler(self, event): print(event.widget.tk) ref = event.widget.ref self.send({ref: getattr(self, ref).get()}) def create_check_buttons(self): self.cb_frame = LabelFrame(self, text="Global Settings") for cb in CHECK_BUTTONS: label = cb target_parent = self.cb_frame if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()): target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame']) setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and CHECK_BUTTONS[cb]['val'] or CHECK_BUTTONS[cb])) self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and 'disable' in list(CHECK_BUTTONS[cb].keys())) self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children())) self.this_cb.ref = cb for but in GLOBAL_BUTTONS: label = but ele = GLOBAL_BUTTONS[but] this_but = Button(self.cb_frame, text=but) this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler'])) this_but.ref = but this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children())) self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N) def new_behaviour_chosen(self, a, b, c): self.send({'sys': ['change_behaviour', self.selected_behaviour.get()]}) def set_value(self, name, val): '''sets a widget to the specified value various different widget types need custom setting functionality''' direct = ['scale', 'wavetable_generation_type', 'partial_pool'] if [x for x in direct if match("(voice_\d_|)" + x, name)]: self.gui_logger.info("setting: '{0}' to '{1}' in GUI".format(name, val)) getattr(self, name).set(val) return if name == 'saved_behaviours' and len(val): self.savedBehavioursMenu.destroy() self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, *sorted(val)) self.savedBehavioursMenu.grid(row=5, sticky=E + W) return for w in self.settables: typ = w.__class__.__name__ if w.ref == name: # print "setting '{0}' of type: '{1}' to: {2}".format(name, typ, val) if typ == 'Scale': w.set(val) elif typ == "Checkbutton": w.select() if val else w.deselect() def check_boxes_handler(self, event): '''handles checkbox events. shows and hides gui elements according to their enable/disable fields''' # print event.__dict__ # print event.widget.__dict__ ref = event.widget.ref val = not getattr(self, ref).get() # because is read before the var is changed self.send({ref: val}) # print ref, val # handle gui elements # enable/disable functionality temporarily(?) commented on: # Wed Aug 17 09:39:54 CEST 2011 # if event.widget.disable: # for w in self.children.values(): # # # this try clause is for debugging, remove when stable # try: # w.ref # #print w.ref # except: # pass # if (w.__class__.__name__ == 'Scale' and # (w.disable or w.enable)): # if w.disable == ref: # if val: # w.grid() # else: # w.grid_remove() # elif w.enable == ref: # if val: # w.grid_remove() # else: # w.grid() # #print w.disable, w.enable def create_scales(self): counter = 0 for sca in SCALES: label = SCALES[sca]['label'] if 'label' in list(SCALES[sca].keys()) else sca setattr(self, 'min_' + sca, SCALES[sca]['min']) setattr(self, 'max_' + sca, SCALES[sca]['max']) self.this_scale = Scale(self, label=label, orient=HORIZONTAL, from_=getattr(self, 'min_' + sca), to=getattr(self, 'max_' + sca), resolution=SCALES[sca]['res']) self.this_scale.set(SCALES[sca]['start']) self.this_scale.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) self.this_scale.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) if 'pos' in list(SCALES[sca].keys()): pos = SCALES[sca]['pos'] col = pos['c'] row = pos['r'] else: row = counter col = 1 counter += 1 self.this_scale.grid(column=col, row=row, sticky=E + W) self.this_scale.ref = sca self.this_scale.bind("<ButtonRelease>", self.scale_handler) def scale_handler(self, event): self.send({event.widget.ref: event.widget.get()}) self.gui_logger.info("handling scale: {0}, with new value: {1}".format( event.widget.ref, event.widget.get())) def trigger_waveform_handler(self, event): self.send({event.widget.ref: True}) # print event.widget.ref, "- triggering wavetable" def send_scale(self): do = {'scale': self.scale.get()} self.send(do) def send(self, msg): self.gui_logger.info("sending: {0}".format(msg)) self.send_sock.sendto(json.dumps(msg), (remote_host, send_port)) def create_ranges(self): counter = 0 for ran in RANGES: setattr(self, 'min_' + ran, RANGES[ran]['min']) setattr(self, 'max_' + ran, RANGES[ran]['max']) self.this_min_scale = Scale(self, label='min ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_max_scale = Scale(self, label='max ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_min_scale.set(RANGES[ran]['min_start']) self.this_max_scale.set(RANGES[ran]['max_start']) self.this_min_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_min_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_max_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_max_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_min_scale.grid(column=2, row=counter, sticky=E + W) self.this_max_scale.grid(column=2, row=counter + 1, sticky=E + W) self.this_min_scale.ref = 'min_' + ran self.this_max_scale.ref = 'max_' + ran self.this_min_scale.bind("<ButtonRelease>", self.scale_handler) self.this_max_scale.bind("<ButtonRelease>", self.scale_handler) counter += 2 def socket_read_handler(self, file, mask): data_object = json.loads(file.recv(1024)) do = list(data_object.items())[0] self.set_value(do[0], do[1])
class SplitsView(View): """ """ def _create_widgets(self): self.title_label = Label(self, text="--") self.split_button = Button(self, text="Split", command=self.controller.split_callback) self.skip_split_button = Button( self, text="Skip Split", command=self.controller.skip_split_callback) self.name_header = Label(self, text="Name".ljust(20)) self.difference_header = Label(self, text="| Diff".ljust(8)) self.best_header = Label(self, text="| Best Run".ljust(11)) self.segment_area = Frame(self) self.segments = [] self.open_button = Button(self, text="Open Split", command=self.controller.sl_component.load) self.new_button = Button(self, text="New Split", command=self.controller.new_callback) def _arrange_widgets(self): self.title_label.grid(row=0, column=0, columnspan=3) self.split_button.grid(row=1, column=0, columnspan=2) self.skip_split_button.grid(row=1, column=2, columnspan=2) self.name_header.grid(row=2, column=0) self.difference_header.grid(row=2, column=1) self.best_header.grid(row=2, column=2) self.segment_area.grid(row=3, column=0, columnspan=3) def update(self, title, segments_data): self.title_label["text"] = title for widget in self.segment_area.winfo_children(): widget.destroy() self.segments = [ self.SegmentFrame(self.segment_area, segment) for segment in segments_data ] for segment in self.segments: segment.pack() def show_open_splitfile_buttons(self): if not self.open_button.winfo_ismapped(): self.open_button.grid(row=4, column=0) self.new_button.grid(row=4, column=2) def hide_open_splitfile_buttons(self): if self.open_button.winfo_ismapped(): self.open_button.grid_forget() self.new_button.grid_forget() class SegmentFrame(Frame): """ """ def __init__(self, root, segment_data): super().__init__(root) self._create(segment_data) self._arrange() def _create(self, segment_data): self.label = Label(self, text=segment_data.label.ljust(20)) self.best_time_label = Label(self, text=Stopwatch.ms_to_time_str( segment_data.best_time).ljust(11)) self.difference_label = Label(self, text="--".ljust(8)) def _arrange(self): self.label.grid(row=0, column=0) self.difference_label.grid(row=0, column=1) self.best_time_label.grid(row=0, column=2) def update_segment_time(self, diff): self.difference_label["text"] = diff.ljust(8)
def clear_frame(frame: tkinter.Frame): """ clears the contents of a given frame """ for widget in frame.winfo_children(): widget.destroy()
class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.tileList = [] self.currentNumOfQueens = None self.initUI() # Hàm này có nhiệm vụ khởi tạo các widget chứa bên trong App def initUI(self): # Cấu hình layout cho cửa sổ này # Tham số side = "left" cho biết layout sẽ cố định bên trái, fill = "both" thì kích thước của layout # sẽ lắp đầy 2 bên, expand = True cho phép mở rộng self.pack(side="left", fill="both", expand=True) # Tạo một frame, frame này sẽ chứa MAP đặt n Queens # Tham số self cho biết widget sẽ chứa nó, width là chiều rộng, height là chiều cao self.map = Frame(self, width=600, height=600) self.map.pack(side="left", fill="both", expand=True) # Lấy ra thông tin chiều dài và rộng tính theo pixel của MAP, ta trừ đi kích thước 20 # để cách đều ra 2 bên self.map.update() self.x = int(self.map.winfo_width() - 20) self.y = int(self.map.winfo_width() - 20) # Tạo frame thứ 2, frame này sẽ chưa textbox cho ta nhập số n queens, số lần lặp của thuật toán self.frameWidget = Frame(self, width=150) self.frameWidget.pack(side="left", fill="both", expand=True) self.lbNumOfQueens = Label(self.frameWidget, text="Num of Queens") # Tham số pady = 25, để label cách đều về 2 phía theo trục y 25 px self.lbNumOfQueens.pack(pady=25) # Tạo textbox để nhập số quân hậu cần đặt self.entryNumOfQueens = Entry(self.frameWidget) self.entryNumOfQueens.pack() # Tạo button để chạy giải quyết thuậ toán # Tham số command = self.resolving để tạo sự kiện khi nhấn button này self.btnResolving = Button(self.frameWidget, text="Min-conflict algorithm", command=self.resolving) self.btnResolving.pack(pady=50) # Tạo label để hiển thị thời gian chạy của thuật toán self.lbTime = Label(self.frameWidget, text="0.00s") # Tham số pady = 25, để label cách đều về 2 phía theo trục y 25 px self.lbTime.pack(pady=25) # Hàm tạo bàn cờ numOfQueens x numOfQueens def createMap(self, numOfQueens): for widget in self.map.winfo_children(): widget.destroy() self.map.update() self.tileList.clear() # Ta lấy chiều dài và rộng của 1 ô theo pixel w = int(self.x / numOfQueens) h = int(self.y / numOfQueens) # Cấu hình cột hàng cho MAP for k in range(numOfQueens): self.map.columnconfigure(k, pad=2) self.map.rowconfigure(k, pad=2) # Tạo các label đại diện cho một ô trong MAP for i in range(numOfQueens): self.tileList.append([]) for j in range(numOfQueens): # Tạo một ảnh pixel, để khi ta set width và height cho Label thì nó sẽ lấy theo pixel # chứ không phải mm #Ta chỉnh các background xen kẽ nhau bg = "white" if (i + j) % 2 == 0: bg = "gray" pixelVirtual = PhotoImage(width=1, height=1) lb = Label(self.map, image=pixelVirtual, width=w, height=h, bg=bg, padx=2, pady=2) lb.grid(row=i, column=j) # Đặt nó vào hàng i, cột j của MAP self.tileList[i].append(lb) ''' Hàm tìm ra solution và đặt các con hậu lên MAP ''' def resolving(self): # Khi thuật toán bắt đầu tìm kiếm, ta tiến hành khóa button này lại, tránh trường hợp # click nhiều lần từ người dùng self.btnResolving["state"] = "disabled" numOfQueens = int(self.entryNumOfQueens.get()) # Ta kiểm tra xem số hậu được nhập từ người dùng là lần đầu tiên hay là số hậu mới, hay # là chỉ tìm kiếm cách đặt hậu mới # self.currentNumOfQueens = None thì ban đầu ta sẽ tạo ra một cái map mới hoặc # số hậu nhận từ người dùng ở lần tiếp theo khác với số hậu nhập từ người dùng ở lần trước đó # thì ta cũng tạo ra map mới. Ngược lại thì ta không cần tạo map mới mà chỉ cần đặt lại vị trí # hình ảnh quân hậu if self.currentNumOfQueens == None or self.currentNumOfQueens != numOfQueens: self.currentNumOfQueens = numOfQueens self.isNewMap = True else: self.isNewMap = False solution, ti = getResults(numOfQueens) if self.isNewMap == True: self.createMap(numOfQueens) self.setTheQueens(numOfQueens, solution) self.lbTime.configure(text=str(ti) + "s") # Thuật toán chạy xong, các con hậu được đặt, ta mở khóa button cho người dùng tìm kiếm # các cách đặt khác self.btnResolving["state"] = "active" ''' Hàm đặt các quân hậu dựa vào solution tìm được ''' def setTheQueens(self, numOfQueens, solution): for i in range(numOfQueens): for j in range(numOfQueens): self.tileList[i][j].configure(image=None) self.tileList[i][j].image = None for column, row in solution.items(): image = ImageTk.PhotoImage(Image.open(os.getcwd() + "/queen.png")) self.tileList[row][column].configure(image=image) self.tileList[row][column].image = image
def init(): # Generic tkinter setup window = tk.Tk() window.configure(bg=Gray) hexCanvas = Canvas( window, width=360, height=360, bg=Gray, bd=0, highlightthickness=0, ) honeyFrame = Frame(window, width=800, height=200, bg=Gray) wordFrame = Frame(window, width=500, height=360, bg=Gray) spacingFix = tk.Label(wordFrame, text="", bg=Gray) spacingFix.grid() #originalWordList = copy.copy(currentWordList) ### Create Game object ### global game game = myGame(window, hexCanvas, honeyFrame, wordFrame) game.checkUser() game.window.title("Welcome to Spelling Bee!") game.window.option_add('*tearOff', False) game.window.geometry(str(int(13 * WIDTH / 16)) + 'x' + str(HEIGHT)) + "-5+1200" # THIS DOESN'T WORK WTF center(game.window) game.WIDTH = WIDTH game.HEIGHT = HEIGHT introText = "Welcome back " + game.userInfo.name + "! Get ready for a Spelling Bee! Make words from the available letters, but all words must use the center letter and be at least 3 characters long. If you would like to play as somebody else, enter your name below, and choose a difficulty setting. " # add an instructions label instructions = tk.Label(game.window, text=introText, bg=Gray, font=('Helvetica', 20), wraplength=600, padx=100, pady=20) instructions.grid() # add a text entry box for entering name and a button next to it def inStart(event): event.widget.configure(bg=Lemon) def leaveStart(event): event.widget.configure(bg='white') entryFrame = Frame(game.window, bg=Gray) global nameBox nameBox = tk.Entry(entryFrame, width=10, justify=tk.CENTER, font=(game.FONT_SELECT, '36')) startButton = tk.Label(entryFrame, text="Start", fg=Gunmetal, bg='white', font=(game.FONT_SELECT, '34'), relief='groove', width=4, borderwidth=4) nameBox.grid(row=0, column=0) startButton.grid(row=0, column=1, padx=15) # run the 'startGame' function when the enter key is pressed game.window.bind('<Return>', startGame) startButton.bind("<Button-1>", startGame) startButton.bind("<Enter>", inStart) startButton.bind("<Leave>", leaveStart) nameBox.focus_set() # set focus on the entry box entryFrame.grid() # Change the picture when the user selects a game mode def setPicture(): if game.userInfo.difficulty == 'Bee': diff = tk.PhotoImage(file='data/big_bee.gif') elif game.userInfo.difficulty == 'Wasp': diff = tk.PhotoImage(file='data/big_wasp.gif') else: diff = tk.PhotoImage(file='data/big_hornet.gif') game.difficultyPic = diff game.difficultyLabel.configure(image=game.difficultyPic) # Adjust the button appearances, save selection in the game object, and call setPicture() def difficultySelect(event): buttonType = event.widget.cget("text") game.userInfo.difficulty = buttonType parent = event.widget.winfo_parent() parentFrame = event.widget._nametowidget(parent) for child in parentFrame.winfo_children(): child.configure(relief='raised') event.widget.configure(relief='sunken') setPicture() # Initialize and grid buttons in their frame buttonFrame = Frame(game.window, bg=Gray) easyButton = tk.Label(buttonFrame, text='Bee', bg=LeafGreen, fg=Gunmetal, font=(game.FONT_SELECT, '20'), relief='raised', padx=5, borderwidth=4) easyButton.grid(row=0, column=0, padx=15) mediumButton = tk.Label(buttonFrame, text='Wasp', bg=SkyBlue, fg=Gunmetal, font=(game.FONT_SELECT, '20'), relief='raised', padx=5, borderwidth=4) mediumButton.grid(row=0, column=1, padx=15) hardButton = tk.Label(buttonFrame, text='Hornet', bg=DullRed, fg=Gunmetal, font=(game.FONT_SELECT, '20'), relief='raised', padx=5, borderwidth=4) hardButton.grid(row=0, column=2, padx=15) for child in buttonFrame.winfo_children(): if child.cget("text") == game.userInfo.difficulty: child.configure(relief='sunken') buttonFrame.grid(pady=(100, 35)) easyButton.bind("<Button-1>", difficultySelect) mediumButton.bind("<Button-1>", difficultySelect) hardButton.bind("<Button-1>", difficultySelect) # Grid the difficulty picture (last) if game.userInfo.difficulty == 'Bee': diff = tk.PhotoImage(file='data/big_bee.gif') elif game.userInfo.difficulty == 'Wasp': diff = tk.PhotoImage(file='data/big_wasp.gif') else: diff = tk.PhotoImage(file='data/big_hornet.gif') game.difficultyPic = diff game.difficultyLabel = tk.Label(game.window, image=game.difficultyPic, bg=Gray) game.difficultyLabel.grid() #Start the GUI window.mainloop()
class InstanceEditor(Toplevel): def __init__(self): Toplevel.__init__(self) self.focus_set() self.grab_set() self.result = None self.module_data = None self.mod_applis = None self.title(ugettext("Instance editor")) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.ntbk = ttk.Notebook(self) self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W)) self.frm_general = Frame(self.ntbk, width=350, height=150) self.frm_general.grid_columnconfigure(0, weight=0) self.frm_general.grid_columnconfigure(1, weight=1) self._general_tabs() self.ntbk.add(self.frm_general, text=ugettext('General')) self.frm_database = Frame(self.ntbk, width=350, height=150) self.frm_database.grid_columnconfigure(0, weight=0) self.frm_database.grid_columnconfigure(1, weight=1) self._database_tabs() self.ntbk.add(self.frm_database, text=ugettext('Database')) btnframe = Frame(self, bd=1) btnframe.grid(row=1, column=0, columnspan=1) Button(btnframe, text=ugettext("OK"), width=10, command=self.apply).grid( row=0, column=0, sticky=(N, S, E)) Button(btnframe, text=ugettext("Cancel"), width=10, command=self.destroy).grid( row=0, column=1, sticky=(N, S, W)) def _database_tabs(self): Label(self.frm_database, text=ugettext("Type")).grid( row=0, column=0, sticky=(N, W), padx=5, pady=3) self.typedb = ttk.Combobox( self.frm_database, textvariable=StringVar(), state=READLONY) self.typedb.bind("<<ComboboxSelected>>", self.typedb_selection) self.typedb.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("Name")).grid( row=1, column=0, sticky=(N, W), padx=5, pady=3) self.namedb = Entry(self.frm_database) self.namedb.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("User")).grid( row=2, column=0, sticky=(N, W), padx=5, pady=3) self.userdb = Entry(self.frm_database) self.userdb.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_database, text=ugettext("Password")).grid( row=3, column=0, sticky=(N, W), padx=5, pady=3) self.pwddb = Entry(self.frm_database) self.pwddb.grid(row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3) def _general_tabs(self): Label(self.frm_general, text=ugettext("Name")).grid( row=0, column=0, sticky=(N, W), padx=5, pady=3) self.name = Entry(self.frm_general) self.name.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Appli")).grid( row=1, column=0, sticky=(N, W), padx=5, pady=3) self.applis = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.applis.bind("<<ComboboxSelected>>", self.appli_selection) self.applis.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Modules")).grid( row=2, column=0, sticky=(N, W), padx=5, pady=3) self.modules = Listbox(self.frm_general, selectmode=EXTENDED) self.modules.configure(exportselection=False) self.modules.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Language")).grid( row=3, column=0, sticky=(N, W), padx=5, pady=3) self.language = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.language.grid( row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("CORE-connectmode") ).grid(row=4, column=0, sticky=(N, W), padx=5, pady=3) self.mode = ttk.Combobox( self.frm_general, textvariable=StringVar(), state=READLONY) self.mode.bind("<<ComboboxSelected>>", self.mode_selection) self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3) Label(self.frm_general, text=ugettext("Password")).grid( row=5, column=0, sticky=(N, W), padx=5, pady=3) self.password = Entry(self.frm_general, show="*") self.password.grid( row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3) def typedb_selection(self, event): visible = list(self.typedb[VALUES]).index(self.typedb.get()) != 0 for child_cmp in self.frm_database.winfo_children()[2:]: if visible: child_cmp.config(state=NORMAL) else: child_cmp.config(state=DISABLED) def appli_selection(self, event): if self.applis.get() != '': appli_id = list(self.applis[VALUES]).index(self.applis.get()) luct_glo = LucteriosGlobal() current_inst_names = luct_glo.listing() appli_root_name = self.mod_applis[appli_id][0].split('.')[-1] default_name_idx = 1 while appli_root_name + six.text_type(default_name_idx) in current_inst_names: default_name_idx += 1 self.name.delete(0, END) self.name.insert( 0, appli_root_name + six.text_type(default_name_idx)) mod_depended = self.mod_applis[appli_id][2] self.modules.select_clear(0, self.modules.size()) for mod_idx in range(len(self.module_data)): current_mod = self.module_data[mod_idx] if current_mod in mod_depended: self.modules.selection_set(mod_idx) def mode_selection(self, event): visible = list(self.mode[VALUES]).index(self.mode.get()) != 2 for child_cmp in self.frm_general.winfo_children()[-2:]: if visible: child_cmp.config(state=NORMAL) else: child_cmp.config(state=DISABLED) def apply(self): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang if self.name.get() == '': showerror(ugettext("Instance editor"), ugettext("Name empty!")) return if self.applis.get() == '': showerror(ugettext("Instance editor"), ugettext("No application!")) return db_param = "%s:name=%s,user=%s,password=%s" % ( self.typedb.get(), self.namedb.get(), self.userdb.get(), self.pwddb.get()) security = "MODE=%s" % list( self.mode[VALUES]).index(self.mode.get()) if self.password.get() != '': security += ",PASSWORD=%s" % self.password.get() module_list = [ self.module_data[int(item)] for item in self.modules.curselection()] appli_id = list(self.applis[VALUES]).index(self.applis.get()) current_lang = get_locale_lang() for lang in DEFAULT_LANGUAGES: if lang[1] == self.language.get(): current_lang = lang[0] self.result = (self.name.get(), self.mod_applis[appli_id][ 0], ",".join(module_list), security, db_param, current_lang) self.destroy() def _load_current_data(self, instance_name): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang lct_inst = LucteriosInstance(instance_name) lct_inst.read() self.name.delete(0, END) self.name.insert(0, lct_inst.name) self.name.config(state=DISABLED) applis_id = 0 for appli_iter in range(len(self.mod_applis)): if self.mod_applis[appli_iter][0] == lct_inst.appli_name: applis_id = appli_iter break self.applis.current(applis_id) if lct_inst.extra['']['mode'] is not None: self.mode.current(lct_inst.extra['']['mode'][0]) else: self.mode.current(2) self.mode_selection(None) typedb_index = 0 for typedb_idx in range(len(self.typedb[VALUES])): if self.typedb[VALUES][typedb_idx].lower() == lct_inst.database[0].lower(): typedb_index = typedb_idx break self.typedb.current(typedb_index) self.typedb.config(state=DISABLED) self.typedb_selection(None) self.namedb.delete(0, END) if 'name' in lct_inst.database[1].keys(): self.namedb.insert(0, lct_inst.database[1]['name']) self.userdb.delete(0, END) if 'user' in lct_inst.database[1].keys(): self.userdb.insert(0, lct_inst.database[1]['user']) self.pwddb.delete(0, END) if 'password' in lct_inst.database[1].keys(): self.pwddb.insert(0, lct_inst.database[1]['password']) self.modules.select_clear(0, self.modules.size()) for mod_idx in range(len(self.module_data)): current_mod = self.module_data[mod_idx] if current_mod in lct_inst.modules: self.modules.select_set(mod_idx) current_lang = get_locale_lang() if 'LANGUAGE_CODE' in lct_inst.extra.keys(): current_lang = lct_inst.extra['LANGUAGE_CODE'] for lang in DEFAULT_LANGUAGES: if lang[0] == current_lang: self.language.current(self.language[VALUES].index(lang[1])) def execute(self, instance_name=None): from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang self.mode[VALUES] = [ugettext( "CORE-connectmode.0"), ugettext("CORE-connectmode.1"), ugettext("CORE-connectmode.2")] self.language[VALUES] = [lang[1] for lang in DEFAULT_LANGUAGES] self.typedb[VALUES] = ["SQLite", "MySQL", "PostgreSQL"] lct_glob = LucteriosGlobal() _, self.mod_applis, mod_modules = lct_glob.installed() self.mod_applis.sort(key=lambda item: get_module_title(item[0])) self.modules.delete(0, END) self.module_data = [] module_list = [] for mod_module_item in mod_modules: module_list.append( (get_module_title(mod_module_item[0]), mod_module_item[0])) module_list.sort(key=lambda module: module[0]) for module_title, module_name in module_list: self.modules.insert(END, module_title) self.module_data.append(module_name) appli_list = [] for mod_appli_item in self.mod_applis: appli_list.append(get_module_title(mod_appli_item[0])) self.applis[VALUES] = appli_list if instance_name is not None: self._load_current_data(instance_name) else: self.typedb.current(0) self.mode.current(2) if len(appli_list) > 0: self.applis.current(0) self.appli_selection(None) self.mode_selection(None) self.typedb_selection(None) for lang in DEFAULT_LANGUAGES: if lang[0] == get_locale_lang(): self.language.current(self.language[VALUES].index(lang[1])) center(self)