Ejemplo n.º 1
0
    def createWidgets(self):
        win = Toplevel(self)
        self.win = win
        geometry = self.config.get('geometry', fallback='400x80')
        win.geometry(geometry)
        win.protocol("WM_DELETE_WINDOW", self.on_closing)
        win.grid_columnconfigure(0, weight=0)
        win.grid_columnconfigure(1, weight=1)
        win.title("Pick a Game")
        Label(win, text="Game: ").grid()
        try:
            self.pickgamecombo = ttk.Combobox(win,
                                              values=[
                                                  "{} ({}: {})".format(
                                                      g.note.replace('"', ''),
                                                      g.identifier_plugin,
                                                      g.identifier_data)
                                                  for g in self.pick_games_list
                                              ])
            self.pickgamecombo.grid(row=0, column=1, sticky=E + W)
        except Exception:
            import pprint
            logger.exception("Failed to create pickgamecombo. Games:\n%s",
                             pprint.pformat(self.pick_games_list))
            Label(win, text="Failed to create pickgamecombo.").\
                grid(row=0, column=1, sticky=E+W)

        Button(win, text="Add Game",
               command=self.do_pickgame).grid(row=1, columnspan=2)
        Label(win, text="To add a game manually, leave the box empty.").grid(
            row=2, columnspan=2)
Ejemplo n.º 2
0
    def createWidgets(self):
        win = Toplevel(self)
        self.win = win
        geometry = self.config.get('geometry', fallback='400x120')
        win.geometry(geometry)
        win.protocol("WM_DELETE_WINDOW", self.on_closing)
        win.grid_columnconfigure(0, weight=0)
        win.grid_columnconfigure(1, weight=1)
        win.title("Add Time")

        self.games = [(g.id, g.name)
                      for g in Session.query(App).order_by(App.name)]
        self.gamecombo = SearchableCombobox(win,
                                            values=[g[1] for g in self.games])

        Label(win, text="Game: ").grid()
        self.gamecombo.grid(row=0, column=1, sticky=E + W)

        Label(win, text="Added seconds: ").grid()
        Entry(win, textvariable=self.seconds_entry).grid(row=1,
                                                         column=1,
                                                         sticky=E + W)

        Button(win, text="Add Time", command=self.add_time).grid(row=2,
                                                                 columnspan=2)
    def create_widgets(self):
        '''Create basic 3 row x 3 col search (find) dialog.

        Other dialogs override subsidiary create_x methods as needed.
        Replace and Find-in-Files add another entry row.
        '''
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        self.top = top
        self.frame = Frame(top, padding="5px")
        self.frame.grid(sticky="nwes")
        top.grid_columnconfigure(0, weight=100)
        top.grid_rowconfigure(0, weight=100)

        self.row = 0
        self.frame.grid_columnconfigure(0, pad=2, weight=0)
        self.frame.grid_columnconfigure(1, pad=2, minsize=100, weight=100)

        self.create_entries()  # row 0 (and maybe 1), cols 0, 1
        self.create_option_buttons()  # next row, cols 0, 1
        self.create_other_buttons()  # next row, cols 0, 1
        self.create_command_buttons()  # col 2, all rows
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
	def printFiles(self):

		for pdf in self.PDFs:
			self.jobCounter = ghostscript("\"T:\RELEASED_FILES\CURRENT_PDF\\"+pdf.replace("\"","")+"\"", self.jobCounter, self.selectedPrinter.get(), self.selectedPaper.get(),self.POPENFile)
			#print (jobCounter)

		if self.print_wrong_revision_var.get():
			for pdf in self.wrongRevsion:
				self.jobCounter = ghostscript("\"T:\RELEASED_FILES\CURRENT_PDF\\"+pdf.replace("\"","")+"\"", self.jobCounter, self.selectedPrinter.get(), self.selectedPaper.get(),self.POPENFile)


		#os.remove(self.POPENFile)
		posx  = 500
		posy  = 400
		sizex = 500
		sizey = 100
		top = Toplevel()
		top.title("Done")
		top.grid_rowconfigure(0,weigh=1)
		top.grid_columnconfigure(0, weight=1)
		top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
		msg = Message(top, text="Sent all files to printer.\nPlease wait for the printer to finish", width=200, pady=10)
		msg.grid(row=0, column=0, columnspan=4)
		top.focus_force()
		self.current_window = top
		if self.runningInFrozen:
			top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico")
		else:
			top.iconbitmap("emblem_print.ico")
		top.bind("<FocusOut>", self.Alarm)
		button = Button(top,text="Ok", command=top.quit)
		button.grid(row=1, column=0)
Ejemplo n.º 6
0
 def open_pop(self, hook_remove, hook_add, hook_apply):
     '''Manage bookmark sources: Major dialogue'''
     dprint(3, "\nTkMemobook::open_pop:: ")
     manager = Toplevel(self.root)
     manager_list = ListboxHV(manager, selectmode="multiple")
     manager_items = self.ctrl["db"]["scan"]
     if isinstance(manager_items, str):
         manager_items = [ manager_items ]
     else:
         manager_items = list(manager_items)
     manager_items.sort()
     for item in manager_items:
         manager_list.insert(END, item)
     manager_list.grid_columnconfigure(0, weight=1)
     manager_list.grid_rowconfigure(0, weight=1)
     manager_list.grid(sticky="nswe")
     buttons = Frame(manager)
     rembutt = Button(buttons,
                      text="Remove",
                      command=lambda: hook_remove(manager_list, manager_items) )
     addbutt = Button(buttons,
                      text="Add Other...",
                      command=lambda: hook_add(manager, manager_list, manager_items) )
     appbutt = Button(buttons,
                      text="Apply",
                      command=lambda: self.__get_busy_with(None, hook_apply, manager, manager_items) )
     rembutt.grid(row=1, column=0)
     addbutt.grid(row=1, column=1)
     appbutt.grid(row=1, column=2)
     buttons.grid_columnconfigure(1, weight=1)
     buttons.grid_rowconfigure(1, weight=1)
     buttons.grid(stick="nswe")
     manager.grid_columnconfigure(0, weight=1)
     manager.grid_rowconfigure(0, weight=1)
Ejemplo n.º 7
0
    def information(self):
        ########################################################################
        #                  Information                                         #
        ########################################################################
        # Renvoie les spécialite offerte par l'école en fonction du choix de l'utilisateur

        window = Toplevel(self.root)
        window.resizable(True, True)
        vsb = Scrollbar(window, orient="vertical")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb = Scrollbar(window, orient="horizontal")
        hsb.grid(row=1, column=0, sticky="ew")
        ca = Canvas(window, yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        ca.grid(row=0, column=0, sticky="news")
        vsb.config(command=ca.yview)
        hsb.config(command=ca.xview)
        window.grid_rowconfigure(0, weight=1)
        window.grid_columnconfigure(0, weight=1)
        fr = Frame(ca)

        i=1
        for a in ["Nom","Admission","Region","Alternance","Specialite"]:
            Label(fr, text=a).grid(row=0, column=i)
            i+=2

        if self.choix["specialites"] == None:
            ListeSpe = list(self.specialites.get(0, "end"))
        else:
            ListeSpe = [
                self.specialites.get(i) for i in self.specialites.curselection()
            ]

        if self.choix["alternance"] == None:
            alternance = ["Oui", "Non"]

        else:
            alternance = [self.choix["alternance"][0]]

        ligne = 1
        for ecole in self.ecolesselect.values():
            if ecole["var"].get() == 1:
                for i in [value for (key,value) in self.ecolesselect.items() if value['nom']==ecole['nom'] and value["Spe"] in ListeSpe and value["Alternance"] in alternance ]:
                    j=1
                    for texte in [i["nom"],i["admission"],i["region"],i["Alternance"],i["Spe"]] :
                        a = Entry(fr,width=60)
                        a.insert(0,texte)
                        a.grid(row=ligne, column=j)
                        j+=2

                        a.config(state="disabled")
                        

                    ligne += 1

        ca.create_window(0, 0, window=fr)
        fr.update_idletasks()
        ca.config(scrollregion=ca.bbox("all"))
Ejemplo n.º 8
0
    def execute_debug(self, event = None):
        self.__sym_table_3d = None

        self.c = 0
        # create debug player
        window = Toplevel()
        window['bg'] = 'black'

        label_count = Label(window, text="Execute Now:", 
                            borderwidth=0, width=10, bg = "black", fg = "white")
        label_count.grid(row=0, column=0, sticky="nsew", padx=1, pady=1)

        label_last = Label(window, text="Executed Before:", 
                            borderwidth=0, width=10, bg = "black", fg = "white")
        label_last.grid(row=0, column=2, sticky="nsew", padx=1, pady=1)

        self.label_last_line = Label(window, text="Line: 1", 
                            borderwidth=0, width=10, bg = "black", fg = "white")
        self.label_last_line.grid(row=1, column=0, sticky="nsew", padx=1, pady=1)

        execute = Button(window, text='>',
                                   command=self.update_line_debugg)
        execute.grid(row=1, column=1, sticky="nsew", padx=1, pady=1)

        self.count = Label(window, text="Line: 0", 
                            borderwidth=0, width=10, bg = "black", fg = "white")
        self.count.grid(row=1, column=2, sticky="nsew", padx=1, pady=1)

        window.grid_columnconfigure(0, weight=1)
        window.grid_columnconfigure(1, weight=1)
        window.grid_columnconfigure(2, weight=1)
        window.resizable(width=True, height=False)


        # get all txt from current tab
        selectedTab = self.tabs.index("current")
        currentTextArea = self.tabs.winfo_children()[selectedTab+1].textarea
        input = currentTextArea.get('1.0','end-1c')

        # new singleton symbol table
        self.__sym_table = table()

        # define mode for syntax-tree know how to autoexecute
        self.__sym_table.setMode(0)

        # start lex and sintactic analysis
        ply_left = tenorC.parse()

        self.__ast  = ply_left(tenorC, input, self.__sym_table)

        # TODO sintax error recover
        if self.__ast != None:
            self.__ast.execute(self.__sym_table)
            self.codeGenerated = self.__ast.get3D()
Ejemplo n.º 9
0
def rest_submit():
    def record_voice():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            audio = r.listen(source,timeout=1,phrase_time_limit=10)
        try:
            text.insert(INSERT,r.recognize_google(audio))
        except sr.UnknownValueError:
            messagebox.showinfo("Error", "Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            messagebox.showinfo("Error", "Could not request results from Google Speech Recognition service; {0}".format(e))
    
    def main_action():
        restaurant_id=ip1.get().lower()
        if(restaurant_id not in rest_id_dict.keys() or ip2.get()=="" or text.get("1.0",END)==""):
            messagebox.showinfo("Error", "Invalid Restaurant ID or textbox left blank.")
        else:
            restaurant_name=rest_id_dict[restaurant_id]
            get_title=ip2.get()
            get_review=text.get("1.0",END)
            with open(r'newdata.csv', 'a', newline='') as csvfile:
                fieldnames = ['restaurant_id','name','title','review_text']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writerow({'restaurant_id':restaurant_id, 'name':restaurant_name,'title':get_title,'review_text':get_review})
            messagebox.showinfo("Success", "You review was successfully sent.")

    newwin = Toplevel(root)
    newwin.resizable(False, False)
    newwin.title("Submit a Review")
    newwin.geometry("310x389")
    newwin.grid_columnconfigure(0, weight=1, uniform="fred")
    newwin.grid_columnconfigure(1, weight=1, uniform="fred")
    C = Canvas(newwin, bg="blue", height=389, width=310)
    filename = PhotoImage(file = "bg.png")
    background_label = Label(newwin, image=filename)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    label1=Label(newwin,text="Enter Restaurant ID:",bg='#ffae93')
    label1.grid(column=0,row=0,pady=(120,10))
    ip1=Entry(newwin,width=20)
    ip1.grid(column=1,row=0,pady=(120,10),sticky=W)
    label2=Label(newwin,text="Enter Review Title:",bg='#ffae93')
    label2.grid(column=0,row=1,pady=(0,10))
    ip2=Entry(newwin,width=20)
    ip2.grid(column=1,row=1,pady=(0,10),sticky=W)
    text=Text(newwin,width=40,height=8)
    text.grid(columnspan=2,row=2,padx=(10,10),pady=(0,10))
    mic_on=PhotoImage(file="mic_on.png")
    record=Button(newwin,text="Record Voice",command=record_voice,image=mic_on)
    record.grid(column=0,row=3,pady=(0,10),padx=30,sticky=E)
    button=Button(newwin,text="Submit Review",command=main_action)
    button.grid(column=1,row=3,pady=(0,10),padx=5,sticky=W)
    C.grid()
    newwin.mainloop()
Ejemplo n.º 10
0
def add_btn_click_event(event, root, table):
    prompt = Toplevel()
    prompt.grid_columnconfigure(0, weight=1)
    prompt.resizable(0, 0)
    prompt.title(literals["add_url_prompt_title"])
    prompt_width = 400
    prompt_height = 100
    middle_x_pos = int(root.winfo_x() - prompt_width / 2 +
                       root.winfo_width() / 2)
    middle_y_pos = int(root.winfo_y() - prompt_height / 2 +
                       root.winfo_height() / 2)
    prompt.geometry("%sx%s+%s+%s" %
                    (prompt_width, prompt_height, middle_x_pos, middle_y_pos))
    load_prompt_frame(prompt, table)
Ejemplo n.º 11
0
	def checkSettingsBeforePrint(self):

		if self.selectedPrinter.get() != '' and self.PDFs != None :
			printingThread = threading.Thread(target=self.printFiles)
			printingThread.start()
		else:
			if self.selectedPrinter.get() == '':
				posx  = 500
				posy  = 400
				sizex = 500
				sizey = 100
				top = Toplevel()
				top.grid_rowconfigure(0,weigh=1)
				top.grid_columnconfigure(0, weight=1)
				top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
				top.title("Printer not set")
				msg = Message(top, text="Set the default printer in\nPrinter Settings.",width=200, pady=10)
				msg.grid(row=0, column=0,columnspan=5)
				button = Button(top,text="Ok", command=top.destroy)
				button.grid(row=1, column=0)
				self.current_window = top
				if self.runningInFrozen:
					top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico")
				else:
					top.iconbitmap("emblem_print.ico")
				top.focus_force()
				top.bind("<FocusOut>", self.Alarm)
				return None
			elif self.PDFs == None:
				posx  = 500
				posy  = 400
				sizex = 500
				sizey = 100
				top = Toplevel()
				top.grid_rowconfigure(0,weigh=1)
				top.grid_columnconfigure(0, weight=1)
				top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
				top.title("No file loaded")
				msg = Message(top, text="Browse for a file before printing.",width=200, pady=10)
				msg.grid(row=0, column=0,columnspan=5)
				button = Button(top,text="Ok", command=top.destroy)
				button.grid(row=1, column=0)
				self.current_window = top
				if self.runningInFrozen:
					top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico")
				else:
					top.iconbitmap("emblem_print.ico")
				top.focus_force()
				top.bind("<FocusOut>", self.Alarm)
				return None
Ejemplo n.º 12
0
    def execute_debug(self, event=None):
        self.__sym_table = None
        self.c = 0
        # create debug player
        window = Toplevel()
        window['bg'] = 'black'

        label_count = Label(window,
                            text="Execute Now:",
                            borderwidth=0,
                            width=10,
                            bg="black",
                            fg="white")
        label_count.grid(row=0, column=0, sticky="nsew", padx=1, pady=1)

        label_last = Label(window,
                           text="Executed Before:",
                           borderwidth=0,
                           width=10,
                           bg="black",
                           fg="white")
        label_last.grid(row=0, column=2, sticky="nsew", padx=1, pady=1)

        self.label_last_line = Label(window,
                                     text="Line: 1",
                                     borderwidth=0,
                                     width=10,
                                     bg="black",
                                     fg="white")
        self.label_last_line.grid(row=1,
                                  column=0,
                                  sticky="nsew",
                                  padx=1,
                                  pady=1)

        execute = Button(window, text='>', command=self.update_line_debugg)
        execute.grid(row=1, column=1, sticky="nsew", padx=1, pady=1)

        self.count = Label(window,
                           text="Line: 0",
                           borderwidth=0,
                           width=10,
                           bg="black",
                           fg="white")
        self.count.grid(row=1, column=2, sticky="nsew", padx=1, pady=1)

        window.grid_columnconfigure(0, weight=1)
        window.grid_columnconfigure(1, weight=1)
        window.grid_columnconfigure(2, weight=1)
        window.resizable(width=True, height=False)
Ejemplo n.º 13
0
    def createWidgets(self):
        win = Toplevel(self)
        self.win = win
        geometry = self.config.get('geometry', fallback='400x160')
        win.geometry(geometry)
        win.grid_columnconfigure(0, weight=0)
        win.grid_columnconfigure(1, weight=1)
        win.title("Add Game")

        self.games = [(g.id, g.name)
                      for g in Session.query(App).order_by(App.name)]
        self.gamecombo = ttk.Combobox(win, values=[g[1] for g in self.games])
        if self.game:
            self.gamecombo.set(self.game)

        Label(win, text="Game: ").grid()
        self.gamecombo.grid(row=0, column=1, sticky=E + W)

        Label(win, text="Plugin: ").grid()
        Entry(win, textvariable=self.plugin_entry).grid(row=1,
                                                        column=1,
                                                        sticky=E + W)

        Label(win, text="Plugin Data: ").grid()
        Entry(win, textvariable=self.data_entry).grid(row=2,
                                                      column=1,
                                                      sticky=E + W)

        Label(win, text="Window Title: ").grid()
        Entry(win, textvariable=self.title_entry).grid(row=3,
                                                       column=1,
                                                       sticky=E + W)

        Label(win, text="Initial seconds: ").grid()
        Entry(win, textvariable=self.seconds_entry).grid(row=4,
                                                         column=1,
                                                         sticky=E + W)

        Label(win, text="Notes: ").grid()
        Entry(win, textvariable=self.notes_entry).grid(row=5,
                                                       column=1,
                                                       sticky=E + W)

        Button(win, text="Add Game", command=self.add_game).grid(row=6,
                                                                 columnspan=2)

        win.protocol("WM_DELETE_WINDOW", self.on_closing)
Ejemplo n.º 14
0
    def aboutsoft(self):
        root1 = Toplevel()
        wwwwidth = 1200
        wwheight = 400
        screenWidth = self.root.winfo_screenwidth()
        screenHeight = self.root.winfo_screenheight()

        left = (screenWidth / 2) - (wwwwidth / 2)
        top = (screenHeight / 2) - (wwheight / 2)

        root1.geometry('%dx%d+%d+%d' % (wwwwidth, wwheight, left, top))

        root1.grid_rowconfigure(0, weight=1)
        root1.grid_columnconfigure(0, weight=1)
        root1.title("About Sheet.wd")
        photo3 = PhotoImage(file="logo.gif")
        label3 = Label(root1, image=photo3)
        label4 = Label(
            root1,
            text="Code name sheet.wd is a simple text editor for web developers"
        )
        label5 = Label(
            root1,
            text="and simple users developed by Dhaval. Current version :- 0.1"
        )
        label6 = Label(
            root1,
            text=
            "sheet.wd is purely made for web development purpose supporting")
        label7 = Label(
            root1,
            text="simple txt files and HTML webpages.Although you can edit CSS"
        )
        label8 = Label(
            root1,
            text="files also,its proper functioning would be given later")
        label9 = Label(
            root1, text="For Suggestions or queries - [email protected]")
        label3.pack()
        label4.pack()
        label5.pack()
        label6.pack()
        label7.pack()
        label8.pack()
        label9.pack()
        root1.mainloop()
Ejemplo n.º 15
0
def get_top_level(frames, kwargs=None):
    master = kwargs.pop('master')
    title = kwargs.pop('title')
    width = kwargs.get('width')
    height = kwargs.get('height')
    frames_kwargs = None
    if 'frames_kwargs' in kwargs.keys():
        frames_kwargs = kwargs.pop('frames_kwargs')

    top_level = Toplevel(master=master, **kwargs)
    # Hide the toplevel
    top_level.withdraw()
    top_level.geometry(
        center_tk_window(window=top_level, height=width, width=height))

    # Create main container frame that will hold all other frames
    top_level.grid_rowconfigure(0, weight=1)
    top_level.grid_columnconfigure(0, weight=1)
    container = ttk.Frame(top_level)
    container.grid(column=0, row=0, sticky="nsew")
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)
    top_level.__setattr__('container', container)

    # Render all the other frames
    top_level_frames = {}
    for frame in frames:
        _frame = frame(parent=container,
                       controller=top_level,
                       kwargs=frames_kwargs[frame] if frames_kwargs else None)
        top_level_frames[frame] = _frame
        _frame.grid(row=0, column=0, sticky='nsew')

    top_level.__setattr__('frames', top_level_frames)

    # Define the title
    if title:
        top_level.title(title)

    # Raise the first frame
    top_level_frames[frames[0]].tkraise()

    # Make the toplevel visible again
    top_level.deiconify()
    return top_level
Ejemplo n.º 16
0
def run():
    """
    Esegue l'emulatore del pdp8
    """
    CD = pdp8()
    principale = Tk()
    principale.title("Pdp8 Emulator : Assembly Editor")
    emulatore = Toplevel()
    emulatore.title("Pdp8 Emulator")
    emulatore.geometry("1015x589")

    edit = Editor(principale, CD)

    scrollbar1 = AutoScrollbar(emulatore)
    scrollbar1.grid(row=0, column=1, sticky=N + S)
    scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL)
    scrollbar2.grid(row=1, column=0, sticky=E + W)

    finestra = Canvas(emulatore,
                      yscrollcommand=scrollbar1.set,
                      xscrollcommand=scrollbar2.set)
    finestra.grid(row=0, column=0, sticky=N + S + E + W)

    scrollbar1.config(command=finestra.yview)
    scrollbar2.config(command=finestra.xview)

    emulatore.grid_rowconfigure(0, weight=1)
    emulatore.grid_columnconfigure(0, weight=1)

    emul = Emulatore(finestra, edit, CD, emulatore)

    finestra.create_window(0, 0, anchor=NW, window=emul.master)

    emul.master.update_idletasks()

    finestra.config(scrollregion=finestra.bbox("all"))

    principale.protocol("WM_DELETE_WINDOW", edit.exit)
    emulatore.protocol("WM_DELETE_WINDOW", emul.exit)

    principale.mainloop()
    emulatore.mainloop()
Ejemplo n.º 17
0
    def createWidgets(self):
        win = Toplevel(self)
        self.win = win
        geometry = self.config.get('geometry', fallback='400x80')
        win.geometry(geometry)
        win.protocol("WM_DELETE_WINDOW", self.on_closing)
        win.grid_columnconfigure(0, weight=0)
        win.grid_columnconfigure(1, weight=1)
        win.title("Start Manual Session")

        self.games = [(g.id, g.name)
                      for g in Session.query(App).order_by(App.name)]
        self.gamecombo = SearchableCombobox(win,
                                            values=[g[1] for g in self.games])

        Label(win, text="Game: ").grid()
        self.gamecombo.grid(row=0, column=1, sticky=E + W)

        Button(win, text="Begin Session",
               command=self.begin_session).grid(row=5, columnspan=2)
Ejemplo n.º 18
0
def rest_cuisine():
    def main_action():
        name=cb.get().lower().strip()
        if(name.lower() not in cuisines_lower):
            messagebox.showinfo("Error", "The selected Cuisine is not available or the input is invalid.")
        else:
            text.delete('1.0', END)
            positive_reviews, negative_reviews, insufficient_data_to_classify,indexWiseScore = classifyReviewsOf(food_in_restaurants[name])
            most_popular_restaurant = recommendRestaurantForACuisine(indexWiseScore)
            text.insert(INSERT,'The Top '+name+' restaurants are:\n\n')
            if(len(most_popular_restaurant)<10):
                for i in range(len(most_popular_restaurant)):
                    resname=most_popular_restaurant[i].upper()
                    text.insert(INSERT,str(i+1)+'. '+ resname+'\n')
            else:
                for i in range(10):
                    resname=most_popular_restaurant[i].upper()
                    text.insert(INSERT,str(i+1)+'. '+ resname+'\n')

    newwin = Toplevel(root)
    newwin.resizable(False, False)
    newwin.grid_columnconfigure(0, weight=1, uniform="fred")
    newwin.grid_columnconfigure(1, weight=1, uniform="fred")
    newwin.title("Restaurant Cusines")
    newwin.geometry("310x389")
    C = Canvas(newwin, bg="blue", height=389, width=310)
    filename = PhotoImage(file = "cuisine_selector.png")
    background_label = Label(newwin, image=filename)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    l1=Label(newwin,text="Choose Your Cuisine:",bg='#ffae93')
    l1.grid(column=0, row=2,sticky=E,pady=50)
    cb=ttk.Combobox(newwin,values=cuisines,width=10)
    cb.grid(column=1, row=2,sticky=W,pady=50,padx=(20,0))
    cb.current(0)
    button1 =Button(newwin, text ="View Top Restaurants", command =main_action)
    button1.grid(columnspan=2,row=3,sticky=N)
    text = Text(newwin, width=40)
    text.grid(columnspan=2,row=4,pady=(10,10),padx=(10,10))
    C.grid()
    newwin.mainloop()
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
def instructions(fontsize):
    new = Toplevel()
    nw = 850
    nh = 600
    nws = new.winfo_screenwidth()  # width of the screen
    nhs = new.winfo_screenheight()  # height of the screen
    nx = (nws / 2) - (nw / 2)
    ny = (nhs / 2) - (nh / 2)
    new.geometry('%dx%d+%d+%d' % (nw, nh, nx, ny))
    new.title('U-Pack Instructions')
    new.configure(bg=vtmaroon, pady=5, padx=5)
    new.grid_propagate(False)
    new.grid_rowconfigure(0, weight=1)
    new.grid_columnconfigure(0, weight=1)
    txt = Text(new, relief='sunken', bd=4, fg='black', bg=vtsmoke)
    txt.config(pady=10, padx=40, font=('Times', fontsize), wrap='word')
    txt.grid(column=0, row=0, sticky='nsew')
    scroller = Scrollbar(new, orient='vertical', command=txt.yview)
    scroller.grid(column=1, row=0, sticky='nsew')
    txt['yscrollcommand'] = scroller.set
    OKa = Button(new, command=new.destroy, text='OK')
    OKa.configure(bg=hokiestone,
                  bd=4,
                  fg='black',
                  font=('Arial', fontsize),
                  highlightbackground=vtmaroon,
                  relief='raised')
    OKa.grid(column=0, row=1, sticky='nsew')
    instructtext = resource_path("UPackInstructions.txt")
    if path.exists(instructtext):
        with open(instructtext) as inst:
            quote = inst.read()
            txt.insert('end', quote)
    else:
        pathstring = str(instructtext)
        messagebox.showwarning(message="Cannot find the file:\n\'%s\'." %
                               pathstring)
Ejemplo n.º 21
0
    def bootstrap(self):
        root2 = Toplevel()
        width = 1024
        wwheight = 1024
        screenWidth = root2.winfo_screenwidth()
        screenHeight = root2.winfo_screenheight()

        left = (screenWidth / 2) - (width / 2)
        top = (screenHeight / 2) - (wwheight / 2)

        root2.geometry('%dx%d+%d+%d' % (width, wwheight, left, top))

        root2.grid_rowconfigure(0, weight=1)
        root2.grid_columnconfigure(0, weight=1)
        root2.title("Bootstrap infochart")
        photobt = PhotoImage(file="bootstrap.gif")
        labelbt = Label(root2, image=photobt)
        labelbt.grid(row=0, column=0)
        labelheading = Label(root2, text="Glyphs summary")
        labelheading.grid(row=1, column=0)
        glyphs1 = PhotoImage(file="glyphs1.gif")
        glyphs2 = PhotoImage(file="glyphs2.gif")
        glyphs3 = PhotoImage(file="glyphs4.gif")
        glyphs4 = PhotoImage(file="glyphs5.gif")
        glyphs5 = PhotoImage(file="glyphs6.gif")
        labelbt1 = Label(root2, image=glyphs1)
        labelbt2 = Label(root2, image=glyphs2)
        labelbt3 = Label(root2, image=glyphs3)
        labelbt4 = Label(root2, image=glyphs4)
        labelbt5 = Label(root2, image=glyphs5)
        labelbt1.grid(row=1)
        labelbt2.grid(row=2)
        labelbt3.grid(row=3)
        labelbt4.grid(row=4)
        labelbt5.grid(row=5)

        root2.mainloop()
Ejemplo n.º 22
0
class Atualizar():
    def __init__(self, tela, design, idioma, interface_idioma, icon):
        self.icon = icon
        self.interface_idioma = interface_idioma
        self.tp_atualizacao = None
        self.idioma = idioma
        self.design = design
        self.tela = tela

        # Destino dos Downloads e Backups
        data = str(datetime.now()).split('.')[0]
        data = data.replace(' ', '-')
        data = data.replace(':', '-')

        dest_download = os_path.join(os_getcwd(), 'AtualizarSafira')
        dest_backup = os_path.join(os_getcwd(), 'backups', data)

        # Instância de Upgrades
        self.up = Upgrade.Upgrade(dest_download, dest_backup)

    def verificar_versao(self, primeira_vez=False):
        """Verifica se existe uma versão mais recente disponível """
        try:
            baixada = VERSAO_ATUAL

            # Obter todas as versões
            dic_versoes = self.up.obter_informacoes_versao()

            if dic_versoes.get('erro'):
                print(dic_versoes['erro'])

                messagebox.showinfo(
                    "Erro ao buscar versões",
                    "Aconteceu um erro quando a Safira tentou buscar as versões disponíveis. Este foi o erro: {}"
                    .format(dic_versoes['erro']))
            else:
                # Obter ultima versão
                recente = max(dic_versoes.keys())
                if float(VERSAO_ATUAL["versao"]) < float(recente):

                    print('A versão {} disponível, deseja atualizar?'.format(
                        recente))
                    self.aviso_versao(baixada, recente)

                else:
                    # Não é necessário avisar que está atualizado
                    # Se a interface estiver iniciando
                    if not primeira_vez:
                        self.aviso_versao_atualizada(baixada)

        except Exception as erro:
            if not primeira_vez:
                messagebox.showinfo(
                    "ops",
                    self.interface_idioma["erro_generico"][self.idioma] +
                    str(erro))

    def aviso_versao(self, baixada, recente):
        """ Aviso, existe uma nova versão disponível """

        self.tp_atualizacao = Toplevel(
            self.tela, self.design.dic["aviso_versao_top_level"])
        self.tp_atualizacao.withdraw()
        self.tp_atualizacao.focus_force()
        self.tp_atualizacao.resizable(False, False)
        self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w,
                                    self.icon)
        self.tp_atualizacao.grid_columnconfigure(1, weight=1)
        self.tp_atualizacao.title(
            self.interface_idioma["titulo_aviso_atualizacao"][self.idioma])

        # Tentar remover a barra de rolagem
        #try:
        #    self.tp_atualizacao.wm_attributes('-type', 'splash')
        #except Exception as erro:
        #    print("Erro ao remover barra de titulos => ", erro)

        # Objetos da interface
        fr_atualizaca = Frame(self.tp_atualizacao)
        lb_versao_dev = Label(
            fr_atualizaca,
            text=self.interface_idioma["versao_nova_disponivel"][self.idioma])
        lb_versao_tex = Message(
            fr_atualizaca,
            text='{}'.format(self.interface_idioma["texto_update_disponivel"][
                self.idioma]).format(recente))
        fr_botoes = Frame(fr_atualizaca)

        bt_cancela = Button(
            fr_botoes,
            text=self.interface_idioma["versao_nao_quero"][self.idioma])
        bt_atualiza = Button(
            fr_botoes,
            text=self.interface_idioma["atualizar_agora"][self.idioma])

        # Configurações de desingn
        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"],
                             relief=FLAT)
        bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"],
                              relief=FLAT)

        # Eventos
        bt_atualiza.configure(
            command=lambda rec=recente: self.aviso_aguarde_instalando(rec))
        bt_cancela.configure(
            command=lambda event=None: self.tp_atualizacao.destroy())

        # Posicionamento de itens
        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)
        bt_cancela.grid(row=1, column=1)
        bt_atualiza.grid(row=1, column=2)

        # Posicionando a tela
        j_width = self.tp_atualizacao.winfo_reqwidth()
        j_height = self.tp_atualizacao.winfo_reqheight()
        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        self.tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.tp_atualizacao.deiconify()
        self.tp_atualizacao.update()

    def aviso_aguarde_instalando(self, recente):
        """ Realizando a atualização """

        if self.tp_atualizacao is not None:
            self.tp_atualizacao.destroy()

        self.tp_atualizacao = Toplevel(None)
        self.tp_atualizacao.withdraw()
        self.tp_atualizacao.focus_force()
        self.tp_atualizacao.resizable(False, False)
        self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w,
                                    self.icon)
        self.tp_atualizacao.configure(
            self.design.dic["aviso_versao_top_level"])
        self.tp_atualizacao.grid_columnconfigure(1, weight=1)
        self.tp_atualizacao.title('Atualizando.... Não feche a Safira!')

        #try:
        #    self.tp_atualizacao.wm_attributes('-type', 'splash')
        #except Exception as erro:
        #    print("Erro ao remover barra de titulos => ", erro)

        fr_atualizaca = Frame(self.tp_atualizacao)
        lb_versao_dev = Label(fr_atualizaca,
                              text='{:^30}'.format('Aguarde Atualizando!'))
        lb_versao_tex = Message(fr_atualizaca, text=' ' * 50, width=200)
        fr_botoes = Frame(fr_atualizaca)
        bt_atualiza = Button(fr_botoes)

        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"],
                              relief=FLAT)

        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)

        j_width = self.tp_atualizacao.winfo_reqwidth()
        j_height = self.tp_atualizacao.winfo_reqheight()
        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        self.tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.tp_atualizacao.deiconify()
        self.tp_atualizacao.update()

        th = Thread(
            target=lambda ver=recente, lb=lb_versao_tex, bt_at=bt_atualiza,
            lb_2=lb_versao_dev: self.aplica_versao(ver, lb, bt_at, lb_2))
        th.start()

    def log(self, label, texto):
        label['text'] = label['text'] + '\n{}'.format(texto)

    def aplica_versao(self, versao, lb_versao_tex, bt_atualiza, lb_versao_dev):
        """Baixa, faz o download e atualiza a Safira"""

        self.log(lb_versao_tex, "Baixando Versão {}".format(versao))

        atualizar = self.up.baixar_versao(versao)
        sucesso, msg, arquivo = atualizar

        # Baixou com sucesso
        if sucesso:
            self.log(lb_versao_tex, msg)
            self.log(lb_versao_tex,
                     "Extraindo: {}".format(self.up.dest_download))

            # Extraiu com sucesso
            sucesso, msg = self.up.extrair_versao(arquivo)
            if sucesso:
                self.log(lb_versao_tex, msg)
                self.log(lb_versao_tex, "Fazendo Backup")

                # Backup da versão atual
                sucesso_bkup, msg_bpk = self.up.fazer_backup_versao()
                if sucesso_bkup:
                    self.log(lb_versao_tex, msg_bpk)
                    self.log(lb_versao_tex, "Atualizando Versão")

                    # Atualizar a versão
                    sucesso_atualizar, msg_atualizar = self.atualizar_arquivos(
                        versao)
                    if sucesso_atualizar:
                        self.log(lb_versao_tex, msg_atualizar)
                        self.log(lb_versao_tex, "Sucesso!")

                        lb_versao_dev.configure(
                            text='{:^30}'.format('Atualizado com sucesso!'),
                            fg='green')
                        self.tp_atualizacao.title('Safira Atualizada!')

                    else:
                        self.log(lb_versao_tex, msg_atualizar)
                        self.log(lb_versao_tex, "\nRestaurando")

                        sucesso_restaurar, msg_restaurar = self.restaurar_versao(
                        )

                        self.log(lb_versao_tex, sucesso_restaurar[1])
                        lb_versao_dev.configure(text='{:^30}'.format(
                            sucesso_restaurar[1]),
                                                fg='orange')
                        self.tp_atualizacao.title('Safira Não Atualizada!')

                else:
                    self.log(lb_versao_tex, msg_bpk)

                    lb_versao_dev.configure(
                        text='{:^30}'.format('Erro ao fazer Backup'),
                        fg='orange')
                    self.tp_atualizacao.title('Safira Não Atualizada!')

            else:
                self.log(lb_versao_tex, msg)

                lb_versao_dev.configure(
                    text='{:^30}'.format('Erro ao Extrair os arquivos'),
                    fg='orange')
                self.tp_atualizacao.title('Safira Não Atualizada!')

        else:
            self.log(lb_versao_tex, msg)

            lb_versao_dev.configure(
                text='{:^30}'.format('Erro ao fazer Baixar Safira'),
                fg='orange')
            self.tp_atualizacao.title('Safira Não Atualizada!')

        bt_atualiza.configure(command=lambda event=None: self.fechar_tudo())

        bt_atualiza['text'] = 'Reinicie a Safira!'
        bt_atualiza.grid(row=1, column=2)

    def fechar_tudo(self):
        self.tela.destroy()

    def abrir_site(self, url):
        self.tp_atualizacao.destroy()

        th = Thread(target=lambda url=url: webbrowser_open(url))
        th.start()

    def aviso_versao_atualizada(self, baixada):

        self.tp_atualizacao = Toplevel(
            self.tela, self.design.dic["aviso_versao_tp_atualizada"])
        self.tp_atualizacao.withdraw()
        self.tp_atualizacao.focus_force()
        self.tp_atualizacao.resizable(False, False)
        self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w,
                                    self.icon)

        #try:
        #    self.tp_atualizacao.wm_attributes('-type', 'splash')
        #except Exception as erro:
        #    print("Erro ao remover barra de titulos => ", erro)

        self.tp_atualizacao.grid_columnconfigure(1, weight=1)

        j_width = self.tp_atualizacao.winfo_reqwidth()
        j_height = self.tp_atualizacao.winfo_reqheight()
        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        self.tp_atualizacao.title(
            self.interface_idioma["titulo_aviso_atualizado"][self.idioma])

        fr_atualizaca = Frame(self.tp_atualizacao)
        lb_versao_dev = Label(
            fr_atualizaca,
            text=self.interface_idioma["atualizado_versao_ultima"][
                self.idioma])
        lb_versao_tex = Message(
            fr_atualizaca,
            text='{}'.format(
                self.interface_idioma["texto_atualizado"][self.idioma]).format(
                    baixada["versao"]),
            relief=FLAT)
        fr_botoes = Frame(fr_atualizaca)
        bt_cancela = Button(
            fr_botoes,
            text=self.interface_idioma["texto_nao_quero"][self.idioma],
            relief=FLAT)
        bt_facebook = Button(
            fr_botoes,
            self.design.dic["aviso_versao_bt_facebook_atualizada"],
            text=self.interface_idioma["atualizado_facebook"][self.idioma],
            relief=FLAT)
        bt_blogger_ = Button(
            fr_botoes,
            self.design.dic["aviso_versao_bt_blog_atualizada"],
            text=self.interface_idioma["atualizado_blog"][self.idioma],
            relief=FLAT)

        # Configurações de desingn
        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"],
                             relief=FLAT)
        #bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"], relief=FLAT)

        bt_cancela.configure(
            command=lambda event=None: self.tp_atualizacao.destroy())
        bt_facebook.configure(command=lambda event=None: self.abrir_site(
            "https://www.facebook.com/safiralang/"))
        bt_blogger_.configure(command=lambda event=None: self.abrir_site(
            "https://safiralang.blogspot.com/"))

        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_botoes.grid_columnconfigure(3, weight=1)

        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)
        bt_cancela.grid(row=1, column=1)
        bt_facebook.grid(row=1, column=2)
        bt_blogger_.grid(row=1, column=3)

        self.tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.tp_atualizacao.update()
        self.tp_atualizacao.deiconify()
Ejemplo n.º 23
0
def openaboutwindow(main_root_title):
    global about_window

    # Defines the path to config.ini and opens it for reading/writing
    config_file = 'Runtime/config.ini'  # Creates (if doesn't exist) and defines location of config.ini
    config = ConfigParser()
    config.read(config_file)

    try:  # If "About" window is already opened, display a message, then close the "About" window
        if about_window.winfo_exists():
            messagebox.showinfo(
                title=f'"{about_window.wm_title()}" Info!',
                parent=about_window,
                message=
                f'"{about_window.wm_title()}" is already opened, closing window instead'
            )
            about_window.destroy()
            return
    except NameError:
        pass

    def about_exit_function():  # Exit function when hitting the 'X' button
        func_parser = ConfigParser()
        func_parser.read(config_file)
        if func_parser['save_window_locations'][
                'about'] == 'yes':  # If auto save position on close is checked
            try:
                if func_parser['save_window_locations'][
                        'about position'] != about_window.geometry():
                    func_parser.set('save_window_locations', 'about position',
                                    about_window.geometry())
                    with open(config_file, 'w') as configfile:
                        func_parser.write(configfile)
            except (Exception, ):
                pass

        about_window.destroy()  # Close window

    about_window = Toplevel()
    about_window.title('About')
    about_window.configure(background="#434547")
    if config['save_window_locations']['about position'] == '' or config[
            'save_window_locations']['about'] == 'no':
        window_height = 650
        window_width = 720
        screen_width = about_window.winfo_screenwidth()
        screen_height = about_window.winfo_screenheight()
        x_coordinate = int((screen_width / 2) - (window_width / 2))
        y_coordinate = int((screen_height / 2) - (window_height / 2))
        about_window.geometry("{}x{}+{}+{}".format(window_width, window_height,
                                                   x_coordinate, y_coordinate))
    elif config['save_window_locations']['about position'] != '' and config[
            'save_window_locations']['about'] == 'yes':
        about_window.geometry(
            config['save_window_locations']['about position'])
    about_window.resizable(False, False)
    about_window.protocol('WM_DELETE_WINDOW', about_exit_function)

    about_window.grid_columnconfigure(0, weight=1)

    detect_font = font.nametofont(
        "TkDefaultFont")  # Get default font value into Font object
    set_font = detect_font.actual().get("family")

    about_information_frame = LabelFrame(about_window,
                                         text=' About ',
                                         labelanchor="nw")
    about_information_frame.grid(column=0,
                                 row=0,
                                 columnspan=1,
                                 padx=5,
                                 pady=(0, 3),
                                 sticky=N + S + E + W)
    about_information_frame.configure(fg="#3498db",
                                      bg="#434547",
                                      bd=3,
                                      font=(set_font, 10, "bold"))
    about_information_frame.grid_rowconfigure(0, weight=1)
    about_information_frame.grid_columnconfigure(0, weight=1)

    about_window_text = Text(about_information_frame,
                             background="#434547",
                             foreground="white",
                             relief=FLAT,
                             height=10)
    about_window_text.pack()
    about_window_text.insert(INSERT, f"{main_root_title}\n")
    about_window_text.insert(INSERT, "\n")
    about_window_text.insert(
        INSERT,
        "Development: jlw4049\n\nContributors: BassThatHertz, aaronrausch")
    about_window_text.insert(INSERT, "\n\n")
    about_window_text.insert(
        INSERT,
        "Power audio encoding GUI, that mostly uses FFMPEG at the heart. \n")
    about_window_text.configure(state=DISABLED)

    about_information_frame = LabelFrame(about_window,
                                         text=' License ',
                                         labelanchor="nw")
    about_information_frame.grid(column=0,
                                 row=1,
                                 columnspan=1,
                                 padx=5,
                                 pady=(0, 3),
                                 sticky=N + S + E + W)
    about_information_frame.configure(fg="#3498db",
                                      bg="#434547",
                                      bd=3,
                                      font=(set_font, 10, "bold"))
    about_information_frame.grid_rowconfigure(0, weight=1)
    about_information_frame.grid_columnconfigure(0, weight=1)

    license_text = """
    Copyright (c) 2012-2022 Scott Chacon and others

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:
    
    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    """

    about_window_license = Text(about_information_frame,
                                background="#434547",
                                foreground="white",
                                relief=FLAT)
    about_window_license.pack(anchor='center')
    about_window_license.insert(INSERT, license_text)
    about_window_license.configure(state=DISABLED)
Ejemplo n.º 24
0
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()
Ejemplo n.º 25
0
def showTable(table):
    # use black background so it "peeks through" to
    # form grid lines
    window = Toplevel()
    window._widgets = []

    # setting headers
    row = 0
    current_row = []
    ins_tuple = ["IDENTIFIER", "TYPE", "SIZE", "VALUE", "SCOPE", "REFERENCE"]
    for column in range(6):
        label = Label(window,
                      text="%s" % ins_tuple[column],
                      borderwidth=0,
                      width=10,
                      bg="black",
                      fg="white")
        label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
        current_row.append(label)
    window._widgets.append(current_row)
    row += 1

    table = table.printTable()

    # setting content
    for key in list(table[0].keys()):
        #current_row = []
        ins = table[0][key]
        typ = ["INT", "FLOAT", "STRING", "STRUCT", "VOID"]
        is_label = ins.getType()
        is_pointer = ins.getValue()
        is_struct = ins.getSize()
        ref = ins.getRef()
        if type(is_label) == str:
            typ = "FUNCTION"
        elif type(is_pointer) == leaf:
            typ = "POINTER"
            is_pointer = is_pointer.getValue()
        else:
            if is_label == 3.1:
                is_label = 5
            elif is_label == 4.1:
                is_label = 4
            typ = typ[is_label - 1]
            if typ == "STRUCT":
                is_struct = len(is_pointer)
        ins_tuple = [
            ins.getID(), typ, is_struct, is_pointer,
            ins.getScope(), ref
        ]
        for column in range(6):
            label = Label(window,
                          text="%s" % ins_tuple[column],
                          borderwidth=0,
                          width=10,
                          bg="black",
                          fg="lightgrey")
            label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
            current_row.append(label)
        window._widgets.append(current_row)
        row += 1

    for column in range(6):
        window.grid_columnconfigure(column, weight=1)

    window.resizable(width=True, height=False)
Ejemplo n.º 26
0
class Idioma():
    def __init__(self, tela, design, idioma, interface_idioma, icon):
        self.icon = icon
        self.idioma = idioma
        self.interface_idioma = interface_idioma
        self.design = design
        self.tela = tela
        self.base = "imagens/"
        self.tp_interface_idioma = None
        self.bt_idioma = None
        self.lb1 = None
        self.dic_imgs = None

    def selecionar_idioma(self, dic_imgs):
        self.dic_imgs = dic_imgs
        self.tp_interface_idioma = Toplevel(self.tela,
                                            self.design.dic["idioma_tp"])
        self.tp_interface_idioma.withdraw()

        self.tp_interface_idioma.tk.call('wm', 'iconphoto',
                                         self.tp_interface_idioma._w,
                                         self.icon)
        self.tp_interface_idioma.grid_columnconfigure(1, weight=1)
        self.tp_interface_idioma.title('Escolha de Idioma')

        self.fr_top_idioma = Frame(self.tp_interface_idioma,
                                   self.design.dic["idioma_fr"])
        self.fr_top_idioma.grid_columnconfigure(1, weight=1)
        self.fr_top_idioma.grid(row=1, column=1, sticky=NSEW)

        self.lb1 = Label(
            self.fr_top_idioma,
            self.design.dic['idioma_lb'],
            text=self.interface_idioma["texto_atualizacao"][self.idioma])
        self.lb1.grid(row=1, column=1, sticky=NSEW)

        self.fr_idionas = Frame(self.tp_interface_idioma,
                                self.design.dic['idioma_fr2'])
        self.fr_idionas.grid(row=2, column=1)

        # Carregar as imagens
        self.imgs = []
        for k, v in self.dic_imgs.items():
            self.imgs.append(PhotoImage(file=self.base + v))

        # Carregar os botões
        x = 0
        self.lista_botoes = []
        for k, v in self.dic_imgs.items():

            if self.idioma == k:
                self.fr_bt = Frame(self.fr_idionas,
                                   self.design.dic['idioma_fr3'])
                self.bt_bt = Button(
                    self.fr_bt,
                    self.design.dic['idioma_bt'],
                    relief=GROOVE,
                    image=self.imgs[x],
                )
                self.lb_bt = Label(
                    self.fr_bt,
                    self.design.dic['idioma_lb2'],
                    relief=GROOVE,
                    text=k,
                )
            else:
                self.fr_bt = Frame(self.fr_idionas,
                                   self.design.dic['idioma_fr4'])
                self.bt_bt = Button(
                    self.fr_bt,
                    self.design.dic['idioma_bt2'],
                    relief=GROOVE,
                    image=self.imgs[x],
                )
                self.lb_bt = Label(self.fr_bt,
                                   self.design.dic['idioma_lb3'],
                                   relief=GROOVE,
                                   text=k)

            self.bt_bt[
                "command"] = lambda bt_bt=self.bt_bt, dic=self.dic_imgs: self.marcar_opcao_idioma(
                    bt_bt, dic)

            self.lista_botoes.append([self.fr_bt, self.bt_bt, self.lb_bt])

            self.fr_bt.grid(row=1, column=x)
            self.bt_bt.grid(row=1, column=x)
            self.lb_bt.grid(row=2, column=x)

            x += 1

        self.tp_interface_idioma.update()

        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        j_heigth = self.tp_interface_idioma.winfo_screenmmheight()
        j_width = self.tp_interface_idioma.winfo_screenmmwidth()

        self.tp_interface_idioma.geometry("+{}+{}".format(
            j_width, j_heigth, int(t_width / 2 - (j_width / 2)),
            int(t_heigth / 2 - (j_heigth / 2))))
        self.tp_interface_idioma.deiconify()

    def marcar_opcao_idioma(self, botao, dic_imgs):
        self.dic_imgs = dic_imgs
        self.tp_interface_idioma.withdraw()

        for bandeira in self.lista_botoes:
            if bandeira[1] == botao:
                self.idioma = bandeira[2]["text"]

                self.ic_idioma = PhotoImage(
                    file="imagens/{}".format(self.dic_imgs[self.idioma]))
                self.ic_idioma = self.ic_idioma.subsample(4, 4)
                funcoes.arquivo_de_configuracoes_interface(
                    "idioma", self.idioma)

                #self.lb1.configure(text=self.interface_idioma["texto_atualizacao"][self.idioma])

                self.tp_interface_idioma.destroy()
                del bandeira

                self.selecionar_idioma(self.dic_imgs)

            else:
                pass
        return 10, 20
Ejemplo n.º 27
0
class Interface:
    def __init__(self):
        log.info(f'{__name__} has been initialized.')

        self.window = Tk()
        self.window.title(f"FIB v{current_version}")
        self.window.geometry("380x225")
        self.style = Style()
        # if sys.platform == "win32":
        #     self.style.theme_use('winnative')
        self.window.minsize(380, 200)
        self.window.wait_visibility(self.window)
        self.windowWidth = self.window.winfo_reqwidth()
        self.windowHeight = self.window.winfo_reqheight()
        # Gets both half the screen width/height and window width/height
        self.positionRight = int(self.window.winfo_screenwidth() / 2 -
                                 self.windowWidth / 2)
        self.positionDown = int(self.window.winfo_screenheight() / 2 -
                                self.windowHeight / 2)
        self.window.geometry("+{}+{}".format(self.positionRight,
                                             self.positionDown))
        self.window.grid_columnconfigure(0, weight=1)
        self.window.resizable(0, 0)
        self.window.attributes("-topmost", True)

        self.window.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.main_menu = Menu(self.window)

        self.file_menu = Menu(self.main_menu, tearoff=0)
        # self.file_menu.add_command(label="Save")
        self.file_menu.add_command(label="Exit", command=self.menu_exit)

        self.help_menu = Menu(self.main_menu, tearoff=0)
        self.help_menu.add_command(label="About", command=self.menu_about)
        self.help_menu.add_command(label="Change License Key",
                                   command=self.menu_change_license)

        self.main_menu.add_cascade(label="File", menu=self.file_menu)
        self.main_menu.add_cascade(label="Help", menu=self.help_menu)

        self.window.config(menu=self.main_menu)

        self.info_label = Label(self.window,
                                text="STOP BOT: SHIFT + ESC",
                                font=("Helvetica", 16))
        self.info_label.grid(column=0, row=0, padx=15, pady=10, columnspan=2)

        self.btn1 = Button(self.window,
                           text="GENERAL OPTIONS",
                           command=self.options_win,
                           width=50)
        self.btn1.grid(column=0, row=1, padx=15, pady=5, columnspan=2)

        self.btn2 = Button(self.window,
                           text="CONFIGURE PARTY",
                           command=self.party_win,
                           width=50)
        self.btn2.grid(column=0, row=2, padx=15, pady=0, columnspan=2)

        self.gobtn = Button(self.window,
                            text="<---    START    --->",
                            command=self.ready_set_go,
                            width=50)
        self.gobtn.config(foreground="white", background="blue")
        self.gobtn.grid(column=0, row=3, padx=15, pady=20, columnspan=2)

        # self.window.bind('<Control-n>', self.party_win)

        # self.window.after(300, self.status_win)

        self.window.mainloop()

    def ready_set_go(self):
        self.window.quit()
        self.window.withdraw()
        self.window.destroy()
        database.paused = False
        log.info(f"FIB v{current_version} was started!")

    def options_win(self, e=None):
        self.window.withdraw()
        self.options_win = Toplevel(self.window)
        self.options_win.protocol("WM_DELETE_WINDOW", self.options_on_close)
        self.options_win.title(f"FIB v{current_version}")
        # self.options_win.geometry("400x315")
        self.options_win.minsize(width=400, height=315)
        self.options_win.maxsize(width=400, height=315)
        self.options_win.grid_columnconfigure(0, weight=1)
        self.options_win.grid_columnconfigure(2, weight=1)
        self.options_win.resizable(width=False, height=False)
        # self.options_win.pack_propagate(0)
        self.options_win.attributes("-topmost", True)
        self.options_win.geometry("+{}+{}".format(self.positionRight,
                                                  self.positionDown))

        self.options_text = Label(
            self.options_win,
            text="Use the boxes below to set your preferred options.")
        self.options_text.grid(column=0, row=0, padx=15, pady=5, columnspan=2)

        # Toggle if you want the bot to automatically prestige for you

        self.prestige_state = BooleanVar(self.options_win)
        if database.auto_prestige:
            self.prestige_state.set(True)
        self.prestige_toggle = Checkbutton(self.options_win,
                                           text="Auto-Prestige?",
                                           var=self.prestige_state)
        self.prestige_toggle.grid(column=0, row=5, padx=15, pady=5, sticky="w")

        # Selection for update channel

        self.updates_label = Label(self.options_win, text="Updates Channel:")
        self.updates_label.grid(column=0, row=3, padx=15, pady=2, sticky="w")

        self.channel_choice = Combobox(self.options_win, state="readonly")
        self.channel_choice['values'] = ("Stable", "Development")
        if database.channel == "Stable":
            self.channel_choice.current(0)
        elif database.channel == "Development":
            self.channel_choice.current(1)
        else:
            self.channel_choice['values'] = self.channel_choice['values'] + (
                database.channel, )
            self.channel_choice.current(2)
        self.channel_choice.grid(column=0, row=4, padx=15, pady=5, sticky="w")

        self.guardian_label = Label(self.options_win, text="Which Guardian:")
        self.guardian_label.grid(column=0, row=1, padx=15, pady=2, sticky="w")

        self.guardian_choice = Combobox(self.options_win, state="readonly")
        self.guardian_choice['values'] = [x for x in database.guardians]
        if database.guardian == "Fairy":
            self.guardian_choice.current(1)
        elif database.guardian == "Dragon":
            self.guardian_choice.current(0)
        self.guardian_choice.grid(column=0, row=2, padx=15, pady=5, sticky="w")

        self.guild_missions_state = BooleanVar(self.options_win)
        if database.guild_missions:
            self.guild_missions_state.set(True)
        self.guild_missions_toggle = Checkbutton(self.options_win,
                                                 text="Guild Missions?",
                                                 var=self.guild_missions_state)
        self.guild_missions_toggle.grid(column=1,
                                        row=5,
                                        padx=15,
                                        pady=5,
                                        sticky="w")

        self.prestige_level_label = Label(self.options_win,
                                          text="Prestige Multiplier:")
        self.prestige_level_label.grid(column=1,
                                       row=1,
                                       padx=15,
                                       pady=2,
                                       sticky="w")

        self.prestige_level = Entry(self.options_win)
        self.prestige_level.grid(column=1, row=2, padx=15, pady=5, sticky="w")
        self.prestige_level.insert(0, database.prestige_level)

        self.g_btn = Button(self.options_win,
                            text="SAVE",
                            width=40,
                            command=self.options_save)
        self.g_btn.grid(column=0, row=6, padx=15, pady=15, columnspan=2)
        self.g_btn.config(foreground="white", background="blue")

    def options_save(self, e=None):
        database.save_option('prestige_level', self.prestige_level.get())
        # config['OPTIONS']['in_guild'] = str(self.guild_state.get())
        database.save_option('auto_prestige', self.prestige_state.get())
        database.save_option('guild_missions', self.guild_missions_state.get())
        database.save_option('guardian', self.guardian_choice.get())

        self.window.deiconify()
        self.options_win.destroy()

    def party_win(self, e=None):
        self.window.withdraw()
        self.party_win = Toplevel(self.window)
        self.party_win.protocol("WM_DELETE_WINDOW", self.party_on_close)
        self.party_win.title(f"FIB v{current_version}")
        # self.party_win.geometry("350x275")
        self.party_win.minsize(width=400, height=350)
        self.party_win.maxsize(width=400, height=350)
        self.party_win.resizable(width=False, height=False)
        self.party_win.grid_columnconfigure(0, weight=1)
        self.party_win.grid_columnconfigure(2, weight=1)
        self.party_win.attributes("-topmost", True)
        self.party_win.geometry("+{}+{}".format(self.positionRight,
                                                self.positionDown))
        """

        Begin building the GUI

        """
        self.party_text = Label(
            self.party_win,
            text="Use the boxes below to set your party options.")
        self.party_text.grid(column=0, row=0, padx=15, pady=5, columnspan=2)

        self.party1_label = Label(self.party_win, text="Party Slot 01:")
        self.party1_label.grid(column=0, row=1, padx=15, pady=5, sticky="w")

        self.party2_label = Label(self.party_win, text="Party Slot 02:")
        self.party2_label.grid(column=1, row=1, padx=15, pady=5, sticky="w")

        self.party1 = Combobox(self.party_win, state="readonly")
        self.party1['values'] = [x for x in database.heroes]
        self.party1.current(4)
        self.party1.grid(column=0, row=2, padx=15, pady=5, sticky="w")

        self.party2 = Combobox(self.party_win, state="readonly")
        self.party2['values'] = [x for x in database.heroes]
        self.party2.current(10)
        self.party2.grid(column=1, row=2, padx=15, pady=5, sticky="w")

        self.party3_label = Label(self.party_win, text="Party Slot 03:")
        self.party3_label.grid(column=0, row=3, padx=15, pady=5, sticky="w")

        self.party4_label = Label(self.party_win, text="Party Slot 04:")
        self.party4_label.grid(column=1, row=3, padx=15, pady=5, sticky="w")

        self.party3 = Combobox(self.party_win, state="readonly")
        self.party3['values'] = [x for x in database.heroes]
        self.party3.current(5)
        self.party3.grid(column=0, row=4, padx=15, pady=5, sticky="w")

        self.party4 = Combobox(self.party_win, state="readonly")
        self.party4['values'] = [x for x in database.heroes]
        self.party4.current(2)
        self.party4.grid(column=1, row=4, padx=15, pady=5, sticky="w")

        self.party5_label = Label(self.party_win, text="Party Slot 05:")
        self.party5_label.grid(column=0, row=5, padx=15, pady=5, sticky="w")

        self.party_size_label = Label(self.party_win, text="Party Size:")
        self.party_size_label.grid(column=1,
                                   row=5,
                                   padx=15,
                                   pady=5,
                                   sticky="w")

        self.party5 = Combobox(self.party_win, state="readonly")
        self.party5['values'] = [x for x in database.heroes]
        self.party5.current(3)
        self.party5.grid(column=0, row=6, padx=15, pady=5, sticky="w")

        self.party_size = Combobox(self.party_win, state="readonly")
        self.party_size['values'] = ("1", "2", "3", "4", "5")
        self.party_size.current(4)
        self.party_size.grid(column=1, row=6, padx=15, pady=5, sticky="w")

        self.btn = Button(self.party_win,
                          text="SAVE",
                          command=self.party_save,
                          width=40)
        self.btn.grid(column=0, row=7, padx=15, pady=15, columnspan=2)
        self.btn.config(foreground="white", background="blue")

    def party_save(self):
        heroes = database.heroes.copy()
        selections = []
        selections.extend([
            self.party2.get(),
            self.party3.get(),
            self.party4.get(),
            self.party5.get()
        ])
        print(selections)

        party_slot_1 = self.party1.get()
        if party_slot_1 in heroes and party_slot_1 not in selections:
            database.save_option('party_slot_1', party_slot_1)
            heroes.remove(party_slot_1)
        else:
            messagebox.showerror(
                title="ERROR",
                message="PARTY SLOT 1: Invalid selection choice.")

        selections = []
        selections.extend([
            self.party1.get(),
            self.party3.get(),
            self.party4.get(),
            self.party5.get()
        ])
        print(selections)

        party_slot_2 = self.party2.get()
        if party_slot_2 in heroes and party_slot_2 not in selections:
            database.save_option('party_slot_2', party_slot_2)
            heroes.remove(party_slot_2)
        else:
            messagebox.showerror(
                title="ERROR",
                message="PARTY SLOT 2: Invalid selection choice.")

        selections = []
        selections.extend([
            self.party1.get(),
            self.party2.get(),
            self.party4.get(),
            self.party5.get()
        ])
        print(selections)

        party_slot_3 = self.party3.get()
        if party_slot_3 in heroes and party_slot_3 not in selections:
            database.save_option('party_slot_3', party_slot_3)
            heroes.remove(party_slot_3)
        else:
            messagebox.showerror(
                title="ERROR",
                message="PARTY SLOT 3: Invalid selection choice.")

        selections = []
        selections.extend([
            self.party1.get(),
            self.party2.get(),
            self.party3.get(),
            self.party5.get()
        ])
        print(selections)

        party_slot_4 = self.party4.get()
        if party_slot_4 in heroes and party_slot_4 not in selections:
            database.save_option('party_slot_4', party_slot_4)
            heroes.remove(party_slot_4)
        else:
            messagebox.showerror(
                title="ERROR",
                message="PARTY SLOT 4: Invalid selection choice.")

        selections = []
        selections.extend([
            self.party1.get(),
            self.party2.get(),
            self.party3.get(),
            self.party4.get()
        ])
        print(selections)

        party_slot_5 = self.party5.get()
        if party_slot_5 in heroes and party_slot_5 not in selections:
            database.save_option('party_slot_5', party_slot_5)
            heroes.remove(party_slot_5)
        else:
            messagebox.showerror(
                title="ERROR",
                message="PARTY SLOT 5: Invalid selection choice.")

        database.save_option('party_size', self.party_size.get())

        self.window.deiconify()
        self.party_win.destroy()

    def status_win(self, e=None):
        # self.window.withdraw()
        print('Deploy status window')
        self.status_win = Toplevel(self.window)
        self.status_win.configure(background="black")
        self.status_win.overrideredirect(1)
        self.status_win.protocol("WM_DELETE_WINDOW", self.status_on_close)
        self.status_win.title(f"Idle Bot Status")
        self.status_win.geometry("350x35")
        self.status_win.grid_columnconfigure(0, weight=1)
        self.status_win.grid_columnconfigure(0, weight=2)
        self.status_win.resizable(0, 0)
        # self.status_win.pack_propagate(0)
        self.status_win.attributes("-topmost", True)
        self.status_win.geometry("+{}+{}".format(0, 0))

        self.status_text = Label(
            self.status_win,
            foreground="white",
            background="black",
            text="IDLE BOT: Verify my settings before we get started.")
        self.status_text.grid(column=0,
                              row=0,
                              padx=5,
                              pady=5,
                              columnspan=2,
                              sticky="w")

    def update_status(self, status):
        self.status_text.config(text=f"IDLE BOT: {status}")
        self.status_win.update()

    def menu_exit(self):
        self.window.quit()
        self.window.destroy()
        database.running = False

    def menu_change_license(self):
        self.change_license()

    def menu_about(self):
        if database.email:
            user = database.email
        else:
            user = "******"

        messagebox.showinfo(
            f"ABOUT",
            f"FIRESTONE IDLE BOT v{current_version}\n\nLICENSED TO: {user}\n{database.edition}\n\nThank you for supporting Firestone Idle Bot!",
            parent=self.window)

    def options_on_close(self):
        self.window.deiconify()
        self.options_win.destroy()

    def status_on_close(self):
        self.status_win.destroy()

    def party_on_close(self):
        self.window.deiconify()
        self.party_win.destroy()

    def on_closing(self):
        self.window.quit()
        self.window.destroy()
        database.running = False
Ejemplo n.º 28
0
def show_streams_mediainfo_function(x):  # Stream Viewer
    global stream_win_text_area, exit_stream_window, stream_window
    video_input = pathlib.Path(x)  # "x" is passed through from main GUI

    # Defines the path to config.ini and opens it for reading/writing
    config_file = 'Runtime/config.ini'  # Creates (if it doesn't exist) and defines location of config.ini
    config = ConfigParser()
    config.read(config_file)

    detect_font = font.nametofont("TkDefaultFont")  # Get default font value into Font object
    set_font = detect_font.actual().get("family")
    # set_font_size = detect_font.actual().get("size")

    try:
        stream_win_text_area.config(state=NORMAL)
        stream_win_text_area.delete(1.0, END)
    except (NameError, TclError):
        stream_window = Toplevel()
        stream_window.title("Audio Streams")
        stream_window.configure(background="#434547")
        stream_window.resizable(False, False)  # Disable resize of this window
        if config['save_window_locations']['audio window - view streams - position'] != '' and \
                config['save_window_locations']['audio window - view streams'] == 'yes':
            stream_window.geometry(config['save_window_locations']['audio window - view streams - position'])
        stream_window.protocol('WM_DELETE_WINDOW', exit_stream_window)
        stream_window.grid_columnconfigure(0, weight=1)
        stream_window.grid_rowconfigure(0, weight=1)

        stream_window_frame = LabelFrame(stream_window, text=' Audio Streams ', labelanchor="n")
        stream_window_frame.grid(column=0, row=0, columnspan=1, padx=5, pady=(0, 3), sticky=N + S + E + W)
        stream_window_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold"))
        stream_window_frame.grid_rowconfigure(0, weight=1)
        stream_window_frame.grid_columnconfigure(0, weight=1)

        stream_win_text_area = scrolledtext.ScrolledText(stream_window_frame, width=80, height=25, tabs=10, spacing2=3,
                                                         spacing1=2, spacing3=3)
        stream_win_text_area.config(bg='black', fg='#CFD2D1', bd=8)
        stream_win_text_area.grid(column=0, pady=5, padx=5, sticky=N + E + S + W)

    character_space = 30  # Can be changed to adjust space of all items in the list automatically
    media_info = MediaInfo.parse(video_input)  # Uses pymediainfo to get information for track selection
    for track in media_info.tracks:  # For loop to loop through mediainfo tracks
        # Formatting --------------------------------------------------------------------------------------------------
        if track.track_type == 'Audio':  # Only grab audio track information
            if str(track.stream_identifier) != 'None':  # Gets stream #
                audio_track_id_space = 'Track#' + ' ' * int(f'{character_space - len("Track#")}')
                audio_track_id = audio_track_id_space + f': {str(int(track.stream_identifier) + 1)}\n'
            else:
                audio_track_id = ''
            if str(track.format) != 'None':  # Gets format string of tracks (aac, ac3 etc...)
                audio_format_space = 'Codec' + ' ' * int(f'{character_space - len("Codec")}')
                audio_format = audio_format_space + f": {str(track.commercial_name)} - ({str(track.format).lower()})\n"
            else:
                audio_format = ''
            if str(track.channel_s) != 'None':  # Gets audio channels of input tracks
                audio_channel_space = 'Channels' + ' ' * int(f'{character_space - len("Channels")}')
                if str(track.channel_s) == '8':
                    show_channels = '7.1'
                elif str(track.channel_s) == '6':
                    show_channels = '5.1'
                elif str(track.channel_s) == '3':
                    show_channels = '2.1'
                else:
                    show_channels = str(track.channel_s)
                audio_channels = audio_channel_space + f": {show_channels} - {str(track.channel_layout)}\n"
            else:
                audio_channels = ''
            if str(track.bit_rate_mode) != 'None':  # Gets audio bit rate mode
                audio_bitrate_mode_space = 'Bit rate mode' + ' ' * int(f'{character_space - len("Bit rate mode")}')
                if str(track.other_bit_rate_mode) != 'None':  # Get secondary string of audio bit rate mode
                    audio_bitrate_mode = audio_bitrate_mode_space + f": {str(track.bit_rate_mode)} / " \
                                                                    f"{str(track.other_bit_rate_mode[0])}\n"
                else:
                    audio_bitrate_mode = audio_bitrate_mode_space + f": {str(track.bit_rate_mode)}\n"
            else:
                audio_bitrate_mode = ''
            if str(track.other_bit_rate) != 'None':  # Gets audio bit rate of input tracks
                audio_bitrate_space = 'Bit rate' + ' ' * int(f'{character_space - len("Bit rate")}')
                audio_bitrate = audio_bitrate_space + f": {str(track.other_bit_rate[0])}\n"
            else:
                audio_bitrate = ''
            if str(track.other_language) != 'None':  # Gets audio language of input tracks
                audio_language_space = 'Language' + ' ' * int(f'{character_space - len("Language")}')
                audio_language = audio_language_space + f": {str(track.other_language[0])}\n"
            else:
                audio_language = ''
            if str(track.title) != 'None':  # Gets audio title of input tracks
                audio_title_space = 'Title' + ' ' * int(f'{character_space - len("Title")}')
                if len(str(track.title)) > 40:  # Counts title character length
                    audio_title = audio_title_space + f": {str(track.title)[:40]}...\n"  # If title > 40 characters
                else:
                    audio_title = audio_title_space + f": {str(track.title)}\n"  # If title is < 40 characters
            else:
                audio_title = ''
            if str(track.other_sampling_rate) != 'None':  # Gets audio sampling rate of input tracks
                audio_sampling_rate_space = 'Sampling Rate' + ' ' * int(f'{character_space - len("Sampling Rate")}')
                audio_sampling_rate = audio_sampling_rate_space + f": {str(track.other_sampling_rate[0])}\n"
            else:
                audio_sampling_rate = ''
            if str(track.other_duration) != 'None':  # Gets audio duration of input tracks
                audio_duration_space = 'Duration' + ' ' * int(f'{character_space - len("Duration")}')
                audio_duration = audio_duration_space + f": {str(track.other_duration[0])}\n"
            else:
                audio_duration = ''
            if str(track.delay) != 'None':  # Gets audio delay of input tracks
                if str(track.delay) == '0':
                    audio_delay = ''
                else:
                    audio_delay_space = 'Delay' + ' ' * int(f'{character_space - len("Delay")}')
                    audio_del_to_vid_space = 'Delay to Video' + ' ' * int(f'{character_space - len("Delay to Video")}')
                    audio_delay = audio_delay_space + f': {str(track.delay)}ms\n' \
                                  + audio_del_to_vid_space + f': {str(track.delay_relative_to_video)}ms\n '
            else:
                audio_delay = ''
            if str(track.other_stream_size) != 'None':  # Get tracks stream size
                audio_track_size_space = 'Stream size' + ' ' * int(f'{character_space - len("Stream size")}')
                audio_track_stream_size = audio_track_size_space + f": {str(track.other_stream_size[4])}\n"
            else:
                audio_track_stream_size = ''
            if str(track.other_bit_depth) != 'None':  # Get tracks bit-depth
                audio_track_b_depth_space = 'Bit Depth' + ' ' * int(f'{character_space - len("Bit Depth")}')
                audio_track_bit_depth = audio_track_b_depth_space + f": {(track.other_bit_depth[0])}\n"
            else:
                audio_track_bit_depth = ''
            if str(track.compression_mode) != 'None':
                audio_track_compression_space = 'Compression' + ' ' * int(f'{character_space - len("Compression")}')
                audio_track_compression = audio_track_compression_space + f": {str(track.compression_mode)}\n"
            else:
                audio_track_compression = ''
            if str(track.default) != 'None':  # Get tracks default boolean
                audio_track_default_space = 'Default' + ' ' * int(f'{character_space - len("Default")}')
                audio_track_default = audio_track_default_space + f": {str(track.default)}\n"
            else:
                audio_track_default = ''
            if str(track.forced) != 'None':  # Get tracks forced boolean
                audio_track_forced_space = 'Forced' + ' ' * int(f'{character_space - len("Forced")}')
                audio_track_forced = audio_track_forced_space + f": {str(track.forced)}"
            else:
                audio_track_forced = ''

            # ---------------------------------------------------------------------------------------------- Formatting
            audio_track_info = str(audio_track_id + audio_format + audio_channels + audio_bitrate_mode +
                                   audio_bitrate + audio_sampling_rate + audio_delay + audio_duration +
                                   audio_language + audio_title + audio_track_stream_size + audio_track_bit_depth +
                                   audio_track_compression + audio_track_default + audio_track_forced)  # Formatting
            media_info_track_string = 80 * '#' + '\n' + audio_track_info + '\n' + 80 * '#' + '\n'  # String to insert
            stream_win_text_area.configure(state=NORMAL)  # Enable textbox
            stream_win_text_area.insert(INSERT, media_info_track_string)  # Insert string
            stream_win_text_area.insert(INSERT, '\n')  # Insert a newline
            stream_win_text_area.configure(state=DISABLED)  # Disable textbox

    def right_click_menu_func(x_y_pos):  # Function for mouse button 3 (right click) to pop up menu
        right_click_menu.tk_popup(x_y_pos.x_root, x_y_pos.y_root)  # This gets the position of cursor

    def copy_selected_text():  # Function to copy only selected text
        pya_hotkey('ctrl', 'c')
        time_sleep(.01)  # Slow program incase ctrl+c is slower

    right_click_menu = Menu(stream_window, tearoff=False)  # This is the right click menu
    right_click_menu.add_command(label='Copy Selected Text', command=copy_selected_text)
    right_click_menu.add_command(label='Copy All Text', command=pyperclip_copy(stream_win_text_area.get(1.0, END)))
    stream_window.bind('<Button-3>', right_click_menu_func)  # Uses mouse button 3 (right click) to pop up menu
    Hovertip(stream_win_text_area, 'Right click to copy', hover_delay=1200)  # Hover tip tool-tip
Ejemplo n.º 29
0
class ProcMemPlot:
    def __init__(self, hostname=None):
        self.peak_mem = 0
        self.total_mem = 1024
        self.free_mem = self.total_mem
        self.pause_plot = 0
        self.hostname = hostname

        # members for GUI
        self.window_plot = None

        self.combo_period = None
        self.label_period = None
        self.combo_period_seconds = []

        self.figure_hist = None
        self.plot_axe_hist = None
        self.y_ax = None
        self.canvas_hist = None
        self.frame_toolbar = None
        self.toolbar_plot = None

        self.button_plot_pause = None

        # members for plot data.
        self.time_hist = {}
        self.mem_hist = {}

    def plot_metrics(self):
        if (not (self.window_plot is not None and \
                 tk.Toplevel.winfo_exists(self.window_plot))) or \
            self.time_hist.get('rss_total') is None or self.pause_plot == 1:
            return

        period_selection = self.combo_period.current()
        period_secodns_sel = self.combo_period_seconds[period_selection]
        last_N = period_secodns_sel // DEFAULT_REFRESH_INTERVAL
        self.plot_axe_hist.clear()
        y_hist_dict = {
            'time': self.time_hist['rss_total'][-last_N:],
            'mem': self.mem_hist['rss_total'][-last_N:]
        }
        y_hist_df = DataFrame(y_hist_dict, columns=['time', 'mem'])
        y_hist_df.plot(kind='line',
                       legend=True,
                       x='time',
                       y='mem',
                       ax=self.plot_axe_hist,
                       color='r',
                       marker='.',
                       fontsize=10)

        self.plot_axe_hist.set_ylabel('Memory(GB)')
        self.plot_axe_hist.set_title('Memory (GB) History - max=' + str(self.peak_mem) + \
                                     ' free=' + str(self.free_mem))
        self.plot_axe_hist.set_ylim([0, self.total_mem])
        self.canvas_hist.draw()

    def toggle_pause_plot(self):
        if self.pause_plot == 0:
            self.pause_plot = 1
            self.button_plot_pause['text'] = 'Resume'
        else:
            self.pause_plot = 0
            self.button_plot_pause['text'] = 'Pause'

    def show_plot_window(self, root_window):
        if self.window_plot is not None and tk.Toplevel.winfo_exists(
                self.window_plot):
            return

        self.window_plot = Toplevel(root_window)
        self.window_plot.geometry('1200x600+20+500')
        self.window_plot.title(PROGRAM_NAME + ' ' + VERSION + ' - plot - ' +
                               self.hostname)
        self.window_plot.grid_columnconfigure(1, weight=1)

        cur_grid_row = 0
        self.label_period = ttk.Label(self.window_plot,
                                      text="Period",
                                      width=LABEL_WIDTH,
                                      anchor='w')
        self.label_period.grid(row=cur_grid_row,
                               column=0,
                               sticky='w',
                               padx=10,
                               pady=10)
        self.combo_period = ttk.Combobox(self.window_plot, width=COMBO_WIDTH)
        self.combo_period['values'] = [
            'Last 1 hour', 'Last 4 hours', 'Last 8 hours', 'Last 24 hours',
            'All history'
        ]
        self.combo_period_seconds = [
            3600, 3600 * 4, 3600 * 8, 3600 * 24, 3600 * 10000
        ]
        self.combo_period.grid(row=cur_grid_row, column=1, sticky='w', pady=10)
        self.combo_period.current(0)
        cur_grid_row = cur_grid_row + 1

        # plot row
        self.figure_hist = plt.Figure(figsize=(10, 5), dpi=FIGURE_DPI)
        self.plot_axe_hist = self.figure_hist.add_subplot(111)
        self.canvas_hist = FigureCanvasTkAgg(self.figure_hist,
                                             self.window_plot)
        self.canvas_hist.get_tk_widget().grid(row=cur_grid_row,
                                              column=0,
                                              columnspan=2,
                                              sticky='nsew')
        self.window_plot.grid_rowconfigure(cur_grid_row, weight=1)
        cur_grid_row = cur_grid_row + 1

        # Plot navigation toolbar
        self.frame_toolbar = tk.Frame(self.window_plot)
        self.frame_toolbar.grid(row=cur_grid_row, column=0, columnspan=2)
        self.toolbar_plot = NavigationToolbar2Tk(self.canvas_hist,
                                                 self.frame_toolbar)
        cur_grid_row = cur_grid_row + 1

        # command buttons
        self.button_plot_pause = ttk.Button(self.window_plot,
                                            text="Pause",
                                            command=self.toggle_pause_plot)
        self.button_plot_pause.grid(row=cur_grid_row,
                                    column=0,
                                    columnspan=2,
                                    pady=10)
        cur_grid_row = cur_grid_row + 1

    def update_history(self, mem_usages):
        if self.time_hist.get('rss_total') is None:
            self.time_hist['rss_total'] = []
            self.mem_hist['rss_total'] = []

        cur_time = datetime.datetime.now().strftime("%m/%d %H:%M:%S")
        self.time_hist['rss_total'].append(cur_time)
        self.mem_hist['rss_total'].append(mem_usages['rss_total']['rss'])
        if mem_usages['rss_total']['rss'] > self.peak_mem:
            self.peak_mem = mem_usages['rss_total']['rss']
            print('INFO: @{} peak memory={} total memory={}'.format(
                cur_time, self.peak_mem, self.total_mem))

        # update free memeory
        command = ['free', '-g']
        p = subprocess.Popen(command,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        free_out = p.stdout.read().decode('utf-8')
        mem_line = free_out.strip().split('\n')[1]
        self.free_mem = int(mem_line.split()[6])
Ejemplo n.º 30
0
class ReportBug(object):
    def __init__(self, interface_idioma, master, design, idioma, icon):
        self.__bt_report = None
        self.__image_bug = None
        self.__bt_cancel = None
        self.__fr_botoes = None
        self.__lb_label3 = None
        self.__lb_label2 = None
        self.__lb_label1 = None
        self.__tp_princi = None
        self.interface_idioma = interface_idioma
        self.master = master
        self.design = design
        self.idioma = idioma
        self.icon = icon

    def __acessar_site_reporte(self):
        website_forms = "https://forms.gle/J4kE2Li8c58fz4hh6"

        self.__bt_report.configure(
            text=self.interface_idioma["abrir_formulario"][self.idioma])

        t = Thread(target=lambda event=None: webbrowser_open(website_forms))
        t.start()

        self.__destruir_interface()

    def __destruir_interface(self):
        self.__bt_report.destroy()
        self.__bt_cancel.destroy()
        self.__fr_botoes.destroy()
        self.__lb_label3.destroy()
        self.__lb_label2.destroy()
        self.__lb_label1.destroy()
        self.__tp_princi.destroy()

    def bug_carregar_tela(self):
        self.__image_bug = PhotoImage(file="imagens/bug.png")
        self.__image_bug = self.__image_bug.subsample(4)

        self.__tp_princi = Toplevel(
            self.master,
            bd=10,
            bg=self.design.dic["bug_lb1_encontrou_bug"]["bg"])
        self.__tp_princi.resizable(False, False)
        self.__tp_princi.title(
            self.interface_idioma["titulo_reporte_bug"][self.idioma])
        self.__tp_princi.tk.call('wm', 'iconphoto', self.__tp_princi._w,
                                 self.icon)
        self.__tp_princi.withdraw()

        try:
            self.__tp_princi.wm_attributes('-type', 'splash')
        except Exception as erro:
            print("Erro ao remover barra de titulos => ", erro)

        self.__lb_label1 = Label(self.__tp_princi)
        self.__lb_label2 = Label(self.__tp_princi)
        self.__lb_label3 = Label(self.__tp_princi)

        self.__lb_label1.configure(self.design.dic["bug_lb1_encontrou_bug"])
        self.__lb_label2.configure(self.design.dic["bug_lb2_encontrou_bug"])
        self.__lb_label3.configure(self.design.dic["bug_lb3_encontrou_bug"])

        self.__lb_label1.configure(
            text=self.interface_idioma["encontrou_bug"][self.idioma])
        self.__lb_label2.configure(image=self.__image_bug)
        self.__lb_label3.configure(
            text=self.interface_idioma["texto_reportar_bug"][self.idioma])

        self.__fr_botoes = Frame(self.__tp_princi,
                                 self.design.dic["bug_fr_bt_encontrou_bug"])
        self.__bt_cancel = Button(
            self.__fr_botoes,
            self.design.dic["bug_bt_canc_encontrou_bug"],
            text=self.interface_idioma["texto_depois"][self.idioma],
            relief=FLAT)
        self.__bt_report = Button(
            self.__fr_botoes,
            self.design.dic["bug_bt_report_encontrou_bug"],
            text=self.interface_idioma["texto_reporte_bug"][self.idioma],
            relief=FLAT)

        self.__tp_princi.grid_columnconfigure(1, weight=1)
        self.__fr_botoes.grid_columnconfigure(1, weight=1)
        self.__fr_botoes.grid_columnconfigure(2, weight=1)

        self.__bt_cancel.configure(
            command=lambda event=None: self.__destruir_interface())
        self.__bt_report.configure(
            command=lambda event=None: self.__acessar_site_reporte())

        self.__lb_label1.grid(row=1, column=1, sticky=NSEW)
        self.__lb_label2.grid(row=2, column=1, sticky=NSEW)
        self.__lb_label3.grid(row=3, column=1, sticky=NSEW)
        self.__fr_botoes.grid(row=4, column=1, sticky=NSEW)
        self.__bt_cancel.grid(row=1, column=1)
        self.__bt_report.grid(row=1, column=2)

        self.__tp_princi.update()
        self.__tp_princi.deiconify()