Ejemplo n.º 1
0
class TestWindow(Tk):
    def __init__(self):
        super().__init__()

        # Set the window parameters
        self.wm_title("Test Window")
        self.wm_geometry("800x600")

        self._nb = Notebook(self)
        self._nb.pack(fill=BOTH, expand=1)

        # Add the ScrollableTreeview
        self.STV = ScrollableTreeview(
            self._nb,
            columns=('first','second'),
            headers={
                '#0':'Default',
                'first':{'text':'First'},
                'second':{'text':'Second'}
            }
        )
        self._nb.add(self.STV, text="Scrollable Treeview")

        iid = self.STV.insert('', 'end', text='Root Node')
        self.STV.insert(iid, 'end', text='Child 1')
        self.STV.insert(iid, 'end', text='Child 2')
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     tool_tabs = Notebook(self.tk_object)
     tool_tabs.pack(fill='x')
     with self.attribute_lock:
         self._tool_tabs = tool_tabs
     self.window_manager = WindowManager()
Ejemplo n.º 3
0
class SettingsPopup(Toplevel):
    
    def __init__(self,parent):
        Toplevel.__init__(self) 
        self.transient(parent)
        self.focus()

        sw = parent.winfo_screenwidth()
        sh = parent.winfo_screenheight()
        self.geometry('%dx%d+%d+%d' % (sw/2, sh/2, sw/4, sh/4))
        self.grab_set()
        self.title("Settings")

        self.modeNotebook = Notebook(self)
        self.modeNotebook.pack(fill=BOTH, expand=True)

        self.addFrame = AddSettingsFrame(self.modeNotebook, self)
        self.addFrame.pack(fill=BOTH, expand=True)

        self.editFrame = EditSettingsFrame(self.modeNotebook, self)
        self.editFrame.pack(fill=BOTH, expand=True)

        self.deleteFrame = DeleteSettingsFrame(self.modeNotebook, self)
        self.deleteFrame.pack(fill=BOTH, expand=True)

        self.modeNotebook.add(self.addFrame, text='Add')
        self.modeNotebook.add(self.editFrame, text='Edit')
        self.modeNotebook.add(self.deleteFrame, text='Delete')

        self.addFrame.setupFrame()
        self.editFrame.setupFrame()
        
        self.wait_window()
Ejemplo n.º 4
0
class FinalPlotFrame(AbstractTabFrame):
    """View final plots, move labels and manage footnotes"""
    def __init__(self, parent, handler, next_frame):
        super().__init__(parent, "Final Plots", handler, next_frame)
        self.canvasnotebook = Notebook(self)
        self.peakloadframe = PeakLoadFrame(self.canvasnotebook)
        self.canvasnotebook.add(self.peakloadframe, text="Peak Load")

        self.utsframe = UTSFrame(self.canvasnotebook)
        self.canvasnotebook.add(self.utsframe, text="Yield Stren/UTS")

        self.yieldloadframe = YieldLoadFrame(self.canvasnotebook)
        self.canvasnotebook.add(self.yieldloadframe, text="Yield Load")

        self.build()

    def can_update(self):
        s = self._proj_handle.curr_sample
        return s.is_complete

    def content_update(self):
        s = self._proj_handle.curr_sample
        self.peakloadframe.set_sample(s)
        self.utsframe.set_sample(s)
        self.yieldloadframe.set_sample(s)

    def unload(self):
        s = self._proj_handle.curr_sample
        project = self._proj_handle.project
        pdf_dir = project.pdf_dir

        info_file = "{}temp/S{}_INFO.pdf".format(pdf_dir, s.num)
        generate_sample_layer(s, info_file)

        pl_file = "{}temp/S{}_PL.pdf".format(pdf_dir, s.num)
        self.peakloadframe.canvas.figure.savefig(pl_file)
        create_pdf(info_file, project.template_file, pl_file, pdf_dir+"Sample #{} (PeakLoad).pdf".format(s.num))

        uts_file = "{}temp/S{}_UTS.pdf".format(pdf_dir, s.num)
        self.utsframe.canvas.figure.savefig(uts_file)
        create_pdf(info_file, project.template_file, uts_file, pdf_dir+"Sample #{} (UTS).pdf".format(s.num))

        yl_file = "{}temp/S{}_YL.pdf".format(pdf_dir, s.num)
        self.yieldloadframe.canvas.figure.savefig(yl_file)
        create_pdf(info_file, project.template_file, yl_file, pdf_dir+"Sample #{} (YieldLoad).pdf".format(s.num))

        messagebox.showinfo(title="Success",message="Created 3 files in {}".format(pdf_dir))


    def build(self):
        self.canvasnotebook.pack()
        Button(self, text="Generate PDFs", command=self.on_next, font=GUI_FONT).pack(side=RIGHT)
Ejemplo n.º 5
0
class OptionsFrame(Frame):
    def __init__(self, master):
        super(OptionsFrame, self).__init__(master)
        self.master = master

        self.notebook = Notebook(self)
        self.notebook.pack()

        self.f1 = Frame(self.notebook)
        self.notebook.add(self.f1, text='F1')

        self.quit_button = Button(self.f1,
                                  text='Quit',
                                  width=25,
                                  command=self._close_windows)
        self.quit_button.pack()
        self.f1.pack()
        self.pack()

    def _close_windows(self):
        self.master.destroy()
Ejemplo n.º 6
0
class Main:

    def __init__(self):
        self.nb = Notebook(rootWindow)
        self.nb.pack()

        database = Database('Timesheet2.db')


        clock_frame = tkinter.Frame(self.nb)
        self.nb.add(clock_frame, text='Clock in')
        display_frame = tkinter.Frame(self.nb)
        self.nb.add(display_frame, text='Display hours')

        alter_frame = tkinter.Frame(self.nb)
        self.nb.add(alter_frame, text='Alter hours')


        display_sheet = DisplayGrid(display_frame, database)
        alter_sheet = AlterHours(alter_frame, database)
        clock_in = Timestamp(clock_frame, database)
Ejemplo n.º 7
0
class menu():
    def __init__(self, main_menu, gemroc_handler, main_menu_istance):
        self.error_window_main = Toplevel(main_menu)
        self.error_window_main.wm_title("Noise and thresholds")
        self.tabControl = Notebook(
            self.error_window_main)  # Create Tab Control

        self.rate_tab = noise_rate_measure(self.error_window_main,
                                           gemroc_handler, self.tabControl,
                                           main_menu_istance)
        self.rate_tab._insert("All system")
        self.rate_tab._init_windows()
        self.error_window_main.protocol("WM_DELETE_WINDOW",
                                        self.rate_tab.close_stopping)

        self.tabControl.pack(expand=1, fill="both")  # Pack to make visible

    def _delete_window(self):
        self.main_menu_istance.run_control_Button.config(state='normal')
        self.main_menu_istance.doing_something = False
        self.error_window_main.destroy()
Ejemplo n.º 8
0
class GUI(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_frames()
        self.master.title("Tk with Pandas Plot test")

    def create_frames(self):
        self.tabs = Notebook(self)
        self.tabs.pack()

        self.home_frame = HomeFrame(self.tabs)

        self.tabs.add(self.home_frame, text='Home')

        self.tabs.select(self.home_frame)
        self.tabs.enable_traversal()

    def start(self):
        self.master.mainloop()
Ejemplo n.º 9
0
 def init_tabs(self):
     """Creating Tabs : Dice, Map, Encounters, Treasure"""
     tab_bar = Notebook(self)
     tab_bar.pack(fill=BOTH, padx=2, pady=3)
     #Dice
     self.tab_dice = DiceTab(tab_bar)
     tab_bar.add(self.tab_dice, text="Dice")
     #Map
     self.tab_map = MapTab(tab_bar)
     tab_bar.add(self.tab_map, text="Map")
     #Encounters
     self.tab_encounters = EncountersTab(tab_bar)
     tab_bar.add(self.tab_encounters, text="Encounters")
     #Treasure
     self.tab_treasure = TreasureTab(tab_bar)
     tab_bar.add(self.tab_treasure, text="Treasure")
     #Character Sheet
     self.tab_character_sheet = CharacterSheetTab(tab_bar)
     tab_bar.add(self.tab_character_sheet, text="Character Sheet")
     #Disease Generator
     self.tab_disease = DiseaseTab(tab_bar)
     tab_bar.add(self.tab_disease, text="Disease")
Ejemplo n.º 10
0
class OptionsFrame(Frame):
    def __init__(self, master):
        super(OptionsFrame, self).__init__(master)
        self.master = master

        self.notebook = Notebook(self)
        self.notebook.pack()

        self.f1 = Frame(self.notebook)
        self.notebook.add(self.f1, text='F1')

        self.quit_button = Button(
            self.f1,
            text='Quit',
            width=25,
            command=self._close_windows)
        self.quit_button.pack()
        self.f1.pack()
        self.pack()

    def _close_windows(self):
        self.master.destroy()
Ejemplo n.º 11
0
def ui():
    w = 0
    c = 0
    k = 0
    root = Tk()
    root.title("Product Details")
    root.geometry("700x450+0+0")
    frame2 = Frame(root)
    frame2.pack(fill="both")

    tablayout = Notebook(frame2)

    tab1 = Frame(tablayout)
    tab1.pack(fill="both")
    for w in range(1, r + 2):
        newrow = customer.row_values(w)
        k = 1
        for c in newrow:
            Label(tab1,
                  text=c,
                  width=15,
                  bg="white",
                  fg="black",
                  padx=3,
                  pady=3).grid(row=w, column=k, sticky="nsew", padx=1, pady=1)
            # Entry(tab1, bg=c, width=10).grid(row=r,column=1)
            k = k + 1
    Label(tab1,
          text="Total Amount",
          width=15,
          bg="white",
          fg="black",
          padx=3,
          pady=3).grid(row=w + 1, column=k - 6, sticky="nsew", padx=1, pady=1)
    Label(tab1, text=sum, width=15, bg="white", fg="black", padx=3,
          pady=3).grid(row=w + 1, column=k - 5, sticky="nsew", padx=1, pady=1)
    tablayout.add(tab1)
    tablayout.pack(fill="both")
    root.mainloop()
def Checkpoints():
    global show
    topic = ["No.","Room","Student Id","Name","Score"] #หัวตาราง
    ptr = 0
    show = Toplevel(root) 
    show.geometry("625x250+800+50")
    show.title("Show Student list and score")
    frame1 = Frame(show,bg='#FDF5E6')
    frame1.pack(fill="both")
    tablelayout = Notebook(frame1)
    tab1 = Frame(tablelayout,bg='#FDF5E6')
    tab1.pack(fill="both")
    checker(show)
    file=open("d:\\UserData\\STD_DATA.txt", "r")
    many = file.read()
    many = many.split(":")
    j = len(many)
    j = j//4
    for row in range(0,j+1):
        for column in range(0,5):
            if row == 0:
                label = Label(tab1,text=topic[column],bg="#FDF5E6",padx=3,pady=3)
                label.grid(row=row,column=column,sticky="nsew",padx=1,pady=1)
                tab1.grid_columnconfigure(column,weight=1)
            elif column == 0:
                label = Label(tab1,text=row,bg="white",padx=3,pady=3)
                label.grid(row=row,column=column,sticky="nsew",padx=1,pady=1)
                tab1.grid_columnconfigure(column,weight=1)
            else:
                label = Label(tab1,text=str(many[ptr]),bg="white",padx=3,pady=3)
                label.grid(row=row,column=column,sticky="nsew",padx=1,pady=1)
                tab1.grid_columnconfigure(column,weight=1)
                ptr += 1
    edit = Button(tab1,text="Edit",height=1,width=10,command=edit_tab,font=('supermarket'),bg='#FA8072')
    edit.grid(row=j+1,column=4,sticky="E")
    tablelayout.add(tab1,text="Student Data")
    tablelayout.pack(fill="both")
    def __init__(self):
        self.tk = Tk()
        self.tk.minsize(1000, 600)
        self.tk.title('Прайс-мастер (версия 0.15)')

        self.db = DataBase()
        self.db.openData()
        self.theme = Theme(self.tk)
        self.theme.refresh()
        self.vld = Validator(self.tk)
        self.grd = Grider()
        self.trn = Translater()

        self.main_menu = Menu(self.tk)
        self.tk.config(menu=self.main_menu)
        self.pl_menu = Menu(self.main_menu, tearoff=0)
        self.main_menu.add_cascade(label="Импорт/экспорт .pickle-файлов",
                                   menu=self.pl_menu)
        self.pl_menu.add_command(command=self.import_pm_template,
                                 label="Обновить шаблон базы данных")
        self.pl_menu.add_command(command=self.export_pm_data,
                                 label="Экспорт прайс-листа")

        nb = Notebook(self.tk)

        self.prcTab = PriceTab(self)
        self.debugXlsTab = DebugXlsTab(self)
        self.importXlsTab = ImportXlsTab(self)
        self.prcTab.reset()

        nb.add(self.prcTab.frmTab, text='Прайс-лист')
        nb.add(self.debugXlsTab.frmTab, text='Отладка .xls-файлов')
        nb.add(self.importXlsTab.frmTab, text='Импорт .xls-файлов')
        nb.pack(expand=True, fill='both')

        self.tk.mainloop()
Ejemplo n.º 14
0
def _gui():
  try:
    from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar
    from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style
  except:
    sys.exit("Unable to load tkinter. Aborting.")
  
  def _check_single(): #check the input and accordingly give the output... for the f_single tab
    if txt_f_single_entry.get()=="":
      lbl_f_single_result.config(text="", style="TLabel")
    elif check_afm(txt_f_single_entry.get()):
      lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel")
    else:
      lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel")
  
  def _select_input_file():
    strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου"))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
#TODO a much better mechanism to enable / disable btn_f_file_submit is needed.
  def _select_output_file():
    strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως..."))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
  
  def _check_file():#TODO this could / should be merged with the TUI version...
    input_filepath = strv_f_file_input.get()
    output_filepath = strv_f_file_output.get()
    filter_output = intvar_filter_sel.get()
    try:
      input_file = open(input_filepath, "r")
      output_file = open(output_filepath, "w")
    except:
      messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.")
      return
    counter = {True:0, False:0}
    for entry in input_file:
      validation = check_afm(entry.strip())
      counter[validation]+=1
      if filter_output == 3 and validation == False:
        output_file.write(entry)
      elif filter_output == 2 and validation == True:
        output_file.write(entry)
      elif filter_output == 1:
        output_file.write(entry.strip() + "\t" + str(validation) + "\n\r")
    lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False]))

  #create the window
  main_window = Tk()
  main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)")
  main_window.geometry("600x180")
  main_window.minsize(600,180)

  #fool arround with styling
  style = ttk.Style()
  style.configure("valid.TLabel", background="green")
  style.configure("empty.TLabel", background="white")
  style.configure("invalid.TLabel", background="red")
  style.configure("TNotebook", padding = 10)
  
  #create the Notebook
  tabs = Notebook(main_window)
  f_single = Frame(tabs)
  f_file = Frame(tabs)
  tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.")
  tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready
  tabs.pack(anchor="nw")
  
  #add some widgets in f_single tab
  lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο")
  lbl_f_single_instructions.grid(column=0, row=0)

  lbl_f_single_result = Label(f_single, text="", width=10, justify="center")
  lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns")

  txt_f_single_entry = Entry(f_single, width=11)
  txt_f_single_entry.focus()
  txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() )
  txt_f_single_entry.grid(column=0,row=1)

  #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single)
  #btn_f_single_submit.grid(column=0,row=2)
    
  #add some widgets in f_file tab
  lbl_f_file_finput = Label(f_file, text="Άνοιγμα...")
  lbl_f_file_finput.grid(column=0, row=0)
  strv_f_file_input = StringVar()
  txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input)
  txt_f_file_finput.grid(column=1, row=0)
  btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file)
  btn_f_file_finput.grid(column=2, row=0, sticky="W")
  
  lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...")
  lbl_f_file_foutput.grid(column=0, row=1)
  strv_f_file_output = StringVar()
  txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output)
  txt_f_file_foutput.grid(column=1, row=1)
  btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file)
  btn_f_file_foutput.grid(column=2, row=1, sticky="W")
  
  lf_filter = LabelFrame(f_file, text="Επιστροφή")
  lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns")
  intvar_filter_sel = IntVar()
  rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command
  rb_filter_all.pack(anchor="w")
  rb_filter_all.invoke()
  rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2)
  rb_filter_true.pack(anchor="w")
  rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3)
  rb_filter_false.pack(anchor="w")
  
  lf_result = LabelFrame(f_file, text="Σύνοψη")
  lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns")
  lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results
  lbl_f_file_result.pack()
  
  btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file)
  btn_f_file_submit.grid(column=0, row=2, columnspan=3)
  
  btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit)
  btn_main_exit.pack(anchor="se")

  main_window.mainloop()
Ejemplo n.º 15
0
               activebackground="red",
               troughcolor="orange",
               orient="horizontal")
scale2.pack(fill="x")

frame2 = Frame(window)
frame2.pack(fill="both")

tablayout = Notebook(frame2)

tab1 = Frame(tablayout)
tab1.pack(fill="both")
label = Label(tab1, text="same Data in Tab 1")
label.pack()
tablayout.add(tab1, text="TAB 1")
tablayout.pack(fill="both")

tab1 = Frame(tablayout)
tab1.pack(fill="both")
label = Label(tab1, text="same Data in Tab 1")
label.pack()

# adding table into tab
for row in range(5):
    for column in range(6):
        if row == 0:
            label = Label(tab1,
                          text="Heading : " + str(column),
                          bg="white",
                          fg="black",
                          padx=3,
Ejemplo n.º 16
0
class Root(tk.Tk):
    def __init__(self):
        super().__init__()

        # ---------Initializing--------------------------------------

        # import data for gamma, beta, and alpha radiation
        with open('gamma.pickle', 'rb') as handle:
            self.gamma_db = pickle.load(handle)

        with open('beta.pickle', 'rb') as handle:
            self.beta_db = pickle.load(handle)

        with open('alpha.pickle', 'rb') as handle:
            self.alpha_db = pickle.load(handle)

        # this data includes A, Z, name, half-life, and abundance of each isotope attached to each reference
        with open('parents.pickle', 'rb') as handle:
            self.parents1 = pickle.load(handle)

        # this data includes the decay mode and branching ratio attached to each reference
        with open('parents2.pickle', 'rb') as handle:
            self.parents2 = pickle.load(handle)

        with open('xray.pickle', 'rb') as handle:
            self.xray_db = pickle.load(handle)

        self.y_rads = []  # gamma
        self.b_rads = []  # beta
        self.a_rads = []  # alpha
        self.x_rads = []  #x-ray

        self.y_I = []  # gamma intensity
        self.b_I = []  # beta intensity
        self.a_I = []  # alpha intensity
        self.x_level = []  #orbital shell

        self.iso = []
        self.hl = []
        self.act = []

        self.title("Table of Radioactive Isotopes Lookup")
        self.geometry("470x370")
        self.resizable(width=False, height=False)
        self.configure(background="Gray")
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # ---------Tabs----------------------------------------------

        self.notebook = Notebook(self)

        self.tori_tab = tk.Frame(self.notebook)
        self.conversion_tab = tk.Frame(self.notebook)
        self.decay_tab = tk.Frame(self.notebook)
        self.xray_tab = tk.Frame(self.notebook)

        self.notebook.add(self.tori_tab, text='TORI')
        self.notebook.add(self.xray_tab, text='X-rays')
        self.notebook.add(self.decay_tab, text='Decay')
        self.notebook.add(self.conversion_tab, text='Conversion')

        # -------TORI TAB--------------------------------------------

        # Row 0
        # Create Frame 0
        self.frame_zero = tk.Frame(self.tori_tab, bd=3, relief=tk.RIDGE)
        self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW)

        self.isotope_input_label = tk.Label(self.frame_zero, text="Isotope:")
        self.isotope_input_label2 = tk.Label(
            self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)")
        self.isotope_input = tk.Text(self.frame_zero, height=1, width=20)

        self.isotope_input_label.grid(row=0, column=0, sticky=tk.NSEW)
        self.isotope_input_label2.grid(row=0,
                                       column=2,
                                       rowspan=2,
                                       sticky=tk.NSEW)
        self.isotope_input.grid(row=0, column=1, sticky=tk.NSEW)

        # Row 1
        # Create Frame 1
        self.frame_one = tk.Frame(self.tori_tab)
        self.frame_one.grid(row=1, column=0, sticky=tk.NSEW)

        self.search_button = tk.Button(self.frame_one, text="Search")
        self.search_button.grid(row=0, column=0, sticky=tk.NSEW)
        self.print_button = tk.Button(self.frame_one, text="Print Data")
        self.print_button.grid(row=0, column=1, sticky=tk.NSEW)

        # Row 2
        # Create Frame 2
        self.frame_two = tk.Frame(self.tori_tab)
        self.frame_two.grid(row=2, column=0, sticky=tk.NSEW)

        self.gamma_label = tk.Label(self.frame_two,
                                    text="Gamma-Rays",
                                    width=20,
                                    relief=tk.RIDGE,
                                    padx=2)
        self.beta_label = tk.Label(self.frame_two,
                                   text="Beta Particles",
                                   width=20,
                                   relief=tk.RIDGE,
                                   padx=2)
        self.alpha_label = tk.Label(self.frame_two,
                                    text="Alpha Particles",
                                    width=20,
                                    relief=tk.RIDGE,
                                    padx=3)

        self.gamma_label.grid(row=0, column=0, columnspan=2, sticky=tk.NSEW)
        self.beta_label.grid(row=0, column=2, columnspan=2, sticky=tk.NSEW)
        self.alpha_label.grid(row=0, column=4, columnspan=2, sticky=tk.NSEW)

        # Row 3
        # Create Frame 3
        self.frame_three = tk.Frame(self.tori_tab)
        self.frame_three.grid(row=3, column=0, sticky=tk.NSEW)

        for i in range(6):
            energy_label = tk.Label(self.frame_three,
                                    text="Energy (keV)",
                                    width=10,
                                    bd=3,
                                    relief=tk.RIDGE)
            I_label = tk.Label(self.frame_three,
                               text="Intensity %",
                               width=9,
                               bd=3,
                               relief=tk.RIDGE)
            if i % 2 == 0:
                energy_label.grid(row=3, column=i, sticky="E")
                I_label.grid(row=3, column=i + 1, sticky="E")

        # Row 4
        # Create Frame 4
        self.frame_four = tk.Frame(self.tori_tab)
        self.frame_four.grid(row=4, column=0, sticky=tk.NSEW)

        self.canvas = tk.Canvas(self.frame_four,
                                width=439,
                                height=200,
                                bd=3,
                                relief=tk.RIDGE)  # parent canvas to frame four
        self.canvas.grid(row=0, column=0, sticky=tk.NSEW)

        self.vsbar = tk.Scrollbar(
            self.frame_four, orient=tk.VERTICAL,
            command=self.canvas.yview)  # create scroll bar to frame four
        self.vsbar.grid(row=0, column=1, sticky=tk.NSEW)
        self.canvas.configure(
            yscrollcommand=self.vsbar.set
        )  # configure canvas to respond to scrollbar object

        self.radiations_frame = tk.Frame(
            self.canvas, bd=3,
            relief=tk.RIDGE)  # Create frame for radiations to be inserted onto

        self.canvas.create_window(
            (0, 0), window=self.radiations_frame,
            anchor=tk.NW)  # create window with radiations frame
        self.radiations_frame.update_idletasks()  # acquire bbox
        self.canvas.configure(scrollregion=self.canvas.bbox(
            tk.ALL))  # configure the canvas to scroll

        # -------CONVERSION TAB--------------------------------------------

        self.start_var = tk.StringVar()
        self.end_var = tk.StringVar()

        # Row 0
        self.frame_zero = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE)
        self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW)

        self.curies_start = tk.Radiobutton(self.frame_zero,
                                           text='curies',
                                           variable=self.start_var,
                                           value='curies',
                                           tristatevalue=0)
        self.millicuries_start = tk.Radiobutton(self.frame_zero,
                                                text='millicuries',
                                                variable=self.start_var,
                                                value='millicuries',
                                                tristatevalue=0)
        self.microcuries_start = tk.Radiobutton(self.frame_zero,
                                                text='microcuries',
                                                variable=self.start_var,
                                                value='microcuries',
                                                tristatevalue=0)
        self.nanocuries_start = tk.Radiobutton(self.frame_zero,
                                               text='nanocuries',
                                               variable=self.start_var,
                                               value='nanocuries',
                                               tristatevalue=0)
        self.bq_start = tk.Radiobutton(self.frame_zero,
                                       text='Bq',
                                       variable=self.start_var,
                                       value='bq',
                                       tristatevalue=0)
        self.kbq_start = tk.Radiobutton(self.frame_zero,
                                        text='KBq',
                                        variable=self.start_var,
                                        value='kbq',
                                        tristatevalue=0)
        self.mbq_start = tk.Radiobutton(self.frame_zero,
                                        text='MBq',
                                        variable=self.start_var,
                                        value='mbq',
                                        tristatevalue=0)
        self.gbq_start = tk.Radiobutton(self.frame_zero,
                                        text='GBq',
                                        variable=self.start_var,
                                        value='gbq',
                                        tristatevalue=0)
        self.tbq_start = tk.Radiobutton(self.frame_zero,
                                        text='TBq',
                                        variable=self.start_var,
                                        value='tbq',
                                        tristatevalue=0)

        self.buffer = tk.Label(self.frame_zero, text="TO", padx=35)

        self.curies_end = tk.Radiobutton(self.frame_zero,
                                         text='curies',
                                         variable=self.end_var,
                                         value='curies',
                                         tristatevalue=0)
        self.millicuries_end = tk.Radiobutton(self.frame_zero,
                                              text='millicuries',
                                              variable=self.end_var,
                                              value='millicuries',
                                              tristatevalue=0)
        self.microcuries_end = tk.Radiobutton(self.frame_zero,
                                              text='microcuries',
                                              variable=self.end_var,
                                              value='microcuries',
                                              tristatevalue=0)
        self.nanocuries_end = tk.Radiobutton(self.frame_zero,
                                             text='nanocuries',
                                             variable=self.end_var,
                                             value='nanocuries',
                                             tristatevalue=0)
        self.bq_end = tk.Radiobutton(self.frame_zero,
                                     text='Bq',
                                     variable=self.end_var,
                                     value='bq',
                                     tristatevalue=0)
        self.kbq_end = tk.Radiobutton(self.frame_zero,
                                      text='KBq',
                                      variable=self.end_var,
                                      value='kbq',
                                      tristatevalue=0)
        self.mbq_end = tk.Radiobutton(self.frame_zero,
                                      text='MBq',
                                      variable=self.end_var,
                                      value='mbq',
                                      tristatevalue=0)
        self.gbq_end = tk.Radiobutton(self.frame_zero,
                                      text='GBq',
                                      variable=self.end_var,
                                      value='gbq',
                                      tristatevalue=0)
        self.tbq_end = tk.Radiobutton(self.frame_zero,
                                      text='TBq',
                                      variable=self.end_var,
                                      value='tbq',
                                      tristatevalue=0)

        self.curies_start.grid(row=0, column=0, sticky=tk.W)
        self.millicuries_start.grid(row=1, column=0, sticky=tk.W)
        self.microcuries_start.grid(row=2, column=0, sticky=tk.W)
        self.nanocuries_start.grid(row=3, column=0, sticky=tk.W)
        self.bq_start.grid(row=4, column=0, sticky=tk.W)
        self.kbq_start.grid(row=5, column=0, sticky=tk.W)
        self.mbq_start.grid(row=6, column=0, sticky=tk.W)
        self.gbq_start.grid(row=7, column=0, sticky=tk.W)
        self.tbq_start.grid(row=8, column=0, sticky=tk.W)

        self.buffer.grid(row=0, column=1, rowspan=9, sticky=tk.W)

        self.curies_end.grid(row=0, column=2, sticky=tk.W)
        self.millicuries_end.grid(row=1, column=2, sticky=tk.W)
        self.microcuries_end.grid(row=2, column=2, sticky=tk.W)
        self.nanocuries_end.grid(row=3, column=2, sticky=tk.W)
        self.bq_end.grid(row=4, column=2, sticky=tk.W)
        self.kbq_end.grid(row=5, column=2, sticky=tk.W)
        self.mbq_end.grid(row=6, column=2, sticky=tk.W)
        self.gbq_end.grid(row=7, column=2, sticky=tk.W)
        self.tbq_end.grid(row=8, column=2, sticky=tk.W)

        # Row 1
        self.frame_one = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE)
        self.frame_one.grid(row=1, column=0, sticky=tk.NSEW)

        self.calc_conv_button = tk.Button(self.frame_one, text="Calculate")

        self.calc_conv_button.grid(row=0, column=0, sticky=tk.NSEW)

        # Row 2
        self.frame_two = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE)
        self.frame_two.grid(row=2, column=0, sticky=tk.NSEW)

        self.start_entry = tk.Text(self.frame_two, height=1, width=20)
        self.start_entry_label = tk.Label(self.frame_two, text="Start Value:")

        self.start_entry_label.grid(row=0, column=0, sticky=tk.NSEW)
        self.start_entry.grid(row=0, column=1, sticky=tk.NSEW)

        # Row 3
        self.frame_three = tk.Frame(self.conversion_tab, bd=3, relief=tk.RIDGE)
        self.frame_three.grid(row=3, column=0, sticky=tk.NSEW)

        self.end_entry_label = tk.Label(self.frame_three, text="End Value:")
        self.end_entry_label.grid(row=0, column=0)

        # -------DECAY TAB--------------------------------------------

        # Row 0
        self.frame_zero = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW)

        self.iso_input_label = tk.Label(self.frame_zero, text="Isotope:")
        self.iso_input_label2 = tk.Label(
            self.frame_zero, text="(Ex: Cs-137, cs137,cesium-137, cesium137)")
        self.iso_input = tk.Text(self.frame_zero, height=1, width=20)

        self.iso_input_label.grid(row=0, column=0, sticky=tk.NSEW)
        self.iso_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW)
        self.iso_input.grid(row=0, column=1, sticky=tk.NSEW)

        option_list = ('cpm', 'dpm', 'pCi', 'nCi', 'uCi', 'mCi', 'Ci', 'Bq',
                       'kBq', 'MBq', 'GBq', 'TBq')
        self.v = tk.StringVar()
        self.v.set(option_list[0])

        # Row 1
        self.frame_one = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_one.grid(row=1, column=0, sticky=tk.NSEW)

        self.orig_act = tk.Label(self.frame_one,
                                 text="Enter Original Activity:")
        self.orig_act_input = tk.Text(self.frame_one, height=1, width=20)
        self.dropdown = tk.OptionMenu(self.frame_one, self.v, *option_list)
        self.decay_button = tk.Button(self.frame_one, text="Calculate")

        self.orig_act.grid(row=0, column=0)
        self.orig_act_input.grid(row=0, column=1)
        self.dropdown.grid(row=0, column=2)
        self.decay_button.grid(row=0, column=3, sticky=tk.NSEW)

        # Row 2
        self.frame_two = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_two.grid(row=2, column=0, sticky=tk.NSEW)

        self.start_date_label = tk.Label(
            self.frame_two, text="Enter Original Date(MM/DD/YYYY):")
        self.start_date_input = tk.Text(self.frame_two, height=1, width=20)

        self.start_date_label.grid(row=0, column=0)
        self.start_date_input.grid(row=0, column=1)

        # Row 3
        self.frame_three = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_three.grid(row=3, column=0, sticky=tk.NSEW)

        self.end_date_label = tk.Label(self.frame_three,
                                       text="Enter End Date (MM/DD/YYYY):")
        self.end_date_input = tk.Text(self.frame_three, height=1, width=20)

        self.end_date_label.grid(row=0, column=0)
        self.end_date_input.grid(row=0, column=1)

        # Row 4
        self.frame_four = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_four.grid(row=4, column=0, sticky=tk.NSEW)

        self.iso_label = tk.Label(self.frame_four, text="Isotope:")

        self.iso_label.grid(row=0, column=0)

        # Row 5
        self.frame_five = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_five.grid(row=5, column=0, sticky=tk.NSEW)

        self.half_life_label = tk.Label(self.frame_five, text="Half-life:")

        self.half_life_label.grid(row=0, column=0)

        # Row 6
        self.frame_six = tk.Frame(self.decay_tab, bd=3, relief=tk.RIDGE)
        self.frame_six.grid(row=6, column=0, sticky=tk.NSEW)

        self.end_act_label = tk.Label(self.frame_six, text="Decayed Activity:")

        self.end_act_label.grid(row=0, column=0)

        # -------X-RAY TAB--------------------------------------------

        # Row 0
        self.frame_zero = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE)
        self.frame_zero.grid(row=0, column=0, sticky=tk.NSEW)

        self.ele_input_label = tk.Label(self.frame_zero, text="Element:")
        self.ele_input_label2 = tk.Label(self.frame_zero,
                                         text="(Ex: Cs, cs, cesium)")
        self.ele_input = tk.Text(self.frame_zero, height=1, width=20)
        self.xray_search_button = tk.Button(self.frame_zero, text='Search')

        self.ele_input_label.grid(row=0, column=0, sticky=tk.NSEW)
        self.ele_input_label2.grid(row=0, column=2, rowspan=2, sticky=tk.NSEW)
        self.ele_input.grid(row=0, column=1, sticky=tk.NSEW)
        self.xray_search_button.grid(row=0, column=3)

        # Row 1
        self.frame_one = tk.Frame(self.xray_tab, bd=3, relief=tk.RIDGE)
        self.frame_one.grid(row=1, column=0, sticky=tk.NSEW)

        self.x_label1 = tk.Label(self.frame_one,
                                 text="Energy (keV)",
                                 width=15,
                                 bd=3,
                                 relief=tk.RIDGE)
        self.x_label2 = tk.Label(self.frame_one,
                                 text="Orbital Shell",
                                 width=15,
                                 bd=3,
                                 relief=tk.RIDGE)

        self.x_label1.grid(row=0, column=0)
        self.x_label2.grid(row=0, column=1)

        # Row 2
        self.frame_twox = tk.Frame(self.xray_tab)
        self.frame_twox.grid(row=2, column=0, sticky=tk.NSEW)

        self.x_canvas = tk.Canvas(
            self.frame_twox, width=439, height=200, bd=3,
            relief=tk.RIDGE)  # parent canvas to frame four
        self.x_canvas.grid(row=0, column=0)

        self.x_vsbar = tk.Scrollbar(
            self.frame_twox, orient=tk.VERTICAL,
            command=self.x_canvas.yview)  # create scroll bar to frame four
        self.x_vsbar.grid(row=0, column=1, sticky=tk.NS)
        self.x_canvas.configure(
            yscrollcommand=self.x_vsbar.set
        )  # configure canvas to respond to scrollbar object

        self.x_frame = tk.Frame(
            self.x_canvas, bd=3,
            relief=tk.RIDGE)  # Create frame for radiations to be inserted onto

        self.x_canvas.create_window(
            (0, 0), window=self.x_frame,
            anchor=tk.NW)  # create window with radiations frame
        self.x_frame.update_idletasks()  # acquire bbox
        self.x_canvas.configure(scrollregion=self.x_canvas.bbox(
            tk.ALL))  # configure the canvas to scroll

        self.testlabel = tk.Label(self.x_frame, text='TEST')
        self.testlabel.grid(row=0, column=0)
        #---------Binds---------------------------------------------

        self.bind_all("<MouseWheel>", self.mouse_scroll)

        # TORI TAB
        self.search_button.bind(
            "<Button-1>",
            lambda foo: self.TORI_search(self, self.isotope_input))
        self.print_button.bind("<Button-1>", self.print_data)
        self.isotope_input.bind(
            "<Return>", lambda foo: self.TORI_search(self, self.isotope_input))

        # CONVERSION TAB
        self.calc_conv_button.bind("<Button-1>", self.calculate_conversion)
        self.start_entry.bind("<Return>", self.calculate_conversion)

        # DECAY TAB
        self.decay_button.bind("<Button-1>", self.calculate_decay)
        self.iso_input.bind("<Return>", self.calculate_decay)

        # XRAY TAB
        self.xray_search_button.bind("<Button-1>", self.search_xrays)
        self.ele_input.bind("<Return>", self.search_xrays)

        # ---------Notebook------------------------------------------

        self.notebook.pack(fill=tk.BOTH, expand=1)


# ---------Functions-----------------------------------------

    def search_xrays(self, event=None):
        element = (self.ele_input.get(1.0, tk.END).strip('\n')).lower()
        self.ele_input.delete(1.0, tk.END)
        element = element[:1].upper() + element[1:]
        try:
            Z = nuclides[element]
        except KeyError:
            try:
                Z = nuclides_long[element]
            except KeyError:
                msg.askokcancel("Confirm", "Please enter a valid element")

        ref = str(Z) + '0000'

        # clear any existing radiation labels
        for xr in self.x_rads:
            xr.destroy()
        for lvl in self.x_level:
            lvl.destroy()
        self.x_rads = []
        self.x_level = []

        row = 0
        for i in range(int(len(self.xray_db[ref]) / 2)):
            new_x = tk.Label(self.x_frame,
                             text=self.xray_db[ref]['xray' + str(i + 1)],
                             width=15)
            new_level = tk.Label(self.x_frame,
                                 text=self.xray_db[ref]['level' + str(i + 1)],
                                 width=15)

            new_x.grid(row=row, column=0)
            new_level.grid(row=row, column=1)

            self.x_rads.append(new_x)
            self.x_level.append(new_level)

            row += 1

        # reconfigure canvas with updated radiations_frame
        self.x_canvas.create_window((0, 0), window=self.x_frame, anchor=tk.NW)
        self.x_frame.update_idletasks()
        self.x_canvas.configure(scrollregion=self.x_canvas.bbox(tk.ALL))

    # Function used to calculate decay from start to end date with original activity
    # ----------------------------------------------------
    def calculate_decay(self, event=None):
        unit_list = ['ns', 'us', 'ms', 's', 'm', 'd', 'y']
        unit_conv_list = [
            1.16e-14, 1.16e-11, 1.15e-8, 1.16e-5, 6.94e-4, 1, 365
        ]

        # Get activity input
        try:
            act = float(self.orig_act_input.get(1.0, tk.END).strip('\n'))
            test = False
        except ValueError:
            msg.askokcancel("Confirm", "Please enter a valid activity")

        #return time in days
        t = self.get_time(self, self.start_date_input, self.end_date_input)

        #translate isotope input
        isotope, A = self.search(self, self.iso_input)
        ref = self.translate_isotope(isotope, A)

        #delete any isotope values on screen and put new value on screen
        for i in self.iso:
            i.destroy()
        self.iso = []
        iso = tk.Label(self.frame_four, text=isotope + "-" + A)
        iso.grid(row=0, column=1)
        self.iso.append(iso)

        #acquire half-life of isotope input
        halflife = self.parents1[ref]['halflife']

        #delete any halflife values on screen and put new value on screen
        for h in self.hl:
            h.destroy()
        self.hl = []
        half_life_label = tk.Label(self.frame_five, text=halflife)
        half_life_label.grid(row=0, column=1)
        self.hl.append(half_life_label)

        #split up num value and unit value of halflife
        for j in range(len(unit_list)):
            if unit_list[j] in halflife:
                halflife = halflife.replace(unit_list[j], "")
                hl_unit = unit_list[j]
                break

        #convert halflife unit to days and convert to decay constant
        halflife = float(halflife) * unit_conv_list[unit_list.index(hl_unit)]
        decay_constant = 0.693 / halflife  #d^-1

        #calculate decay factor and new activity after t passed

        try:
            decay_factor = math.exp(-decay_constant * t)
            new_act = decay_factor * act

            #delete any activity values ons creen and put new value on screen
            for a in self.act:
                a.destroy()
            self.act = []
            new_act_label = tk.Label(self.frame_six,
                                     text='{:.2e}'.format(new_act))
            new_act_label.grid(row=0, column=1)
            self.act.append(new_act_label)
        except (UnboundLocalError, TypeError):
            pass

    # Function used to calculate time difference between start and end date
    # ----------------------------------------------------
    def get_time(self, event=None, start=None, end=None):
        #acquire start and end date, take the difference, return time passed
        try:
            start_date = start.get(1.0, tk.END).strip('\n')
            start_date = start_date.split('/')
            t1 = dt.datetime(int(start_date[2]), int(start_date[1]),
                             int(start_date[0]))
        except IndexError:
            msg.askokcancel("Confirm", "Please enter a valid start date")

        try:
            end_date = end.get(1.0, tk.END).strip('\n')
            end_date = end_date.split('/')
            t2 = dt.datetime(int(end_date[2]), int(end_date[1]),
                             int(end_date[0]))
        except IndexError:
            msg.askokcancel("Confirm", "Please enter a valid end date")
        try:
            t = t2 - t1
            return t.days
        except UnboundLocalError:
            pass

    # Function used to calculate conversion from one unit to other
    # ----------------------------------------------------
    def calculate_conversion(self, event=None):
        units = [
            'curies', 'millicuries', 'microcuries', 'nanocuries', 'bq', 'kbq',
            'mbq', 'gbq', 'tbq'
        ]
        conv_list = [
            [1E0, 1E3, 1E6, 1E9, 3.7E10, 3.7E7, 3.7E4, 3.7E1, 3.7E-2],
            [1E-3, 1E0, 1E3, 1E6, 3.7E7, 3.7E4, 3.7E1, 3.7E-2, 3.7E-5],
            [1E-6, 1e-3, 1e0, 1e3, 3.7e4, 3.7e1, 3.7e-2, 3.7e-5, 3.7e-8],
            [1e-9, 1e-6, 1e-3, 1, 3.7e1, 3.7e-2, 3.7e-5, 3.7e-8, 3.7e-11],
            [2.7e-11, 2.7e-8, 2.7e-5, 2.7e-2, 1, 1e-3, 1e-6, 1e-9, 1e-12],
            [2.7e-8, 2.7e-5, 2.7e-2, 2.7e1, 1e3, 1, 1e-3, 1e-6, 1e-9],
            [2.7e-5, 2.7e-2, 2.7e1, 2.7e4, 1e6, 1e3, 1, 1e-3, 1e-6],
            [2.7e-2, 2.7e1, 2.7e4, 2.7e7, 1e9, 1e6, 1e3, 1, 1e-3],
            [2.7e1, 2.7e4, 2.7e7, 2.7e10, 1e12, 1e9, 1e6, 1e3, 1],
        ]

        start_unit = self.start_var.get()
        end_unit = self.end_var.get()

        val = int(self.start_entry.get(1.0, tk.END).strip('\n'))

        unit_num_start = units.index(start_unit)
        unit_num_end = units.index(end_unit)

        conversion = conv_list[unit_num_start][unit_num_end]
        val = val * conversion
        self.new_value = tk.Label(self.frame_three,
                                  text='{:.2e}'.format(val),
                                  width=10)
        self.new_value.grid(row=0, column=1)

    # Function used to translate user input and add radiations to GUI
    # ----------------------------------------------------
    def TORI_search(self, event=None, isotope_input=None):
        isotope, A = self.search(self, isotope_input)
        ref = self.translate_isotope(isotope, A)
        self.add_radiation(ref)

    # function used to acquire information from user input
    # passes input along to acquire radiation data from db
    # ----------------------------------------------------
    def search(self, event=None, isotope_input=None):
        # pull data from user input
        isotope = isotope_input.get(1.0, tk.END).strip('\n')
        test = False
        # Logic to acquire formatting of isotope and separate name from A
        try:
            count = 0
            A = ""
            # check all characters in isotope variable
            for char in isotope:
                try:
                    value = int(char)
                    A += char
                except ValueError:
                    if char != "-":
                        count += 1
            # check if someone entered in a metastable state
            # includes error checking for miss-types
            try:
                if isotope[-1:].lower() == 'm':
                    count -= 1
                    A += 'm'
                else:
                    value = int(isotope[-1:])
            except ValueError:
                msg.askokcancel("Confirm", "Please enter a nuclide")
                test = True
            # delete user input
            isotope_input.delete(1.0, tk.END)
            # if no errors with metastable entry, run
            if not test:
                isotope = isotope[:count]
                isotope = isotope[0].upper() + isotope[1:]
                return isotope, A
                self.isotope_print = isotope + A  # add to global variable so that print_data can access for file name
        except IndexError:
            # if a blank is entered, show this error message
            msg.askokcancel("Confirm", "Please enter a nuclide")

    # function used to translate user input to isotope reference number in database
    # passes reference number onto add_radiation() function
    # ----------------------------------------------------
    def translate_isotope(self, isotope=None, A=None):
        # test variable for error checking
        test = False
        try:
            # look up the Z from nuclides dictionary
            Z = str(nuclides[isotope])
        except KeyError:
            # if the isotope isnt in the first dictionary, try the second
            try:
                Z = nuclides_long[isotope]
            except KeyError:
                # if not in the second, user entered invalid isotope
                msg.askokcancel("Error",
                                "Valid Nuclide Not Entered:" + isotope)
                test = True
        # test to see if a metastable isotope was entered
        if not test:
            # if yes, add 300 to A and format appropriately
            if A[-1:] == 'm':
                A = str(int(A.replace('m', '')) + 300)
                ref = Z + "0" + A
            # if no, format appropriate according to # of decimal
            # places in A.
            else:
                if int(A) < 10:
                    A = "00" + A
                elif int(A) >= 10 and int(A) < 100:
                    A = "0" + A
                ref = Z + "0" + A
            try:
                return ref
            except UnboundLocalError:
                pass

    # Function used to translate a reference to isotope and atomic #
    # ----------------------------------------------------
    def translate_reference(self, ref=None):
        isotope = ref.replace(ref[-4:], "")
        tmp = ref[-3:]

        if tmp[:2] == '00':
            A = ref[-1:]
        elif tmp[:1] == '0':
            A = ref[-2:]
        else:
            A = ref[-3:]

        return nuclides_rev[int(isotope)], A

    # add radiations to main screen of all 3 types from isotope
    # ----------------------------------------------------
    def add_radiation(self, ref=None):

        # clear any existing radiation labels
        for rad in self.y_rads:
            rad.destroy()
        for i in self.y_I:
            i.destroy()
        self.y_rads = []
        self.y_I = []

        # clear any existing radiation labels
        for rad in self.b_rads:
            rad.destroy()
        for i in self.b_I:
            i.destroy()
        self.b_rads = []
        self.b_I = []

        # clear any existing radiation labels
        for rad in self.a_rads:
            rad.destroy()
        for i in self.a_I:
            i.destroy()
        self.a_rads = []
        self.a_I = []

        # add radiation energies of gamma rays
        count = 1
        row = 0
        try:
            r_num = int(len(self.gamma_db[ref]) /
                        2)  #determine number of radiations of each type
        except KeyError:
            pass
        if r_num != 0:
            for i in range(r_num):
                new_rad = tk.Label(self.radiations_frame,
                                   text=self.gamma_db[ref]['gamma' +
                                                           str(count)],
                                   width=10)
                new_rad_I = tk.Label(self.radiations_frame,
                                     text=self.gamma_db[ref]['I' + str(count)],
                                     width=9)

                new_rad.grid(row=row, column=0)
                new_rad_I.grid(row=row, column=1)

                self.y_rads.append(new_rad)
                self.y_I.append(new_rad_I)

                row += 1
                count += 1
        # if no radiations, add blank spaces to maintain width
        elif r_num == 0:
            new_rad = tk.Label(self.radiations_frame, text="", width=10)
            new_rad_I = tk.Label(self.radiations_frame, text="", width=9)
            new_rad.grid(row=0, column=0)
            new_rad_I.grid(row=0, column=1)
            self.y_rads.append(new_rad)
            self.y_I.append(new_rad_I)

        # add radiation energies of beta particles
        count = 1
        row = 0
        try:
            r_num = int(len(self.beta_db[ref]) /
                        2)  # determine number of radiations of each type
        except KeyError:
            pass
        if r_num != 0:
            for i in range(r_num):
                new_rad = tk.Label(self.radiations_frame,
                                   text=self.beta_db[ref]['beta' + str(count)],
                                   width=10)
                new_rad_I = tk.Label(self.radiations_frame,
                                     text=self.beta_db[ref]['I' + str(count)],
                                     width=9)

                new_rad.grid(row=row, column=2)
                new_rad_I.grid(row=row, column=3)

                self.b_rads.append(new_rad)
                self.b_I.append(new_rad_I)

                row += 1
                count += 1
        # if no radiations, add blank spaces to maintain width
        elif r_num == 0:
            new_rad = tk.Label(self.radiations_frame, text="", width=10)
            new_rad_I = tk.Label(self.radiations_frame, text="", width=9)
            new_rad.grid(row=0, column=2)
            new_rad_I.grid(row=0, column=3)
            self.b_rads.append(new_rad)
            self.b_I.append(new_rad_I)

        # add radiation energies of alpha particles
        count = 1
        row = 0
        try:
            r_num = int(len(self.alpha_db[ref]) /
                        2)  # determine number of radiations of each type
        except KeyError:
            pass
        if r_num != 0:
            for i in range(r_num):
                new_rad = tk.Label(self.radiations_frame,
                                   text=self.alpha_db[ref]['alpha' +
                                                           str(count)],
                                   width=10)
                new_rad_I = tk.Label(self.radiations_frame,
                                     text=self.alpha_db[ref]['I' + str(count)],
                                     width=9)

                new_rad.grid(row=row, column=4)
                new_rad_I.grid(row=row, column=5)

                self.a_rads.append(new_rad)
                self.a_I.append(new_rad_I)

                row += 1
                count += 1
        # if no radiations, add blank spaces to maintain width
        elif r_num == 0:
            new_rad = tk.Label(self.radiations_frame, text="", width=10)
            new_rad_I = tk.Label(self.radiations_frame, text="", width=9)
            new_rad.grid(row=0, column=4)
            new_rad_I.grid(row=0, column=5)
            self.a_rads.append(new_rad)
            self.a_I.append(new_rad_I)

        # reconfigure canvas with updated radiations_frame
        self.canvas.create_window((0, 0),
                                  window=self.radiations_frame,
                                  anchor=tk.NW)
        self.radiations_frame.update_idletasks()
        self.canvas.configure(scrollregion=self.canvas.bbox(tk.ALL))

    # Print all data
    # ----------------------------------------------------
    def print_data(self, event=None):

        # Get data from labels in GUI to temporary lists
        ytmp = []
        btmp = []
        atmp = []
        for i in range(len(self.y_rads)):
            new = []
            new.append(self.y_rads[i].cget("text"))
            new.append(self.y_I[i].cget("text"))
            ytmp.append(new)
        for i in range(len(self.b_rads)):
            new = []
            new.append(self.b_rads[i].cget("text"))
            new.append(self.b_I[i].cget("text"))
            btmp.append(new)
        for i in range(len(self.a_rads)):
            new = []
            new.append(self.a_rads[i].cget("text"))
            new.append(self.a_I[i].cget("text"))
            atmp.append(new)

        # compile all 3 lists into a single two dimensional list
        # 6 columns across, i rows down for largest # of radiations present
        outputlist = []
        for i in range(max(len(ytmp), len(btmp), len(atmp))):
            tmp = []
            try:
                if str(ytmp[i][0]) != "":
                    tmp.append(str(ytmp[i][0]))
                    tmp.append(str(ytmp[i][1]))
            except IndexError:
                pass
            try:
                if str(btmp[i][0]) != "":
                    tmp.append(str(btmp[i][0]))
                    tmp.append(str(btmp[i][1]))
            except IndexError:
                pass
            try:
                if str(atmp[i][0]) != "":
                    tmp.append(str(atmp[i][0]))
                    tmp.append(str(atmp[i][1]))
            except IndexError:
                pass
            outputlist.append(tmp)

        # print data to a text file
        try:
            with open(self.isotope_print + '.txt', 'w') as f:
                f.write('Gamma-Rays' + ',' + '' + ',' + 'Beta-Particles' +
                        ',' + '' + ',' + 'Alpha-Particles' + '\n')
                f.write('Energy(keV)' + ',' + 'Intensity%' + ',' +
                        'Energy(keV)' + ',' + 'Intensity%' + ',' +
                        'Energy(keV)' + ',' + 'Intensity%' + '\n')
                for line in outputlist:
                    for i in range(len(line)):
                        if i != len(line) - 1:
                            f.write(line[i] + ",")
                        else:
                            f.write(line[i])
                    f.write('\n')
        except AttributeError:
            pass

    # allow the use of the mouse wheel to scroll
    # ----------------------------------------------------
    def mouse_scroll(self, event):
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
Ejemplo n.º 17
0
filenameLabel.pack(side=LEFT)
selectFileButton = Button(fileFrame, text = 'Select File', command = load_file)
selectFileButton.pack(side=RIGHT, padx=5)


bodyFrame = Frame(root, width = 600, height=400)
bodyFrame.pack(expand=True, fill=X, padx=10, anchor=W)

view3DFrame = Frame(width=300, height=300)
viewLayerFrame = LayerPreview(root, width=300, height=300)


viewFrame = Notebook(bodyFrame)
#viewFrame.add(view3DFrame, text="3D View")
viewFrame.add(viewLayerFrame, text="Layer View")
viewFrame.pack(expand=True, side=LEFT, anchor=NW)



settingsFrame = Notebook(bodyFrame)
settingsFrame.pack(expand=True, side=LEFT, anchor=NW)

setupFrame = Frame()
setupFrame.pack(padx=10, pady=10)

printerFrame = Frame(setupFrame)
printerFrame.pack(side=TOP)

zMoveFrame = ZMove(printerFrame)
zMoveFrame.pack(side=RIGHT, anchor=E, padx=(50, 0))
Ejemplo n.º 18
0
class DelimitedPy(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title('DelimitedPy v{appVersion}'.format(appVersion=appVersion))
        self.geometry('500x500')

        # NOTEBOOK
        self.notebook = Notebook(self)

        # FRAME - tabStart
        tabStart = tk.Frame(self.notebook)

        # BUTTON - btnSelectSource
        self.btnSelectSource = tk.Button(tabStart,
                                         text='Select Source',
                                         command=self.clicked_btnSelectSource)
        self.btnSelectSource.pack(side=tk.BOTTOM, fill=tk.X)

        # BUTTON - btnContinue
        self.btnContinue = tk.Button(tabStart,
                                     text='Continue',
                                     command=self.clicked_btnContinue)
        self.btnContinue.configure(state='disabled')
        # self.btnContinue.pack(side=tk.RIGHT, fill=tk.X)
        # self.btnContinue.pack(side=tk.RIGHT, fill=tk.NONE, expand=0)

        # STRINGVAR - varUserFile
        self.varUserFile = tk.StringVar(tabStart)
        self.varUserFile.set('Click the "Select Source" button below.')

        # LABEL - lblUserFilePath
        self.lblUserFilePath = tk.Label(tabStart,
                                        textvar=self.varUserFile,
                                        bg='lightgrey',
                                        fg='black')
        self.lblUserFilePath.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        # ADD FRAMES to NOTEBOOK
        self.notebook.add(tabStart, text='Start Page')

        # PACK NOTEBOOK
        self.notebook.pack(fill=tk.BOTH, expand=1)

    # def translate(self, target_language='it', text=None):
    # if not text:
    #     text = self.english_entry.get(1.0, tk.END)

    # url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}'.format('en', target_language, text)

    # try:
    #     r = requests.get(url)
    #     r.raise_for_status()
    #     translation = r.json()[0][0][0]
    #     self.italian_translation.set(translation)
    #     msg.showinfo('Translation Successful', 'Text successfully translated')
    # except Exception as e:
    #     msg.showerror('Translation Failed', str(e))
    def clicked_btnSelectSource(self):
        # print('clicked_btnSelectSource')

        # Ask for delimited file.
        fileName = filedialog.askopenfilename(initialdir='./',
                                              title="Select a delimited file",
                                              filetypes=(('text files',
                                                          '*.txt *.csv'),
                                                         ('all files', '*.*')))

        # Check that a file has been selected.

        # Update the StringVariable to update the label to be the path of the file.
        self.varUserFile.set(str(fileName))

        # Enable the Continue Button
        self.btnContinue.configure(state='active')
        self.btnContinue.pack(side=tk.RIGHT, fill=tk.X)
        self.notebook.pack(fill=tk.BOTH, expand=1)

    def clicked_btnContinue(self):
        pass
        print('clicked_btnContinue ran.')

    def copy_to_clipboard(self, text=None):
        print('copy_to_clipboard ran')
Ejemplo n.º 19
0
class LpoViewer(Frame):
    """ This class implements the window of the Lpo viewer.

    This class implements a menu and tab management for the LpoView.
    """
    
    def __init__(self, parent):
        """ Create new window. """
        Frame.__init__(self, parent)
        self.__parent = parent
        self.__initUI()

    def __initUI(self):
        """ Set up UI. """
        self.pack(fill=BOTH, expand=1)
        # notebook for LpoView tabs
        self.__notebook = Notebook(self)
        self.__notebook.pack(fill=BOTH, expand=1)
        # menu bar with file menu
        self.__menubar = Menu(self.__parent)
        self.__parent.config(menu=self.__menubar)

        self.__filemenu = Menu(self.__menubar, tearoff=0)
        self.__filemenu.add_command(label="Open", command=self.__onOpen)
        self.__filemenu.add_command(label="Close", command=self.__onClose)
        self.__filemenu.add_command(label="Exit", command=self.__onExit)
        self.__menubar.add_cascade(label="File", menu=self.__filemenu)
        # size and title
        self.__parent.geometry("300x300+300+300")
        self.__parent.title("Lpo viewer Tk")

    def __onExit(self):
        """ Close the app. """
        self.__parent.withdraw()
        self.quit()

    def __onClose(self):
        """ Close the selected LPO. """
        tab = self.__notebook.select()
        if tab != '':
            self.__notebook.forget(tab)
        

    def __onOpen(self):
        """ Open a new LPO (with file chooser). """
        ftypes = [('LPO files', '*.lpo'), ('All files', '*')]
        dialog = filedialog.Open(self, filetypes=ftypes)
        file = dialog.show()

        if file != '':
            self.openLpo(file)

    def openLpo(self, file):
        """ This method shows the LPO contained in the given file as new tab. """
        lpos = partialorder.parse_lpo_file(file) # parse LPO from file
        print(lpos[0])
        self.showLpo(lpos[0]) # show first lpo (Assumption: Only 1 LPO in a file)
    
    def showLpo(self, lpo):
        """ Show the given LPO in a new tab. """
        lpo_view = LpoView(self.__notebook)
        self.__notebook.add(lpo_view, text=lpo.name, sticky="nswe")
        lpo_view.showLpo(lpo)
Ejemplo n.º 20
0
from tkinter import *
from tkinter.ttk import Notebook

from views.AdjacencyListGraph import AdjacencyListGraph
from views.SimpleFormAdd import AddGraphSimpleFormViewCreator
from views.AdjacencyMatrixGraph import AdjacencyMatrixGraph
from views.IncidenceMatrixGraph import IncidenceMatrixGraph

if __name__ == '__main__':
    root = Tk()
    notebook = Notebook(root)

    frame1 = Frame(notebook)
    frame2 = Frame(notebook)
    frame3 = Frame(notebook)
    frame4 = Frame(notebook)

    notebook.add(frame1, text='Simple form')
    notebook.add(frame2, text='Adjacency Matrix Graph')
    notebook.add(frame3, text='Incidence Matrix Graph')
    notebook.add(frame4, text='Adjacency List Graph')
    notebook.pack()

    AddGraphSimpleFormViewCreator(frame1)
    AdjacencyMatrixGraph(frame2)
    IncidenceMatrixGraph(frame3)
    AdjacencyListGraph(frame4)

    root.mainloop()
Ejemplo n.º 21
0
    def __init__(self):
        Tk.__init__(self)

        pwd = os.path.dirname(__file__)

        # ico = PhotoImage(file=os.path.join(pwd, "icon.png"))
        # self.call('wm', 'iconphoto', self._w, ico)

        self.title("Spectacuplot!")

        left_frame = Frame(self)

        control_frame = Frame(left_frame)
        left_frame.pack(side=LEFT, fill=Y)
        control_frame.pack(anchor=N,fill=BOTH,expand=1)

        # Menu bar
        mb = Menu(self)
        file_menu = Menu(mb)
        file_menu.add_command(label='Open...', command=self.open_dialog,
                              accelerator='Ctrl-O')
        file_menu.add_command(label='Close All Files', command=self.close_files)

        # Get recent files
        self.recent = []
        self.recent_commands = []
        try:
            recent_files = open(os.path.expanduser("~/spectacuplot_recent"), "r")
            for f in recent_files:
                self.recent.append(f.strip())
                self.recent_commands.append(functools.partial(self.open, f.strip()))
            recent_files.close()
        except:
            print("no recent files")

        self.recent_cascade = Menu(file_menu)

        for (f, c) in zip(self.recent, self.recent_commands):
            self.recent_cascade.add_command(label=f, command=c)

        file_menu.add_cascade(label="Recent Files", menu=self.recent_cascade)

        # Set up stuff for quitting Spectacuplot
        file_menu.add_command(label='Exit', command=self.quit)
        self.protocol("WM_DELETE_WINDOW", self.quit)

        self.bind_all("<Control-o>", self.open_dialog)

        self.config(menu=mb)

        mb.add_cascade(label="File", menu=file_menu)


        # Notebook
        nb = Notebook(control_frame, name="controls")
        nb.enable_traversal()
        nb.pack(expand=1, fill=BOTH)

        # Plot Area
        self.plot_frame = PlotArea(self)
        self.plot_frame.pack(side=LEFT, fill=BOTH, expand=1)

        # This will be used as the notbook tab for plotting individual datasets
        self.plot_set_tab = OpSetPlot(nb, self.opened_files, self.plot_frame)

        # This will be used as the notebook tab for plotting dataset diffs
        self.diff_tab = OpDiffPlot(nb, self.opened_files, self.plot_frame)

        nb.add(self.plot_set_tab, text="Plot Set")
        nb.add(self.diff_tab, text="Diff Sets")
Ejemplo n.º 22
0
class CimApp(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.file = None;
        self.master.title("Tiborcim")
        self.master.iconphoto(True, PhotoImage(file=ICON_PNG))
        self.files = []
        self.current_tab = StringVar()
        self.pack(expand=1, fill="both")
        self.master.minsize(300,300)
        self.master.geometry("500x500")

        self.menubar = Menu(self.master)
        self.fileMenu = Menu(self.master, tearoff=0)
        self.fileMenu.add_command(label="New", command=self.new_file,
                                  underline=0, accelerator="Ctrl+N")
        self.fileMenu.add_command(label="Open...", command=self.load_file,
                                  underline=0, accelerator="Ctrl+O")
        self.fileMenu.add_command(label="Save", command=self.file_save,
                                  underline=0, accelerator="Ctrl+S")
        self.fileMenu.add_command(label="Save As...", command=self.file_save_as,
                                  underline=5, accelerator="Ctrl+Alt+S")
        self.fileMenu.add_command(label="Close", command=self.close_file,
                                  underline=0, accelerator="Ctrl+W")
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=self.file_quit, underline=1)
        self.menubar.add_cascade(label="File", menu=self.fileMenu, underline=0)

        self.edit_program = Menu(self.master, tearoff=0)
        self.edit_program.add_command(label="Undo", command=self.edit_undo,
                                  underline=0, accelerator="Ctrl+Z")
        self.edit_program.add_command(label="Redo", command=self.edit_redo,
                                      underline=0, accelerator="Ctrl+Y")
        self.edit_program.add_separator()
        self.edit_program.add_command(label="Cut",
                                      command=self.edit_cut,
                                      underline=2,
                                      accelerator="Ctrl+X")
        self.edit_program.add_command(label="Copy",
                                      command=self.edit_copy,
                                      underline=0,
                                      accelerator="Ctrl+C")
        self.edit_program.add_command(label="Paste",
                                      command=self.edit_paste,
                                      underline=0,
                                      accelerator="Ctrl+V")
        self.menubar.add_cascade(label="Edit", menu=self.edit_program, underline=0)

        self.menu_program = Menu(self.master, tearoff=0)
        self.menu_program.add_command(label="Convert",
                                      command=self.convert_file,
                                      underline=0,
                                      accelerator="Ctrl+T")
        self.menu_program.add_command(label="Flash",
                                      command=self.flash_file,
                                      underline=0,
                                      accelerator="Ctrl+B")
        self.menu_program.add_separator()
        self.menubar.add_cascade(label="Program", menu=self.menu_program, underline=0)

        self.menu_view = Menu(self.master,
                              tearoff=0)
        self.viewmode = StringVar()
        self.viewmode.set("tiborcim")
        self.menu_view.add_radiobutton(label="Tiborcim",
                                       command=self.view_tiborcim,
                                       variable=self.viewmode,
                                       value="tiborcim",
                                       underline=0)
        self.menu_view.add_radiobutton(label="Python",
                                       command=self.view_python,
                                       variable=self.viewmode,
                                       value="python",
                                       underline=0)
        self.menubar.add_cascade(label="View",
                                 menu=self.menu_view,
                                 underline=0)

        self.menu_help = Menu(self.master,
                              tearoff=0)
        
        self.menu_samples = Menu(self.master, tearoff=0)
        samples = tiborcim.resources.samples_list()
        def add_sample (sample):
            self.menu_samples.add_command(label=sample,
                                          command=lambda: self.help_sample(sample))
        for sample in samples:
            add_sample(sample)
    
        self.menu_help.add_cascade(label="Samples",
                                   menu=self.menu_samples,
                                   underline=0)
        self.menu_help.add_separator()
        self.menu_help.add_command(label="README",
                                   command=self.help_readme,
                                   underline=0)
        self.menu_help.add_separator()
        self.menu_help.add_command(label="About",
                                   command=self.help_about,
                                   underline=0)
        self.menubar.add_cascade(label="Help",
                                 menu=self.menu_help,
                                 underline=0)

        self.master.config(width=450,
                           height=400,
                           menu=self.menubar)

        self.bind_all("<Control-o>", self.load_file)
        self.bind_all("<Control-s>", self.file_save)
        self.bind_all("<Control-Alt-s>", self.file_save_as)
        self.bind_all("<Control-t>", self.convert_file)
        self.bind_all("<Control-b>", self.flash_file)
        self.bind_all("<Control-w>", self.close_file)
        self.master.protocol("WM_DELETE_WINDOW", self.file_quit)

        self.file_tabs = Notebook(self)
        self.file_tabs.bind_all("<<NotebookTabChanged>>", self.file_changed)
        self.file_tabs.pack(expand=1, fill="both")

    def file_changed(self, event):
        if len(self.file_tabs.tabs()) <= 0:
            self.add_file()
            return
        title = str(event.widget.tab(event.widget.index("current"),"text")).upper().strip()
        self.menu_program.delete(3, END)
        for tab in self.file_tabs.tabs():
            tabtext = self.file_tabs.tab(self.file_tabs.index(tab),"text")
            if tabtext.upper().strip() == title:
                self.current_tab.set(tab)        
            self.menu_program.add_radiobutton(label=tabtext, command=self.program_switch,
                                  underline=1, value=tab, variable=self.current_tab)
        if title != "PYTHON" or title != "TIBORCIM":
            if self.current_file().filename is not None:
                self.master.title(self.current_file().get_file() + " - Tiborcim")
            else:
                self.master.title("Tiborcim")
            if str(self.current_file().tab(self.current_file().index("current"),"text")).upper().strip() == "TIBORCIM":
                self.menubar.entryconfig("Edit", state=NORMAL)
            else:
                self.menubar.entryconfig("Edit", state=DISABLED)
            self.viewmode.set(self.current_file().viewmode)
        if title == "PYTHON":
            self.menubar.entryconfig("Edit", state=DISABLED)
            self.current_file().viewmode = "python";
            self.viewmode.set("python");
        if title == "TIBORCIM":
            self.menubar.entryconfig("Edit", state=NORMAL)
            self.current_file().viewmode = "tiborcim";
            self.viewmode.set("tiborcim");

    def add_file(self, file=None):
        filepage = CimFilePage(self.file_tabs)
        if file is None:
            self.file_tabs.add(filepage, text="Unsaved Program")
        else:
            filepage.load_file(file)
            self.file_tabs.add(filepage, text=filepage.get_file())
        self.files.append(filepage)
        self.file_tabs.select(filepage)

    def view_tiborcim(self, event=None):
        self.current_file().view_tiborcim()

    def view_python(self, event=None):
        self.current_file().view_python()

    def program_switch(self):
        self.file_tabs.select(self.current_tab.get())

    def new_file(self, event=None):
        self.add_file()

    def load_file(self, event=None):
        fname = askopenfilename(filetypes=(("Tiborcim", "*.tibas"),("All files", "*.*") ), parent=self.master)
        if fname:
            self.add_file(fname)

    def file_save(self, event=None):
        self.current_file().save_file()
        self.file_tabs.tab(self.current_file(), text=self.current_file().get_file())

    def file_save_as(self, event=None):
        self.current_file().save_file_as()
        self.file_tabs.tab(self.current_file(), text=self.current_file().get_file())

    def convert_file(self, event=None):
        self.current_file().convert_file()

    def current_file(self, event=None):
        return self.files[int(self.file_tabs.index(self.file_tabs.select()))]

    def flash_file(self, event=None):
        from tiborcim.tibc import compiler as tibc
        from tiborcim.tibc import flash
        from tiborcim.tibc import TibcStatus as status
        com = tibc(self.current_file().text_tiborcim.get("1.0", "end"))
        res = flash(''.join(com.output))
        if res is status.SUCCESS:
            showinfo(title='Success', message='File Flashed', parent=self.master)
        else:
            showerror(title='Failure', message='An Error Occured. Code: %s' % res, parent=self.master)

    def close_file(self, event=None):
        logging.debug("Close File")
        file = self.current_file()
        if file.close():
            self.file_tabs.forget(file)
            self.files.remove(file)

    def edit_cut(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-x>')

    def edit_copy(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-c>')

    def edit_paste(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-v>')

    def edit_redo(self, event=None):
        self.current_file().text_tiborcim.edit_redo()
        
    def edit_undo(self, event=None):
        self.current_file().text_tiborcim.edit_undo()

    def help_about(self, event=None):
        CimAbout.show(self)

    def help_readme(self, event=None):
        CimReadme.show(self)

    def help_sample(self, sam):
        print(sam)
        filepage = CimFilePage(self.file_tabs)
        filepage.load_file(tiborcim.resources.sample_path(sam))
        filepage.filename = None
        self.file_tabs.add(filepage, text="Unsaved Program")
        self.files.append(filepage)
        self.file_tabs.select(filepage)

    def file_quit(self, event=None):
        for ndx, member in enumerate(self.files):
            logging.debug(self.files[ndx].saved)
            if not self.files[ndx].close():
                return

        self.quit()
Ejemplo n.º 23
0
class View(Tk):
    def __init__(self, control, *args, **kwargs):
        '''
        parametros
        ----------
        control : control.Control
            objeto control
        '''
        super(View, self).__init__(*args, **kwargs)
        self._control = control

        self._criar_estilo()
        self._criar_notebook()
        self._criar_converter()
        self._criar_redimensionar()

    def _criar_notebook(self):
        '''
        Criar notebook p/ navegar entre varias telas.
        '''
        self._note = Notebook(self, style='View.TNotebook')
        self._note.pack(fill='both', expand=True)

    def _criar_converter(self):
        '''
        Intancia uma nova tela_converter e adiciona ao notebook.
        '''
        converter = tela_converter.TelaConverter(self._note, self._control)
        self._note.add(converter, text='Converter')

    def _criar_redimensionar(self):
        redimensionar = tela_redimensionar.TelaRedimensionar(
            self._note, self._control)
        self._note.add(redimensionar, text='Redimensionar')

    def _criar_estilo(self):
        '''
        Define o estilo dos widgets.
        '''
        cor_1 = '#C7E0DD'
        cor_2 = '#76B0AC'
        cor_3 = '#6C8BA7'
        cor_4 = '#CBB6B4'
        cor_5 = '#E5D4D0'
        cor_6 = '#EAE8E6'

        estilo = Style()

        # frame
        estilo.configure('TFrame', background=cor_4)

        # botao
        estilo.configure('TButton',
                         background=cor_3,
                         foreground=cor_6,
                         font=('Georgia', 14, 'normal'),
                         relief='flat')

        estilo.map('TButton',
                   background=[('active', cor_2)],
                   foreground=[('active', cor_6)])

        # label
        estilo.configure('TLabel',
                         background=cor_4,
                         font=('Gergia', 14, 'normal'))

        # entry
        estilo.configure('TEntry', fieldbackground=cor_6)

        #notebook
        estilo.configure('TNotebook.Tab',
                         background=cor_3,
                         foreground=cor_6,
                         font=('Arial', 14, 'bold'),
                         relief='raised',
                         borderwidth=5)

        estilo.map('TNotebook.Tab',
                   background=[('active', cor_2)],
                   foreground=[('active', cor_6)])

        # option menu
        estilo.configure('TMenubutton',
                         background=cor_6,
                         font=('Georgia', 14, 'normal'),
                         relief='flat')

        estilo.map('TMenubutton', background=[('active', cor_2)])

        # scales
        estilo.configure('TScale', background=cor_3)

        estilo.map('TScale', background=[('active', cor_2)])

        # spinboxs
        estilo.configure('TSpinbox',
                         arrowsize=20,
                         relief='flat',
                         background=cor_3,
                         fieldbackground=cor_6)

        estilo.map('TSpinbox', background=[('active', cor_2)])

    def mostrar_msg(self, msg):
        '''
        Abre uma nova janela mostrando uma mensagem.
        '''
        messagebox.showinfo('Mensagem', msg)

    def mostrar_aviso(self, aviso):
        '''
        Abreuma nova janela mostrando um aviso de alerta.
        '''
        messagebox.showwarning('Aviso', aviso)

    def main(self):
        '''
        Inicializa a gui.
        '''
        self.title('Ferramentas v.0.3')
        self.maxsize(width=800, height=450)
        self.minsize(width=800, height=450)
        self.mainloop()
#     print('yes1')
#     Addexpense()
#     # print(expense_tracker.get_LON_items()[0])

#
GUI = Tk()
GUI.title('** Expense Recorder **')
GUI.geometry('1000x600')
# Maximize windrow
# GUI. state ('zoomed')

Tab = Notebook(GUI)
F1 = Frame(Tab, width=500, height=500, bg="cyan")
Tab.add(F1, text='Expense')

Tab.pack(fill=BOTH, expand=1)
# Tab 1 (Expense)

# ==========Row 0 ===========================
LDate = ttk.Label(F1, text='Date', font=(None, 18))
LDate.grid(row=0, column=0, padx=5, pady=5, sticky='w')

EDate = DateEntry(F1,
                  width=19,
                  background='blue',
                  foreground='white',
                  font=(None, 18))
EDate.grid(row=0, column=1, padx=5, pady=5)

# ==========Row 1 ===========================
LTitle = ttk.Label(F1, text='Title', font=(None, 18))
Ejemplo n.º 25
0
class Manager(Toplevel):
    """Note manager."""
    def __init__(self, master):
        """Create note manager to easily delete multiple notes."""
        Toplevel.__init__(self, master, class_='MyNotes')
        self.title(_("Note Manager"))
        self.minsize(width=546, height=200)
        self.grab_set()
        categories = CONFIG.options("Categories")
        categories.sort()

        self.im_del = PhotoImage(file=IM_DELETE, master=self)
        self.im_change = PhotoImage(file=IM_CHANGE, master=self)
        self.im_visible = PhotoImage(file=IM_VISIBLE_24, master=self)
        self.im_hidden = PhotoImage(file=IM_HIDDEN_24, master=self)

        tooltipwrapper = TooltipWrapper(self)

        self.notebook = Notebook(self)
        self.notebook.pack(fill='both', expand=True)

        self.texts = {}
        self.frames = {}
        self.notes = {}

        # to change notes category
        menu_cat = Menu(self, tearoff=False)
        self.category = StringVar(self)

        # create one tab per category
        for cat in categories:
            menu_cat.add_radiobutton(label=cat.capitalize(),
                                     value=cat,
                                     variable=self.category,
                                     command=self.change_cat_selection)
            self.notes[cat] = {}
            frame = Frame(self.notebook, padding=2)
            self.texts[cat] = Text(frame,
                                   width=1,
                                   height=1,
                                   bg=self.cget('bg'),
                                   relief='flat',
                                   highlightthickness=0,
                                   padx=0,
                                   pady=0,
                                   cursor='arrow')
            frame.columnconfigure(0, weight=1)
            frame.rowconfigure(1, weight=1)

            self.texts[cat].grid(row=1, column=0, sticky='ewsn')
            scrolly = Scrollbar(frame,
                                orient='vertical',
                                command=self.texts[cat].yview)
            scrolly.grid(row=1, column=1, sticky='ns', pady=(2, 0))
            scrollx = Scrollbar(frame,
                                orient='horizontal',
                                command=self.texts[cat].xview)
            scrollx.grid(row=2, column=0, sticky='ew')
            self.texts[cat].configure(xscrollcommand=scrollx.set,
                                      yscrollcommand=scrolly.set)
            self.frames[cat] = Frame(self.texts[cat],
                                     style='bg.TFrame',
                                     padding=1,
                                     height=29,
                                     width=523)
            self.frames[cat].columnconfigure(0, weight=1, minsize=170)
            headings = Frame(frame, padding=(1, 0, 1, 0))
            headings.columnconfigure(0, weight=0, minsize=20)
            headings.columnconfigure(1, weight=1, minsize=198)
            headings.columnconfigure(2, weight=1, minsize=198)
            headings.columnconfigure(3, weight=0, minsize=84)
            headings.columnconfigure(4, weight=0, minsize=22)
            Heading(headings,
                    cat,
                    'title',
                    command=self.sort_column,
                    text=_('Title')).grid(row=0, column=1, sticky='ew')
            Heading(headings,
                    cat,
                    'text',
                    command=self.sort_column,
                    text=_('Text')).grid(row=0, column=2, sticky='ew')
            Heading(headings,
                    cat,
                    'date',
                    command=self.sort_column,
                    text=_('Date')).grid(row=0, column=3, sticky='ew')
            Heading(headings,
                    cat,
                    'select_all',
                    style='select.heading.TLabel',
                    padding=0,
                    command=self.toggle_selectall).place(x=0,
                                                         y=0,
                                                         anchor='nw',
                                                         relheight=1,
                                                         width=20)
            Heading(headings, cat, 'visibility',
                    command=self.sort_column).place(relx=1,
                                                    y=0,
                                                    anchor='ne',
                                                    bordermode='outside',
                                                    width=23,
                                                    relheight=1)
            headings.place(x=0, y=2, anchor='nw')
            self.update_idletasks()
            frame.rowconfigure(0, minsize=headings.winfo_reqheight())
            self.texts[cat].window_create('1.0', window=self.frames[cat])
            b_frame = Frame(frame)
            b_frame.grid(row=3, columnspan=2)
            m = Menubutton(b_frame,
                           image=self.im_change,
                           text=_('Change category'),
                           compound='right',
                           menu=menu_cat,
                           padding=1)
            m.pack(side='left', padx=4, pady=4, fill='y')
            tooltipwrapper.add_tooltip(m,
                                       _('Change category of selected notes'))
            b_show = Button(b_frame,
                            image=self.im_visible,
                            padding=1,
                            command=self.show_selection)
            b_show.pack(side='left', padx=4, pady=4)
            tooltipwrapper.add_tooltip(b_show, _('Show selected notes'))
            b_hide = Button(b_frame,
                            image=self.im_hidden,
                            padding=1,
                            command=self.hide_selection)
            b_hide.pack(side='left', padx=4, pady=4)
            tooltipwrapper.add_tooltip(b_hide, _('Hide selected notes'))
            b_del = Button(b_frame,
                           image=self.im_del,
                           command=self.del_selection,
                           padding=1)
            b_del.pack(side='left', padx=4, pady=4, fill='y')
            tooltipwrapper.add_tooltip(b_del, _('Delete selected notes'))

            self.notebook.add(frame,
                              text=cat.capitalize(),
                              sticky="ewsn",
                              padding=0)
        # display notes by category
        for key, note_data in self.master.note_data.items():
            self.display_note(key, note_data)

        for txt in self.texts.values():
            txt.configure(state='disabled')
        self.geometry('410x450')
        self.bind("<Button-4>", lambda e: self.scroll(-1))
        self.bind("<Button-5>", lambda e: self.scroll(1))
        self.notebook.bind('<<NotebookTabChanged>>', self.on_change_tab)

    def toggle_selectall(self, event):
        heading = event.widget
        cat = heading.category
        sel = self.get_selection(cat)
        if len(sel) == len(self.notes[cat]):
            for widget in self.notes[cat].values():
                widget.state(('!selected', ))
        else:
            for widget in self.notes[cat].values():
                widget.state(('selected', ))

    def show_selection(self):
        cat = self.notebook.tab('current', 'text').lower()
        sel = self.get_selection(cat)
        if sel:
            for key in sel:
                self.notes[cat][key].visibility.set(True)
                self.toggle_visibility(key, True)

    def hide_selection(self):
        cat = self.notebook.tab('current', 'text').lower()
        sel = self.get_selection(cat)
        if sel:
            for key in sel:
                self.notes[cat][key].visibility.set(False)
                self.toggle_visibility(key, False)

    def select_all(self):
        cat = self.notebook.tab('current', 'text').lower()
        for widget in self.notes[cat].values():
            widget.state(('selected', ))

    def deselect_all(self):
        cat = self.notebook.tab('current', 'text').lower()
        for widget in self.notes[cat].values():
            widget.state(('!selected', ))

    def sort_column(self, event):
        """Sort column."""
        heading = event.widget
        notes = [(item.get(heading.column), item.get_values(), item)
                 for item in self.notes[heading.category].values()]
        notes.sort(reverse=heading.reverse, key=lambda x: x[:-1])
        for i, (val, values, item) in enumerate(notes):
            item.grid_configure(row=i)
        heading.reverse = not heading.reverse
        heading.state(['!' * heading.reverse + 'alternate'])

    def toggle_visibility(self, key, visible):
        if visible:
            if key not in self.master.notes:
                self.master.show_note(key)
        else:
            if key in self.master.notes:
                self.master.notes[key].hide()
        self.after(2, self.focus_set)
        self.after(4, self.grab_set)

    def display_note(self, key, note_data):
        """Display note in note manager."""
        cat = note_data["category"]
        c, r = self.frames[cat].grid_size()
        self.notes[cat][key] = ManagerItem(
            self.frames[cat], note_data,
            lambda vis: self.toggle_visibility(key, vis))
        self.notes[cat][key].grid(row=r, sticky='ew')

    def on_change_tab(self, event):
        self.category.set(self.notebook.tab("current", "text").lower())

    def del_selection(self):
        """Delete selected notes."""
        cat = self.notebook.tab('current', 'text').lower()
        sel = self.get_selection(cat)
        if sel:
            rep = askokcancel(_("Confirmation"),
                              _("Delete the selected notes?"))
            if rep:
                for key in sel:
                    self.master.delete_note(key)
                    self.notes[cat][key].destroy()
                    del self.notes[cat][key]
                    self.update_idletasks()

    def change_cat_selection(self):
        """Change selected notes category."""
        cat = self.notebook.tab('current', 'text').lower()
        new_cat = self.category.get()
        sel = self.get_selection(cat)
        if sel and new_cat != cat:
            rep = askokcancel(_("Confirmation"),
                              _("Change the category of the selected notes?"))
            if rep:
                for key in sel:
                    self.master.change_note_category(key, new_cat)
                    self.notes[cat][key].destroy()
                    del self.notes[cat][key]
                    self.display_note(key, self.master.note_data[key])
                    self.update_idletasks()
        self.category.set(cat)
        self.grab_set()

    def get_selection(self, cat):
        sel = []
        for key, widget in self.notes[cat].items():
            if 'selected' in widget.state():
                sel.append(key)
        return sel

    def scroll(self, delta):
        cat = self.notebook.tab("current", "text").lower()
        top, bottom = self.texts[cat].yview()
        top += delta * 0.05
        top = min(max(top, 0), 1)
        self.texts[cat].yview_moveto(top)
Ejemplo n.º 26
0
class TestTool(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title("Test Tool Platform:" + str(platform.system()))

        w = 1000  # width for the Tk root
        h = 800  # height for the  Tk root

        # get screen width and height
        ws = self.winfo_screenwidth()  # width of the screen
        hs = self.winfo_screenheight()  # height of the screen

        # calculate x and y coordinates for the Tk root window
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)

        # set the dimensions of the screen
        # and where it is placed
        self.geometry('%dx%d+%d+%d' % (w, h, x, y))
        '''self.notebook'''
        self.notebook = Notebook(self)
        self.notebook.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)

        self.init_FrameViewer()

    def init_FrameViewer(self):
        self.init_FrameViewer_tab = tk.Frame(self.notebook)
        self.init_FrameViewer_tab.pack(side=tk.LEFT,
                                       expand=tk.YES,
                                       fill=tk.BOTH)
        self.notebook.add(self.init_FrameViewer_tab, text="init_FrameViewer")
        self.FrameSwitch = tk.StringVar()

        fvfram1 = tk.Frame(self.init_FrameViewer_tab)
        fvfram1.grid(row=0, column=0, sticky=tk.E + tk.W)
        self.fv1 = FV.FrameViewer(fvfram1)
        fvfram1_2 = tk.Frame(self.init_FrameViewer_tab)
        fvfram1_2.grid(row=1, column=0, sticky=tk.E + tk.W)
        switch1 = tk.Radiobutton(fvfram1_2,
                                 text="Frame\n Switch 1",
                                 font=('Courier', 9),
                                 variable=self.FrameSwitch,
                                 value="Frame Switch 1",
                                 command=self.frameswitch)
        switch1.pack(side=tk.RIGHT, expand=tk.NO, fill=tk.X)

        fvfram2 = tk.Frame(self.init_FrameViewer_tab)
        fvfram2.grid(row=2, column=0, sticky=tk.E + tk.W)
        self.fv2 = FV.FrameViewer(fvfram2)
        fvfram2_2 = tk.Frame(self.init_FrameViewer_tab)
        fvfram2_2.grid(row=3, column=0, sticky=tk.E + tk.W)
        switch2 = tk.Radiobutton(fvfram2_2,
                                 text="Frame\n Switch 2",
                                 font=('Courier', 9),
                                 variable=self.FrameSwitch,
                                 value="Frame Switch 2",
                                 command=self.frameswitch)
        switch2.pack(side=tk.RIGHT, expand=tk.NO, fill=tk.X)

        fvfram3 = tk.Frame(self.init_FrameViewer_tab)
        fvfram3.grid(row=0, column=1, sticky=tk.E + tk.W)
        self.fv3 = FV.FrameViewer(fvfram3)
        fvfram3_2 = tk.Frame(self.init_FrameViewer_tab)
        fvfram3_2.grid(row=1, column=1, sticky=tk.E + tk.W)
        switch3 = tk.Radiobutton(fvfram3_2,
                                 text="Frame\n Switch 3",
                                 font=('Courier', 9),
                                 variable=self.FrameSwitch,
                                 value="Frame Switch 3",
                                 command=self.frameswitch)
        switch3.pack(side=tk.RIGHT, expand=tk.NO, fill=tk.X)

        fvfram4 = tk.Frame(self.init_FrameViewer_tab)
        fvfram4.grid(row=2, column=1, sticky=tk.E + tk.W)
        self.fv4 = FV.FrameViewer(fvfram4)
        fvfram4_2 = tk.Frame(self.init_FrameViewer_tab)
        fvfram4_2.grid(row=3, column=1, sticky=tk.E + tk.W)
        switch4 = tk.Radiobutton(fvfram4_2,
                                 text="Frame\n Switch 4",
                                 font=('Courier', 9),
                                 variable=self.FrameSwitch,
                                 value="Frame Switch 4",
                                 command=self.frameswitch)
        switch4.pack(side=tk.RIGHT, expand=tk.NO, fill=tk.X)

    def frameswitch(self):
        if self.FrameSwitch.get() == "Frame Switch 1":
            StreamFile = self.fv1.cap  #self.iv1.image_paths[self.iv1.image_idx]
        elif self.FrameSwitch.get() == "Frame Switch 2":
            StreamFile = self.fv2.cap  #self.iv2.image_paths[self.iv2.image_idx]
        elif self.FrameSwitch.get() == "Frame Switch 3":
            StreamFile = self.fv3.cap  #self.iv3.image_paths[self.iv3.image_idx]
        elif self.FrameSwitch.get() == "Frame Switch 4":
            StreamFile = self.fv4.cap  #self.iv4.image_paths[self.iv4.image_idx]
        #print(StreamFile)
        """
Ejemplo n.º 27
0
def Result_Print():
    window = Tk()
    window.title("分析結果")
    window.geometry("600x900")

    frame2 = Frame(window)
    frame2.pack(fill="both")

    tablayout = Notebook(frame2)
    tablayout2 = Notebook(frame2)

    #交叉配對
    ntab1 = Frame(tablayout2)
    ntab1.pack(fill="both")
    for row in range(len(name_n)):
        for column in range(1):
            label = Label(ntab1,
                          width=25,
                          height=2,
                          text=name_n[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)
    for row in range(len(name_n)):
        for column in range(1):
            label = Label(ntab1,
                          width=5,
                          height=2,
                          text="%s" % rate_n[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    for row in range(len(name_n)):
        for column in range(1):
            label = Label(ntab1,
                          width=12,
                          height=2,
                          text="%   相似程度",
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=2, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)
    tablayout2.add(ntab1, text="交叉配對結果")

    ntab2 = Frame(tablayout2)
    ntab2.pack(fill="both")

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab2,
                          width=22,
                          height=1,
                          text=ncol[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab2,
                          width=22,
                          height=1,
                          text=row_nf3[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    tablayout2.add(ntab2, text="配方1")

    ntab3 = Frame(tablayout2)
    ntab3.pack(fill="both")

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab3,
                          width=22,
                          height=1,
                          text=ncol[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab3,
                          width=22,
                          height=1,
                          text=row_nf32[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    tablayout2.add(ntab3, text="配方2")

    ntab4 = Frame(tablayout2)
    ntab4.pack(fill="both")

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab4,
                          width=22,
                          height=1,
                          text=ncol[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab4,
                          width=22,
                          height=1,
                          text=row_nf33[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    tablayout2.add(ntab4, text="配方3")

    ntab5 = Frame(tablayout2)
    ntab5.pack(fill="both")

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab5,
                          width=22,
                          height=1,
                          text=ncol[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    for row in range(len(ncol)):
        for column in range(1):
            label = Label(ntab5,
                          width=22,
                          height=1,
                          text=row_nf3[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            ntab1.grid_columnconfigure(column, weight=1)

    tablayout2.add(ntab5, text="最接近配方")

    #顏色分類
    tab1 = Frame(tablayout)
    tab1.pack(fill="both")
    for row in range(len(name)):
        for column in range(1):
            label = Label(tab1,
                          width=25,
                          height=2,
                          text=name[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)
    for row in range(len(name)):
        for column in range(1):
            label = Label(tab1,
                          width=5,
                          height=2,
                          text="%s" % rate[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    for row in range(len(name)):
        for column in range(1):
            label = Label(tab1,
                          width=12,
                          height=2,
                          text="%   相似程度",
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=2, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)
    tablayout.add(tab1, text="顏色分類結果")

    tab2 = Frame(tablayout)
    tab2.pack(fill="both")

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab2,
                          width=22,
                          height=1,
                          text=col[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab2,
                          width=22,
                          height=1,
                          text=row_df3[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    tablayout.add(tab2, text="配方1")

    tab3 = Frame(tablayout)
    tab3.pack(fill="both")

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab3,
                          width=22,
                          height=1,
                          text=col[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab3,
                          width=22,
                          height=1,
                          text=row_df32[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    tablayout.add(tab3, text="配方2")

    tab4 = Frame(tablayout)
    tab4.pack(fill="both")

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab4,
                          width=22,
                          height=1,
                          text=col[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab4,
                          width=22,
                          height=1,
                          text=row_df33[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    tablayout.add(tab4, text="配方3")

    tab5 = Frame(tablayout)
    tab5.pack(fill="both")

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab5,
                          width=22,
                          height=1,
                          text=col[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    for row in range(len(col)):
        for column in range(1):
            label = Label(tab5,
                          width=22,
                          height=1,
                          text=row_text[row],
                          bg="black",
                          fg="white",
                          padx=1,
                          pady=1)
            label.grid(row=row, column=1, sticky="nsew", padx=1, pady=1)
            tab1.grid_columnconfigure(column, weight=1)

    tablayout.add(tab5, text="最接近配方")

    tablayout.pack()
    tablayout2.pack()
    window.mainloop()
Ejemplo n.º 28
0
class Manager(Toplevel):
    """Note manager."""
    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.title(_("Delete"))
        self.grab_set()
        categories = CONFIG.options("Categories")
        categories.sort()

        self.im_moins = PhotoImage(file=IM_MOINS, master=self)

        self.notebook = Notebook(self)
        self.notebook.pack(fill='both', expand=True)

        self.texts = {}
        frames = {}
        self.notes = {}
        for cat in categories:
            frame = Frame(self.notebook)
            self.texts[cat] = Text(frame,
                                   width=1,
                                   height=1,
                                   bg=self.cget('bg'),
                                   relief='flat',
                                   highlightthickness=0,
                                   padx=4,
                                   pady=4,
                                   cursor='arrow')
            frame.columnconfigure(0, weight=1)
            frame.rowconfigure(0, weight=1)

            self.texts[cat].grid(row=0, column=0, sticky='ewsn', padx=(0, 2))
            scrolly = Scrollbar(frame,
                                orient='vertical',
                                command=self.texts[cat].yview)
            scrolly.grid(row=0, column=1, sticky='ns')
            scrollx = Scrollbar(frame,
                                orient='horizontal',
                                command=self.texts[cat].xview)
            scrollx.grid(row=1, column=0, sticky='ew')
            self.texts[cat].configure(xscrollcommand=scrollx.set,
                                      yscrollcommand=scrolly.set)
            frames[cat] = Frame(self.texts[cat])
            frames[cat].columnconfigure(0, weight=1, minsize=170)
            frames[cat].columnconfigure(1, weight=1, minsize=170)
            frames[cat].columnconfigure(2, minsize=20)
            self.texts[cat].window_create('1.0', window=frames[cat])

            self.notebook.add(frame,
                              text=cat.capitalize(),
                              sticky="ewsn",
                              padding=0)
        for key, note_data in self.master.note_data.items():
            cat = note_data["category"]
            c, r = frames[cat].grid_size()
            self.notes[key] = []
            title = note_data['title'][:20]
            title = title.replace('\t', ' ') + ' ' * (20 - len(title))
            self.notes[key].append(
                Label(frames[cat], text=title, font='TkDefaultFont 10 bold'))
            txt = note_data['txt'].splitlines()
            if txt:
                txt = txt[0][:17] + '...'
            else:
                txt = ''
            txt = txt.replace('\t', ' ') + ' ' * (20 - len(txt))
            self.notes[key].append(Label(frames[cat], text=txt))
            self.notes[key].append(
                Button(frames[cat],
                       image=self.im_moins,
                       command=lambda iid=key: self.delete_note(iid)))
            for i, widget in enumerate(self.notes[key]):
                widget.grid(row=r, column=i, sticky='w', padx=4, pady=4)

        for txt in self.texts.values():
            txt.configure(state='disabled')
        self.geometry('410x450')
        self.bind_all("<Button-4>", lambda e: self.scroll(-1))
        self.bind_all("<Button-5>", lambda e: self.scroll(1))

    def delete_note(self, note_id):
        self.master.delete_note(note_id)
        for widget in self.notes[note_id]:
            widget.destroy()

    def scroll(self, delta):
        cat = self.notebook.tab("current", "text").lower()
        top, bottom = self.texts[cat].yview()
        top += delta * 0.05
        top = min(max(top, 0), 1)
        self.texts[cat].yview_moveto(top)
Ejemplo n.º 29
0
class DeviceSelector:

    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    devices = None

    local = LocalConnector()
    grid = GridConnector()
    sauce = SauceConnector()
    mc = MCConnector()

    def __init__(self, parallel=False, platform="mobile"):
        self.parallel = parallel
        self.platform = platform

    def start(self):
        parallel = self.parallel
        platform = self.platform

        # Create Window
        self.root = Tk()
        win = self.root
        self.note = Notebook(self.root)

        # Set Window Properties
        win.wm_title("Test Runner")
        win.minsize(width=500, height=500)

        # Create Listbox
        scrollbar = Scrollbar(win)
        scrollbar.pack(side=RIGHT, fill=Y)

        # Add Mustard Checkbox and Instructions Label
        frame = Frame(win)

        self.mustard = GetConfig("SKIP_MUSTARD").lower() == "false"
        c = Checkbutton(frame, text="Add Mustard?", command=self._toggleMustard)
        if self.mustard:
            c.select()
        c.pack(side=RIGHT)

        mobileFrame = Frame(win)
        if parallel:
            label = Label(frame, text="Please Select one or more devices to run")
            label.pack(side=LEFT)
            self.listboxMobile = Listbox(mobileFrame, selectmode=EXTENDED)
        else:
            label = Label(frame, text="Please Select one device to run")
            label.pack(side=LEFT)
            self.listboxMobile = Listbox(mobileFrame, selectmode=SINGLE)
        frame.pack(fill=X)

        self.listboxMobile.pack(fill=BOTH, expand=1)

        # Attach Scrollbar to Listbox
        self.listboxMobile.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listboxMobile.yview)

        # Generate Listbox Data
        mobileData = []
        mobileNodes = self.grid.mobileNodes
        for node in mobileNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        sauceNodes = self.sauce.mobileNodes
        for node in sauceNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        mcNodes = self.mc.mobileNodes
        for node in mcNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        self.mobileData = mobileData

        self.listboxMobile.insert(END, "Local Device")

        desktopFrame = Frame(win)
        if parallel:
            self.listboxDesktop = Listbox(desktopFrame, selectmode=EXTENDED)
        else:
            self.listboxDesktop = Listbox(desktopFrame, selectmode=SINGLE)
        frame.pack(fill=X)

        self.listboxDesktop.pack(fill=BOTH, expand=1)

        # Attach Scrollbar to Listbox
        self.listboxDesktop.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listboxDesktop.yview)

        # Generate Listbox Data
        webData = []
        webDisplay = []

        localNodes = self.local.webNodes
        for node in localNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        webNodes = self.grid.webNodes
        for node in webNodes:
            ds = node.displayString()
            if ds not in webDisplay:
                webDisplay.append(ds)
                webData.append(node)
                self.listboxDesktop.insert(END, ds)

        sauceNodes = self.sauce.webNodes
        for node in sauceNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        sauceNodes = self.sauce.mobileWebNodes
        for node in sauceNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        mcNodes = self.mc.webNodes
        for node in mcNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        self.webData = webData

        self.frame = Frame(win)
        self.frame.pack(fill=X)

        # Create Buttons
        Button(mobileFrame, text="Cancel", fg="red", command=self.frame.quit, width=50, height=5).pack(
            side=RIGHT, fill=Y
        )
        Button(mobileFrame, text="Run Test", fg="green", command=self._saveDevices, width=50).pack(side=LEFT, fill=Y)

        # Create Buttons
        Button(desktopFrame, text="Cancel", fg="red", command=self.frame.quit, width=50, height=5).pack(
            side=RIGHT, fill=Y
        )
        Button(desktopFrame, text="Run Test", fg="green", command=self._saveDevicesDesktop, width=50).pack(
            side=LEFT, fill=Y
        )

        if platform.lower() == "mobile":
            self.note.add(mobileFrame, text="Mobile")
            self.note.add(desktopFrame, text="Web")
        else:
            self.note.add(desktopFrame, text="Web")
            self.note.add(mobileFrame, text="Mobile")
        self.note.pack(fill=BOTH, expand=1)

        # allow double clicking in listbox to select a browser
        self.listboxMobile.bind("<Double-1>", lambda x: self._saveDevices())
        self.listboxDesktop.bind("<Double-1>", lambda x: self._saveDevicesDesktop())

    def _toggleMustard(self):
        self.mustard = not self.mustard

    def getDevice(self, filter=None, mustard=True):
        if filter:
            # webNodes = self.grid.webNodes
            # mobileNodes = self.grid.mobileNodes
            if self.platform:
                if self.platform == "desktop":
                    nodes = self.grid.webNodes + self.sauce.webNodes + self.sauce.mobileWebNodes
                elif self.platform == "mobile":
                    nodes = self.grid.mobileNodes + self.sauce.mobileNodes
                else:
                    nodes = self.grid.webNodes + self.grid.mobileNodes + self.sauce.webNodes + self.sauce.mobileWebNodes
            output = []
            for node in nodes:
                if re.search(filter, node.displayString()):
                    dc = node.desiredCaps(mustard=mustard)
                    output.append(dc)
            return output
        else:
            self.start()
            # for osx bring selector window to the front
            if sys.platform.lower() == "darwin":  # Mac OS
                self.root.lift()
                self.root.attributes("-topmost", True)
            self.root.mainloop()
            self.root.destroy()
            output = []
            for x in range(len(self.devices)):
                dc = self.devices[x].desiredCaps(mustard=self.mustard)
                output.append(dc)
            return output

    def _saveDevicesDesktop(self):

        selected = self.listboxDesktop.curselection()

        output = []
        for selection in selected:
            output.append(self.webData[int(selection)])

        self.frame.quit()
        self.devices = output

    def _saveDevices(self):

        selected = self.listboxMobile.curselection()

        output = []
        for selection in selected:
            output.append(self.mobileData[int(selection)])

        self.frame.quit()
        self.devices = output
Ejemplo n.º 30
0
class Main:
    def __init__(self, master):
        self.master = master
        self.abas = Notebook()
        self.frame_aba1 = Frame(self.abas)  # Aba superior 'Débitos'.
        self.frame_aba2 = Frame(self.abas)  # Aba 'REALIZAR PEDIDOS'.
        self.frame_aba3 = Frame(self.abas)  # Aba 'ENTREGAS'

        self.abas.add(self.frame_aba1, text='Débitos')  # Nomeando as abas.
        self.abas.add(self.frame_aba2, text='Realizar Pedido')  # Nomeando as abas.
        self.abas.add(self.frame_aba3, text='Entregas')  # Nomeando as abas.
        self.abas.pack(anchor=W)

        #  Início quadrado ADICIONAR DÉBITO.
        self.frame = LabelFrame(self.frame_aba1, text='ADICIONAR DÉBITO')
        self.frame.grid(row=0, column=0, padx=20, pady=20)

        Label(self.frame, text='Nome :').grid(row=1, column=1)
        self.name = Entry(self.frame)
        self.name.grid(row=1, column=2, padx=10)

        Label(self.frame, text='Data de Nascimento :').grid(row=2, column=1)
        self.datanasci = Entry(self.frame)
        self.datanasci.grid(row=2, column=2)

        Label(self.frame, text='CPF :').grid(row=3, column=1)
        self.cpf = Entry(self.frame)
        self.cpf.grid(row=3, column=2)

        Label(self.frame, text='Data do Débito :').grid(row=4, column=1)
        self.datdeb = Entry(self.frame)
        self.datdeb.grid(row=4, column=2)

        Label(self.frame, text='Valor do Débito :').grid(row=5, column=1)
        self.valordeb = Entry(self.frame)
        self.valordeb.grid(row=5, column=2)

        self.btn1 = Button(self.frame, text='ENVIAR', command=self.enviar_nome)
        self.btn1.grid(row=6, column=2, pady=10)

        # Início quadrado Buscar/Deletar Débitos.
        self.frame2 = LabelFrame(self.frame_aba1, text='BUSCAR/DELETAR DÉBITOS')
        self.frame2.grid(row=1, column=0)

        Label(self.frame2, text='Buscar por Nome :').grid(row=1, column=1)
        self.busnome = Entry(self.frame2)
        self.busnome.grid(row=1, column=2, padx=10)

        Label(self.frame2, text='Buscar por CPF :').grid(row=2, column=1)
        self.buscpf = Entry(self.frame2)
        self.buscpf.grid(row=2, column=2)

        Label(self.frame2, text='Buscar Pessoa').grid(row=3, column=1)

        Label(self.frame2, text='Deletar Débito').grid(row=3, column=2)

        self.btn2 = Button(self.frame2, text='BUSCAR')
        self.btn2.grid(row=4, column=1, pady=10)

        self.btn3 = Button(self.frame2, text='DELETAR', command=self.deletar_nome)
        self.btn3.grid(row=4, column=2)

        # Início tabela Treeview.

        self.tree = ttk.Treeview(self.frame_aba1, height=20, columns=('Nº', 'Nome', 'Valor do Débito', 'Data do Débito', 'CPF'))
        self.tree.grid(row=0, column=1, rowspan=10)
        self.tree.heading('#0', text='Nº', anchor=W)
        self.tree.heading('#1', text='Nome', anchor=W)
        self.tree.heading('#2', text='Valor do Débito', anchor=W)
        self.tree.heading('#3', text='Data do Débito', anchor=W)
        self.tree.heading('#4', text='CPF', anchor=W)
        self.tree.heading('#5', text='Data Nascimento', anchor=W)
        self.tree.column('#0', minwidth=50, width=80)
        self.tree.column('#1', minwidth=50, width=250)
        self.tree.column('#2', minwidth=50, width=150)
        self.tree.column('#3', minwidth=50, width=150)
        self.tree.column('#4', minwidth=100, width=200)
        self.tree.column('#5', minwidth=50, width=150)
        self.treeview = self.tree
        self.i = 1

        # Scrollbar da tabela Treeview.
        self.yscroll = Scrollbar(self.frame_aba1, orient=VERTICAL)
        self.tree['yscrollcommand'] = self.yscroll.set
        self.yscroll['command'] = self.tree.yview()
        self.yscroll.grid(row=0, column=1, rowspan=10, sticky=N+S+E)

    ############################## ABA REALIZAR PEDIDO #########################################

        self.frame3 = LabelFrame(self.frame_aba2, text='INFORMAÇÕES DO PEDIDO')
        self.frame3.grid(row=0, column=0, padx=10, pady=10)

        Label(self.frame3, text='Nome :').grid(row=0, column=0)
        self.nameframe3 = Entry(self.frame3)
        self.nameframe3.grid(row=0, column=1)

        Label(self.frame3, text='Entregar Dia :').grid(row=1, column=0)
        self.entdia = Entry(self.frame3)
        self.entdia.grid(row=1, column=1)

        Label(self.frame3, text='Endereço :').grid(row=0, column=2)
        self.ende = Entry(self.frame3)
        self.ende.grid(row=0, column=3)

        Label(self.frame3, text='Bairro :').grid(row=1, column=2)
        self.bairro = Entry(self.frame3)
        self.bairro.grid(row=1, column=3)

        Label(self.frame3, text='CEP :').grid(row=0, column=4)
        self.cep = Entry(self.frame3)
        self.cep.grid(row=0, column=5)

        Label(self.frame3, text='Ponto de Referência :').grid(row=1, column=4)
        self.pontodr = Entry(self.frame3)
        self.pontodr.grid(row=1, column=5)

        Label(self.frame3, text='Fone 1 :').grid(row=0, column=6)
        self.fone1 = Entry(self.frame3)
        self.fone1.grid(row=0, column=7)

        Label(self.frame3, text='Fone 2 :').grid(row=1, column=6)
        self.fone2 = Entry(self.frame3)
        self.fone2.grid(row=1, column=7, padx=10, pady=10)

        self.frame4 = LabelFrame(self.frame_aba2, text='INFORME AQUI OS PRODUTOS DO PEDIDO')
        self.frame4.grid(row=1, column=0)

        self.entradap = Text(self.frame4)
        self.entradap.grid(row=2, column=0, padx=10, pady=10)

        self.btn4 = Button(self.frame4, text='ENVIAR')
        self.btn4.grid(row=3, column=0, pady=10)

    # Comandos da aba Débitos
    def enviar_nome(self):
        self.treeview.insert('', 'end', text='Nº '+str(self.i), values=(self.name.get(), self.valordeb.get(),
                                                                       self.datdeb.get(), self.cpf.get(),
                                                                       self.datanasci.get()))
        self.name.delete(0, 'end')
        self.valordeb.delete(0, 'end')
        self.datdeb.delete(0, 'end')
        self.cpf.delete(0, 'end')
        self.datanasci.delete(0, 'end')
        self.i = self.i + 1

    def deletar_nome(self):
        self.selected_item = self.tree.selection()        # get selected item
        self.tree.delete(self.selected_item)
Ejemplo n.º 31
0
class DeviceSelector:

    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    devices = None

    local = LocalConnector()
    grid = GridConnector()
    sauce = SauceConnector()
    mc = MCConnector()

    def __init__(self, parallel=False, platform='mobile'):
        self.parallel = parallel
        self.platform = platform

    def start(self):
        parallel = self.parallel
        platform = self.platform

        # Create Window
        self.root = Tk()
        win = self.root
        self.note = Notebook(self.root)

        # Set Window Properties
        win.wm_title("Test Runner")
        win.minsize(width=500, height=500)

        # Create Listbox
        scrollbar = Scrollbar(win)
        scrollbar.pack(side=RIGHT, fill=Y)

        #Add Mustard Checkbox and Instructions Label
        frame = Frame(win)

        self.mustard = GetConfig('SKIP_MUSTARD').lower() == 'false'
        c = Checkbutton(frame,
                        text="Add Mustard?",
                        command=self._toggleMustard)
        if self.mustard:
            c.select()
        c.pack(side=RIGHT)

        mobileFrame = Frame(win)
        if parallel:
            label = Label(frame,
                          text="Please Select one or more devices to run")
            label.pack(side=LEFT)
            self.listboxMobile = Listbox(mobileFrame, selectmode=EXTENDED)
        else:
            label = Label(frame, text="Please Select one device to run")
            label.pack(side=LEFT)
            self.listboxMobile = Listbox(mobileFrame, selectmode=SINGLE)
        frame.pack(fill=X)

        self.listboxMobile.pack(fill=BOTH, expand=1)

        # Attach Scrollbar to Listbox
        self.listboxMobile.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listboxMobile.yview)

        # Generate Listbox Data
        mobileData = []
        mobileNodes = self.grid.mobileNodes
        for node in mobileNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        sauceNodes = self.sauce.mobileNodes
        for node in sauceNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        mcNodes = self.mc.mobileNodes
        for node in mcNodes:
            mobileData.append(node)
            self.listboxMobile.insert(END, node.displayString())

        self.mobileData = mobileData

        self.listboxMobile.insert(END, 'Local Device')

        desktopFrame = Frame(win)
        if parallel:
            self.listboxDesktop = Listbox(desktopFrame, selectmode=EXTENDED)
        else:
            self.listboxDesktop = Listbox(desktopFrame, selectmode=SINGLE)
        frame.pack(fill=X)

        self.listboxDesktop.pack(fill=BOTH, expand=1)

        # Attach Scrollbar to Listbox
        self.listboxDesktop.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listboxDesktop.yview)

        # Generate Listbox Data
        webData = []
        webDisplay = []

        localNodes = self.local.webNodes
        for node in localNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        webNodes = self.grid.webNodes
        for node in webNodes:
            ds = node.displayString()
            if ds not in webDisplay:
                webDisplay.append(ds)
                webData.append(node)
                self.listboxDesktop.insert(END, ds)

        sauceNodes = self.sauce.webNodes
        for node in sauceNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        sauceNodes = self.sauce.mobileWebNodes
        for node in sauceNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        mcNodes = self.mc.webNodes
        for node in mcNodes:
            webData.append(node)
            self.listboxDesktop.insert(END, node.displayString())

        self.webData = webData

        self.frame = Frame(win)
        self.frame.pack(fill=X)

        # Create Buttons
        Button(mobileFrame,
               text="Cancel",
               fg="red",
               command=self.frame.quit,
               width=50,
               height=5).pack(side=RIGHT, fill=Y)
        Button(mobileFrame,
               text="Run Test",
               fg="green",
               command=self._saveDevices,
               width=50).pack(side=LEFT, fill=Y)

        # Create Buttons
        Button(desktopFrame,
               text="Cancel",
               fg="red",
               command=self.frame.quit,
               width=50,
               height=5).pack(side=RIGHT, fill=Y)
        Button(desktopFrame,
               text="Run Test",
               fg="green",
               command=self._saveDevicesDesktop,
               width=50).pack(side=LEFT, fill=Y)

        if platform.lower() == 'mobile':
            self.note.add(mobileFrame, text='Mobile')
            self.note.add(desktopFrame, text='Web')
        else:
            self.note.add(desktopFrame, text='Web')
            self.note.add(mobileFrame, text='Mobile')
        self.note.pack(fill=BOTH, expand=1)

        # allow double clicking in listbox to select a browser
        self.listboxMobile.bind('<Double-1>', lambda x: self._saveDevices())
        self.listboxDesktop.bind('<Double-1>',
                                 lambda x: self._saveDevicesDesktop())

    def _toggleMustard(self):
        self.mustard = not self.mustard

    def getDevice(self, filter=None, mustard=True):
        if filter:
            #webNodes = self.grid.webNodes
            #mobileNodes = self.grid.mobileNodes
            if self.platform:
                if self.platform == 'desktop':
                    nodes = self.grid.webNodes + self.sauce.webNodes + self.sauce.mobileWebNodes + self.local.webNodes
                elif self.platform == 'mobile':
                    nodes = self.grid.mobileNodes + self.sauce.mobileNodes
                else:
                    nodes = self.grid.webNodes + self.grid.mobileNodes + self.sauce.webNodes + self.sauce.mobileWebNodes
            output = []
            for node in nodes:
                if re.search(filter, node.displayString()):
                    dc = node.desiredCaps(mustard=mustard)
                    output.append(dc)
            return output
        else:
            self.start()
            # for osx bring selector window to the front
            if sys.platform.lower() == 'darwin':  # Mac OS
                self.root.lift()
                self.root.attributes('-topmost', True)
            self.root.mainloop()
            self.root.destroy()
            output = []
            for x in range(len(self.devices)):
                dc = self.devices[x].desiredCaps(mustard=self.mustard)
                if dc not in output:
                    output.append(dc)
            return output

    def _saveDevicesDesktop(self):

        selected = self.listboxDesktop.curselection()

        output = []
        for selection in selected:
            output.append(self.webData[int(selection)])

        self.frame.quit()
        self.devices = output

    def _saveDevices(self):

        selected = self.listboxMobile.curselection()

        output = []
        for selection in selected:
            output.append(self.mobileData[int(selection)])

        self.frame.quit()
        self.devices = output
Ejemplo n.º 32
0
class MainWindow(object):
    def __init__(self, master):
        self.master = master

        # TOP Frame for LABEL
        frame_1 = LabelFrame(self.master, bd=1, height=80, borderwidth=2)
        frame_1.pack(side=TOP, fill="x", padx=1)
        # create a label in first frame_1
        label_1 = Label(frame_1,
                        text='Library Management System',
                        bg="gray72",
                        height=3,
                        font=("Courier", 25, 'bold'))
        label_1.pack(side=TOP, fill="x")

        # Frame 2 for management
        frame_2 = LabelFrame(self.master, bd=1, borderwidth=2)
        frame_2.pack(fill="x", padx=1, pady=1)
        # Create TABS for frame_4
        self.tabs = Notebook(frame_2, width=800, height=500)
        self.tabs.pack(fill="x")
        self.tab1 = Frame(self.tabs)
        self.tab2 = Frame(self.tabs)
        self.tabs.add(self.tab1, text="Book Management")
        self.tabs.add(self.tab2, text="Student Management")

        # Book Management in Tab1
        # Book Management Frame_1
        book_management_frame_1 = LabelFrame(self.tab1,
                                             bd=1,
                                             height=50,
                                             borderwidth=2)
        book_management_frame_1.pack(fill="x", padx=1, pady=1)
        # Add buttons in book_management_frame_1
        btName = ["Add Book", "Return Book", "Delete Book"]
        # Dynamically adjust buttons configuration
        Grid.rowconfigure(book_management_frame_1, 0, weight=1)
        Grid.columnconfigure(book_management_frame_1, 0, weight=1)
        Grid.columnconfigure(book_management_frame_1, 1, weight=1)
        Grid.columnconfigure(book_management_frame_1, 2, weight=1)
        self.addBook = Button(book_management_frame_1,
                              text=btName[0],
                              font='bold',
                              command=self.new_book)
        self.addBook.grid(row=0, column=0, sticky="EW", ipadx=60)
        self.returnBook = Button(book_management_frame_1,
                                 text=btName[1],
                                 font='bold',
                                 command=self.return_book)
        self.returnBook.grid(row=0, column=1, sticky="EW")
        self.delBook = Button(book_management_frame_1,
                              text=btName[2],
                              font='bold',
                              command=self.delete_book)
        self.delBook.grid(row=0, column=2, sticky="EW")
        # Book Management Frame_2
        book_management_frame_2 = LabelFrame(self.tab1,
                                             bd=1,
                                             height=80,
                                             borderwidth=2)
        book_management_frame_2.pack(fill="x", padx=1, pady=1)
        # Create Combobox for Choice
        self.book_search_choice = StringVar()
        self.combo_book_search_choice = ttk.Combobox(
            book_management_frame_2,
            font=("", 10),
            textvariable=self.book_search_choice,
            postcommand=self.show_books)
        self.combo_book_search_choice.pack(side=LEFT, padx=10)
        # fill comboBox
        self.bookSearchChoice = [
            'All books', 'Issued book', "Not issued books"
        ]
        self.combo_book_search_choice['values'] = self.bookSearchChoice
        # select default
        self.combo_book_search_choice.current(0)
        self.entry_search_book = Entry(book_management_frame_2,
                                       width=40,
                                       bd=3,
                                       font=("", 15))
        self.entry_search_book.pack(side=LEFT, fill="x", padx=10, pady=10)
        self.bookSearchBtn = Button(book_management_frame_2,
                                    text='Search',
                                    padx=12,
                                    font="bold",
                                    command=self.book_search)
        self.bookSearchBtn.pack(side=LEFT, fill="x", padx=10, ipadx=20)
        # Book Management Frame_3
        book_management_frame_3 = LabelFrame(self.tab1,
                                             text="",
                                             bd=3,
                                             height=400,
                                             borderwidth=2,
                                             relief=SUNKEN)
        book_management_frame_3.pack(fill="x", padx=5, pady=5)
        # Create Tab1: Management
        self.book_managementBox = Listbox(book_management_frame_3,
                                          width=50,
                                          height=25)
        self.book_managementBox_sb = Scrollbar(book_management_frame_3,
                                               orient=VERTICAL)
        self.book_managementBox.grid(row=0, column=0, padx=(3, 0), sticky=N)
        self.book_managementBox_sb.config(
            command=self.book_managementBox.yview)
        self.book_managementBox.config(
            yscrollcommand=self.book_managementBox_sb.set)
        self.book_managementBox_sb.grid(row=0, column=0, sticky=N + S + E)
        # Details of books
        self.book_managementBox_detail = Listbox(book_management_frame_3,
                                                 width=80,
                                                 height=25)
        self.book_managementBox_detail.grid(row=0,
                                            column=1,
                                            padx=(10, 0),
                                            sticky=N)

        # Student Management in Tab2
        # Student Management Frame_1
        student_management_frame_1 = LabelFrame(self.tab2,
                                                bd=1,
                                                height=50,
                                                borderwidth=2)
        student_management_frame_1.pack(fill="x", padx=1, pady=1)
        # Add buttons in student_management_frame_1
        student_btName = ["Add Student", "Issue Book", "Delete Student"]
        # Dynamically adjust buttons configuration
        Grid.rowconfigure(student_management_frame_1, 0, weight=1)
        Grid.columnconfigure(student_management_frame_1, 0, weight=1)
        Grid.columnconfigure(student_management_frame_1, 1, weight=1)
        Grid.columnconfigure(student_management_frame_1, 2, weight=1)
        self.addStudent = Button(student_management_frame_1,
                                 text=student_btName[0],
                                 font='bold',
                                 command=self.new_student)
        self.addStudent.grid(row=0, column=0, sticky="EW", ipadx=60)
        self.iBook = Button(student_management_frame_1,
                            text=student_btName[1],
                            font='bold',
                            command=self.issue_book)
        self.iBook.grid(row=0, column=1, sticky="EW")
        self.delStudent = Button(student_management_frame_1,
                                 text=student_btName[2],
                                 font='bold',
                                 command=self.delete_student)
        self.delStudent.grid(row=0, column=2, sticky="EW")

        # Student Management Frame_2
        student_management_frame_2 = LabelFrame(self.tab2,
                                                bd=1,
                                                height=80,
                                                borderwidth=2)
        student_management_frame_2.pack(fill="x", padx=1, pady=1)
        # Create Combobox for Choice
        self.student_search_choice = StringVar()
        self.combo_student_search_choice = ttk.Combobox(
            student_management_frame_2,
            font=("", 10),
            textvariable=self.student_search_choice,
            postcommand=self.show_students)
        self.combo_student_search_choice.pack(side=LEFT, padx=10)
        # fill comboBox
        self.studentSearchChoice = [
            'All Students', 'Students who issued book',
            "Students who didn't issued"
        ]
        self.combo_student_search_choice['values'] = self.studentSearchChoice
        # select default
        self.combo_student_search_choice.current(0)
        self.entry_search_student = Entry(student_management_frame_2,
                                          width=40,
                                          bd=3,
                                          font=("", 15))
        self.entry_search_student.pack(side=LEFT, fill="x", padx=10, pady=10)
        self.studentSearchBtn = Button(student_management_frame_2,
                                       text='Search',
                                       padx=12,
                                       font="bold",
                                       command=self.student_search)
        self.studentSearchBtn.pack(side=LEFT, fill="x", padx=10, ipadx=20)

        # student Management Frame_3
        student_management_frame_3 = LabelFrame(self.tab2,
                                                text="",
                                                bd=3,
                                                height=400,
                                                borderwidth=2,
                                                relief=SUNKEN)
        student_management_frame_3.pack(fill="x", padx=5, pady=5)
        # Create Tab1: Management
        self.student_managementBox = Listbox(student_management_frame_3,
                                             width=50,
                                             height=25)
        self.student_managementBox_sb = Scrollbar(student_management_frame_3,
                                                  orient=VERTICAL)
        self.student_managementBox.grid(row=0, column=0, padx=(3, 0), sticky=N)
        self.student_managementBox_sb.config(
            command=self.student_managementBox.yview)
        self.student_managementBox.config(
            yscrollcommand=self.student_managementBox_sb.set)
        self.student_managementBox_sb.grid(row=0, column=0, sticky=N + S + E)
        # Details of students
        self.student_managementBox_detail = Listbox(student_management_frame_3,
                                                    width=80,
                                                    height=25)
        self.student_managementBox_detail.grid(row=0,
                                               column=1,
                                               padx=(10, 0),
                                               sticky=N)
        self.show_students()
        self.show_books()

    # show student list in message box
    def show_students(self):
        cur = db.conn.cursor()
        if self.studentSearchChoice[0] == self.combo_student_search_choice.get(
        ):
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            print("ALL student")
            students = cur.execute("SELECT * FROM students").fetchall()
            counter = 0
            for student in students:
                self.student_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + student[0] + "  ( ID: " +
                    student[3] + " )")
                counter += 1
        elif self.studentSearchChoice[
                1] == self.combo_student_search_choice.get():
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            print("Issued student")
            students = cur.execute("SELECT * FROM issued").fetchall()
            counter = 0
            for student in students:
                value1 = student[1]
                # print(value)
                studentDetail = cur.execute(
                    "SELECT * FROM students WHERE student_id LIKE ?",
                    ('%' + value1 + '%', )).fetchall()
                # print(studentDetail)
                self.student_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + studentDetail[0][0] + "( ID : " +
                    studentDetail[0][3] + " )")
                counter += 1
        else:
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            print("not issued student")
            students = cur.execute(
                "SELECT * FROM students WHERE student_id NOT IN (SELECT student_id FROM issued)"
            ).fetchall()
            # print(students)
            counter = 0
            for student in students:
                self.student_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + student[0] + " ( ID : " +
                    student[3] + " )")

        # show student info
        def showStudentInfo(evt):
            if self.studentSearchChoice[
                    0] == self.combo_student_search_choice.get():
                value2 = None
                try:
                    value2 = str(
                        self.student_managementBox.get(
                            self.student_managementBox.curselection()))
                except Exception as e:
                    print(e)
                finally:
                    if value2 != None:
                        ID1 = value2.split(')')[1].split(': ')[1][0:3]
                        # print(ID1)
                        self.student_managementBox_detail.delete(0, END)
                        student1 = cur.execute(
                            "SELECT * FROM students WHERE student_id=?",
                            (ID1, ))
                        student_info = student1.fetchall()
                        # print(student_info)
                        self.student_managementBox_detail.insert(
                            0, "Student Name : " + student_info[0][0])
                        self.student_managementBox_detail.insert(
                            1, "Father Name : " + student_info[0][2])
                        self.student_managementBox_detail.insert(
                            2, "Phone Number : " + student_info[0][1])
                    else:
                        print('Value2 : None')
            elif self.studentSearchChoice[
                    1] == self.combo_student_search_choice.get():
                value3 = None
                try:
                    value3 = str(
                        self.student_managementBox.get(
                            self.student_managementBox.curselection()))
                except Exception as e:
                    print(e)
                finally:
                    if value3 != None:
                        ID2 = value3.split(') ')[1].split(': ')[1][0:3]
                        self.student_managementBox_detail.delete(0, END)
                        print(ID2)
                        student2 = cur.execute(
                            "SELECT * FROM students WHERE student_id=?",
                            (ID2, )).fetchall()
                        print(student2)
                        self.student_managementBox_detail.insert(
                            0, "Student Name : " + student2[0][0])
                        self.student_managementBox_detail.insert(
                            1, "Father Name : " + student2[0][2])
                        self.student_managementBox_detail.insert(
                            2, "Phone Number : " + student2[0][1])
                    else:
                        print('Value3 : None')
            else:
                value4 = None
                try:
                    value4 = str(
                        self.student_managementBox.get(
                            self.student_managementBox.curselection()))
                    print(value4)
                except Exception as e:
                    if value4 != None:
                        ID3 = value4.split(') ')[1].split(': ')[1][0:3]
                        print(ID3)
                        self.student_managementBox_detail.delete(0, END)
                        student3 = cur.execute(
                            "SELECT * FROM students WHERE student_id=?",
                            (ID3, )).fetchall()
                        print(student3)
                        self.student_managementBox_detail.insert(
                            0, "Student Name : " + student3[0][0])
                        self.student_managementBox_detail.insert(
                            1, "Father Name : " + student3[0][2])
                        self.student_managementBox_detail.insert(
                            2, "Phone Number : " + student3[0][1])
                    else:
                        print('Value4 : None')

        # student_managementBox bind with student_managementBox_detail
        self.student_managementBox.bind('<<ListboxSelect>>', showStudentInfo)

    def student_search(self):
        cur = db.conn.cursor()
        comboBoxEntry = self.combo_student_search_choice.get()
        studentSearchEntry = self.entry_search_student.get()
        # print(comboBoxEntry)
        # print(studentSearchEntry)
        if comboBoxEntry == self.studentSearchChoice[0]:
            searchQuery = cur.execute(
                "SELECT * FROM students where sname LIKE ?",
                ('%' + studentSearchEntry + '%', )).fetchall()
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            counter = 0
            for student in searchQuery:
                self.student_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + student[0] + "  ( ID: " +
                    student[3] + " )")
                counter += 1
        elif comboBoxEntry == self.studentSearchChoice[1]:
            searchQuery = cur.execute(
                "SELECT * FROM students WHERE sname LIKE ?",
                ('%' + studentSearchEntry + '%', )).fetchall()
            # print(searchQuery)
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            counter = 0
            for student in searchQuery:
                cur = db.conn.cursor()
                value = student[3]
                # print(value)
                studentDetail = cur.execute(
                    "SELECT count(*) FROM issued WHERE student_id=?",
                    (value, )).fetchall()
                print(studentDetail[0][0])
                print(student)
                if studentDetail[0][0] != 0:
                    counter += 1
                    self.student_managementBox.insert(
                        counter,
                        str(counter) + ") " + student[0] + " ( ID : " +
                        student[3] + " )")

        else:
            searchQuery = cur.execute(
                "SELECT * FROM students WHERE student_id NOT IN (SELECT student_id FROM issued) AND (sname LIKE ?)",
                ('%' + studentSearchEntry + '%', )).fetchall()
            print(searchQuery)
            self.student_managementBox.delete(0, END)
            self.student_managementBox_detail.delete(0, END)
            counter = 0
            for student in searchQuery:
                cur = db.conn.cursor()
                # print(student)
                counter += 1
                self.student_managementBox.insert(
                    counter,
                    str(counter) + ") " + student[0] + " ( ID : " +
                    student[3] + " )")

    # show student list in message box
    def show_books(self):
        cur = db.conn.cursor()
        if self.bookSearchChoice[0] == self.combo_book_search_choice.get():
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            print("All Books")
            books = cur.execute("SELECT * FROM books").fetchall()
            # print(books)
            counter = 0
            for book in books:
                self.book_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + book[0] + "  ( ID: " + book[3] +
                    " )")
                counter += 1
        elif self.bookSearchChoice[1] == self.combo_book_search_choice.get():
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            print("Issued books")
            books = cur.execute("SELECT * FROM issued").fetchall()
            counter = 0
            for book in books:
                value1 = book[0]
                # print(value1)
                bookDetail = cur.execute(
                    "SELECT * FROM books WHERE book_id LIKE ?",
                    ('%' + value1 + '%', )).fetchall()
                print(bookDetail)
                self.book_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + bookDetail[0][0] + "( ID : " +
                    bookDetail[0][3] + " )")
                counter += 1
        else:
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            print("not issued books")
            books = cur.execute(
                "SELECT * FROM books WHERE book_id NOT IN (SELECT book_id FROM issued)"
            ).fetchall()
            # print(books)
            counter = 0
            for book in books:
                self.book_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + book[0] + " ( ID : " + book[3] +
                    " )")
                counter += 1

        # show student info
        def showBookInfo(evt):
            if self.bookSearchChoice[0] == self.combo_book_search_choice.get():
                value2 = None
                try:
                    value2 = str(
                        self.book_managementBox.get(
                            self.book_managementBox.curselection()))
                except Exception as e:
                    print(e)
                finally:
                    if value2 != None:
                        ID1 = value2.split(')')[1].split(': ')[1][0:3]
                        print(ID1)
                        self.book_managementBox_detail.delete(0, END)
                        book1 = cur.execute(
                            "SELECT * FROM books WHERE book_id=?", (ID1, ))
                        book_info = book1.fetchall()
                        print(book_info)
                        self.book_managementBox_detail.insert(
                            0, "Book Name   : " + book_info[0][0])
                        self.book_managementBox_detail.insert(
                            1, "Author Name : " + book_info[0][1])
                        self.book_managementBox_detail.insert(
                            2, "Category    : " + book_info[0][2])
                    else:
                        print('Value2 : None')
            elif self.bookSearchChoice[1] == self.combo_book_search_choice.get(
            ):
                value3 = None
                try:
                    value3 = str(
                        self.book_managementBox.get(
                            self.book_managementBox.curselection()))
                except Exception as e:
                    print(e)
                finally:
                    if value3 != None:
                        ID2 = value3.split(') ')[1].split(': ')[1][0:3]
                        self.book_managementBox_detail.delete(0, END)
                        print(ID2)
                        book2 = cur.execute(
                            "SELECT * FROM books WHERE book_id=?",
                            (ID2, )).fetchall()
                        print(book2)
                        self.book_managementBox_detail.insert(
                            0, "Book Name   : " + book2[0][0])
                        self.book_managementBox_detail.insert(
                            1, "Author Name : " + book2[0][1])
                        self.book_managementBox_detail.insert(
                            2, "Category    : " + book2[0][2])
                    else:
                        print('Value3 : None')
            else:
                value4 = None
                try:
                    value4 = str(
                        self.book_managementBox.get(
                            self.book_managementBox.curselection()))
                except Exception as e:
                    print(e)
                finally:
                    if value4 != None:
                        print(value4)
                        ID3 = value4.split(') ')[1].split(': ')[1][0:3]
                        print(ID3)
                        self.book_managementBox_detail.delete(0, END)
                        book3 = cur.execute(
                            "SELECT * FROM books WHERE book_id=?",
                            (ID3, )).fetchall()
                        print(book3)
                        self.book_managementBox_detail.insert(
                            0, "Book Name    : " + book3[0][0])
                        self.book_managementBox_detail.insert(
                            1, "Author Name  : " + book3[0][1])
                        self.book_managementBox_detail.insert(
                            2, "Category     : " + book3[0][2])
                    else:
                        print('Value4 : None')

        # student_managementBox bind with student_managementBox_detail
        self.book_managementBox.bind('<<ListboxSelect>>', showBookInfo)

    def book_search(self):
        cur = db.conn.cursor()
        comboBoxEntry = self.combo_book_search_choice.get()
        bookSearchEntry = self.entry_search_book.get()
        # print(comboBoxEntry)
        # print(bookSearchEntry)
        if comboBoxEntry == self.bookSearchChoice[0]:
            searchQuery = cur.execute(
                "SELECT * FROM books where bname LIKE ?",
                ('%' + bookSearchEntry + '%', )).fetchall()
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            counter = 0
            for book in searchQuery:
                self.book_managementBox.insert(
                    counter,
                    str(counter + 1) + ") " + book[0] + "  ( ID: " + book[3] +
                    " )")
                counter += 1
        elif comboBoxEntry == self.bookSearchChoice[1]:
            searchQuery = cur.execute(
                "SELECT * FROM books WHERE bname LIKE ?",
                ('%' + bookSearchEntry + '%', )).fetchall()
            # print(searchQuery)
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            counter = 0
            for book in searchQuery:
                cur = db.conn.cursor()
                value = book[3]
                print(value)
                bookDetail = cur.execute(
                    "SELECT count(*) FROM issued WHERE book_id=?",
                    (value, )).fetchall()
                # print(bookDetail)
                # print(book)
                if bookDetail[0][0] != 0:
                    counter += 1
                    self.book_managementBox.insert(
                        counter,
                        str(counter) + ") " + book[0] + " ( ID : " + book[3] +
                        " )")

        else:
            searchQuery = cur.execute(
                "SELECT * FROM books WHERE book_id NOT IN (SELECT book_id FROM issued) AND (bname LIKE ?)",
                ('%' + bookSearchEntry + '%', )).fetchall()
            print(searchQuery)
            self.book_managementBox.delete(0, END)
            self.book_managementBox_detail.delete(0, END)
            counter = 0
            for book in searchQuery:
                cur = db.conn.cursor()
                # print(book)
                counter += 1
                self.book_managementBox.insert(
                    counter,
                    str(counter) + ") " + book[0] + " ( ID : " + book[3] +
                    " )")

    @staticmethod
    def new_student():
        newStudent = addstudent.AddStudent()

    @staticmethod
    def new_book():
        newBook = addbook.AddBook()

    @staticmethod
    def return_book():
        ret_book_obj = returnbook.ReturnBook()

    @staticmethod
    def delete_book():
        del_book_obj = deletebook.DeleteBook()

    @staticmethod
    def issue_book():
        issue_book_obj = issuebook.IssueBook()

    @staticmethod
    def delete_student():
        delete_student_obj = deletestudent.DeleteStudent()
Ejemplo n.º 33
0
class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master

        self.master.title("Color Clusters")
        self.pack(fill=BOTH, expand=1)
        self.init_menu()

        self.input_image = Image.new("RGBA", _img_size, 0)
        photo = ImageTk.PhotoImage(
            img_utils.add_transparency_grid(self.input_image))
        self.input_label = Label(self, image=photo)
        self.input_label.image = photo
        self.input_label.pack(side=LEFT)

        self.output_image = Image.new("RGBA", _img_size, 0)
        photo = ImageTk.PhotoImage(
            img_utils.add_transparency_grid(self.input_image))
        self.out_label = Label(self, image=photo)
        self.out_label.image = photo
        self.out_label.pack(side=RIGHT)

        self.button_list = []
        self.timerCount = 0
        self.messageString = None
        self.timerString = None
        self.thread_queue = queue.Queue()
        self.algorithm_thread = None
        self.thread_run_flag = None

        self.algorithms = Notebook(self)
        self.algorithms.pack(fill=BOTH, expand=1)

    def init_menu(self):
        menu = Menu(self.master)
        self.master.config(menu=menu)

        file = Menu(menu)
        file.add_command(label="Load Image...", command=self.load_image)
        file.add_command(label="Save Image...", command=self.save_image)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File", menu=file)

        ctrl = Menu(menu)
        ctrl.add_command(label="Suggest Stop", command=self.halt_thread)
        menu.add_cascade(label="Control", menu=ctrl)

    def load_image(self):
        filename = filedialog.askopenfilename(initialdir="../tests/images",
                                              title="Choose an image")
        if filename is "":
            return
        self.input_image = Image.open(filename)
        self.reload_image_label(self.input_image, self.input_label)

    def save_image(self):
        filename = filedialog.asksaveasfilename(parent=self,
                                                initialdir="../tests/images",
                                                initialfile="output.png",
                                                title="Save an image",
                                                defaultextension=".png",
                                                filetypes=(("PNG image",
                                                            "*.png"), ))
        if filename is "":
            return
        self.output_image.save(filename)

    def reload_image_label(self, image, label):
        if image.size[0] > _img_size[0] or image.size[1] > _img_size[1]:
            img = ImageOps.scale(
                image,
                min((expected / actual
                     for expected, actual in zip(_img_size, image.size))))
        else:
            img = image

        if img.mode != "RGB":
            img = img_utils.add_transparency_grid(img)

        img_tk = ImageTk.PhotoImage(img)

        label.configure(image=img_tk)
        label.image = img_tk

    def set_button_state(self, state):
        for button in self.button_list:
            button.config(state=state)

    def run_algorithm(self, algorithm_runner, **kwargs):
        self.messageString.set("Running!")
        self.set_button_state(DISABLED)

        # set required arguments
        self.thread_run_flag = BooleanVar()
        self.thread_run_flag.set(True)
        if 'image' not in kwargs:
            kwargs['image'] = self.input_image
        if 'run_var' not in kwargs:
            kwargs['run_var'] = self.thread_run_flag
        if 'thread_queue' not in kwargs:
            kwargs['thread_queue'] = self.thread_queue

        # start the algorithm on a separate thread
        self.algorithm_thread = threading.Thread(target=algorithm_runner,
                                                 kwargs=kwargs,
                                                 daemon=True)
        self.algorithm_thread.start()
        self.after(_delay_time, self.listen_for_result)

    def halt_thread(self):
        if self.thread_run_flag is not None:
            self.thread_run_flag.set(False)

    def add_algorithm(self, name, algorithm, **kwargs):
        options = Frame(self.algorithms)
        options.pack(fill=BOTH, expand=1)
        message = StringVar()
        timer = StringVar()
        Label(options, textvariable=timer).pack(side=BOTTOM)
        Message(options, textvariable=message,
                width=_msg_width).pack(side=BOTTOM)

        arg_entries = {}
        for key in kwargs:
            if isinstance(kwargs[key][1], bool):
                var = BooleanVar()
                var.set(kwargs[key][1])
                arg_entries[key] = var
                Checkbutton(options, text=kwargs[key][0],
                            variable=var).pack(pady=5)
            else:
                Label(options, text=kwargs[key][0]).pack()
                var = StringVar()
                var.set(str(kwargs[key][1]))
                arg_entries[key] = var
                if key in _dist_param_names:
                    OptionMenu(options, var, *_function_names).pack(pady=5)
                    Label(options, text="Scale factor:").pack()
                    var = StringVar()
                    var.set("(1,1,1,1)")
                    arg_entries[key + "_scale_"] = var

                    Entry(options, textvariable=var).pack(pady=5)
                else:
                    Entry(options, textvariable=var).pack(pady=5)

        # capture the algorithm. not sure if this is necessary to build the closure?
        algorithm_runner = algorithm

        def callback():
            self.messageString = message
            self.timerString = timer
            self.timerCount = 0
            args = {}
            for key in arg_entries:
                if key in _dist_param_names:
                    scale = literal_eval(arg_entries[key + "_scale_"].get())
                    func = dist_func.decode_string(arg_entries[key].get())
                    if scale.count(1) != len(scale):
                        print('using scale')
                        func = dist_func.scaled_distance(func, scale)
                    args[key] = func
                elif key.endswith("_scale_"):
                    pass  #ignore the internally used scale field
                else:
                    args[key] = arg_entries[key].get()
            self.run_algorithm(algorithm_runner, **args)

        button = Button(options, text="Run %s" % name, command=callback)
        button.pack()
        self.button_list.append(button)
        self.algorithms.add(options, text=name)

    def listen_for_result(self):
        self.timerCount += 1
        self.timerString.set("Time Elapsed: %.1f seconds" %
                             (self.timerCount * _delay_time / 1000))

        try:
            # empty the queue
            while True:
                result = self.thread_queue.get_nowait()
                if isinstance(result, str):
                    self.messageString.set(result)
                elif isinstance(result, Image.Image):
                    self.output_image = result
                    self.messageString.set("Done!")
                    self.set_button_state(NORMAL)
                    self.reload_image_label(self.output_image, self.out_label)
                    # wait for the thread to finish
                    self.algorithm_thread.join()
                    # clear the thread
                    self.algorithm_thread = None
                    self.thread_run_flag = None
        except queue.Empty:
            # continue waiting for an image result
            if self.algorithm_thread is not None and self.algorithm_thread.is_alive(
            ):
                self.master.after(_delay_time, self.listen_for_result)
            # if the thread stopped unexpectedly, stop checking for it
            elif self.algorithm_thread is not None:
                self.messageString.set("Error: Thread stopped unexpectedly.")
                self.set_button_state(NORMAL)
                self.algorithm_thread = None
                self.thread_run_flag = None

    def client_exit(self):
        if self.algorithm_thread is not None:
            # do we need to do anything with unfinished threads?
            pass
        exit()
Ejemplo n.º 34
0
from tkinter import *
from tkinter.ttk import Notebook
import subprocess as sub

def addText(tab):
    tab.insert(END, sub.Popen('python "C:\\Users\\Bosua\\Desktop\\cmd.py"', stdout=sub.PIPE, stderr=sub.PIPE).communicate()[0])

root = Tk()

nb = Notebook(root, height=240, width=480)
tabs = {"foo": [], "bara": []}

for tabname in tabs:
    tab = Text(nb)
    tabs[tabname] = tab
    nb.add(tab, text= tabname)
nb.pack()

# Button(root, text= "Add text!", command = lambda: addText(tabs["foo"])).pack()
quitButton = Button(root, text="Quit", command=root.quit)
quitButton.pack(side=RIGHT, padx=5, pady=5)

bakupButton = Button(root, text="Backup", command=lambda: addText(tabs["foo"]))
bakupButton.pack(side=RIGHT)


root.mainloop()
Ejemplo n.º 35
0
    def initialize(self):
        self.master.title("NENR DZ5 - Miljenko Šuflaj")
        self.pack(fill="both", expand=True)

        notebook = Notebook(self)
        notebook.pack()

        record_gestures_frame = Frame(self)
        classify_gestures_frame = Frame(self)

        notebook.add(record_gestures_frame, text="Zabilježi geste")
        notebook.add(classify_gestures_frame, text="Klasificiraj geste")

        notebook.enable_traversal()
        notebook.select(record_gestures_frame)

        gesture_classification_frame = Frame(classify_gestures_frame)
        gesture_record_frame_2 = Frame(classify_gestures_frame)

        gesture_classification_frame.pack(side="top", fill="x", expand=True)
        gesture_record_frame_2.pack(fill="both")

        # region Record gesture tab
        gesture_info_frame = Frame(record_gestures_frame)
        gesture_record_frame = Frame(record_gestures_frame)
        gesture_end_frame = Frame(record_gestures_frame)
        gesture_info_frame.pack(side="top", fill="x")
        gesture_record_frame.pack(fill="both")
        gesture_end_frame.pack(side="bottom", fill="x")

        gesture_name_menu = Menubutton(gesture_info_frame,
                                       text="Odaberi gestu za bilježenje...")
        gesture_name_menu.menu = Menu(gesture_name_menu, tearoff=0)
        gesture_name_menu["menu"] = gesture_name_menu.menu

        for i, label in enumerate(GestureWindow.labels):
            gesture_name_menu.menu.add_command(label=label,
                                               command=self.switch_record(i))

        self.__recorded_gesture_label = Label(gesture_info_frame)
        gesture_record_canvas = Canvas(gesture_record_frame,
                                       width=700,
                                       height=475,
                                       bg="white")
        gesture_record_canvas.current_coords = None
        gesture_record_canvas.records = list()
        gesture_record_save_button = Button(gesture_end_frame,
                                            text="Pohrani u .tsv",
                                            command=self.save_data)
        gesture_record_delete_button = Button(gesture_end_frame,
                                              text="Zaboravi učitane podatke",
                                              command=self.delete_internal)

        gesture_name_menu.pack(side="left",
                               fill="x",
                               padx=5,
                               pady=5,
                               expand=True)
        self.__recorded_gesture_label.pack(side="left",
                                           fill="x",
                                           padx=5,
                                           pady=5)
        gesture_record_canvas.pack(fill="both", padx=5, pady=5, expand=True)
        gesture_record_delete_button.pack(side="left",
                                          fill="x",
                                          padx=5,
                                          pady=5)
        gesture_record_save_button.pack(side="right", fill="x", padx=5, pady=5)

        self.switch_record(self.__recorded_gesture_index)()
        # endregion

        # region Classify gesture tab
        gesture_classification_frame = Frame(classify_gestures_frame)
        gesture_record_frame_2 = Frame(classify_gestures_frame)

        gesture_classification_frame.pack(side="top", fill="x", expand=True)
        gesture_record_frame_2.pack(fill="both")

        classification_labels = list()
        self.__classification_outputs = list()

        for category in GestureWindow.labels:
            classification_labels.append(
                Label(gesture_classification_frame, text=category))
            self.__classification_outputs.append(
                Label(gesture_classification_frame,
                      text=f"{0.:.01f}%",
                      font=("helvetica", 8)))
            classification_blank = Label(gesture_classification_frame)

            classification_labels[-1].pack(side="left",
                                           fill="x",
                                           padx=5,
                                           pady=5)
            self.__classification_outputs[-1].pack(side="left",
                                                   fill="x",
                                                   padx=5,
                                                   pady=5)
            classification_blank.pack(side="left", fill="x", padx=50, pady=5)

        gesture_record_canvas_2 = Canvas(gesture_record_frame_2,
                                         width=700,
                                         height=525,
                                         bg="white")
        gesture_record_canvas_2.current_coords = None
        gesture_record_canvas_2.records = list()

        gesture_record_canvas_2.pack(side="left",
                                     fill="both",
                                     padx=5,
                                     pady=5,
                                     expand=True)
        # endregion

        # region Functionality
        for record_canvas in [gesture_record_canvas, gesture_record_canvas_2]:
            draw_function = self.get_draw_on_canvas_function(record_canvas)

            record_canvas.bind("<B1-Motion>", draw_function)
            record_canvas.bind("<ButtonRelease-1>", draw_function)

        self.__root_window.bind(
            "<BackSpace>",
            self.get_delete_currently_drawn(gesture_record_canvas))
        self.__root_window.bind(
            "<Return>",
            self.get_record_gesture_function(gesture_record_canvas))

        gesture_record_canvas_2.bind(
            "<Leave>",
            self.get_evaluate_gesture_function(gesture_record_canvas_2))
        self.__root_window.bind(
            "<Delete>",
            self.get_delete_currently_drawn(gesture_record_canvas_2))
Ejemplo n.º 36
0
class TranslateBook(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title("Translation Book v3")
        self.geometry("500x300")

        self.menu = tk.Menu(self, bg="lightgrey", fg="black")

        self.languages_menu = tk.Menu(self.menu,
                                      tearoff=0,
                                      bg="lightgrey",
                                      fg="black")
        self.languages_menu.add_command(label="Add New",
                                        command=self.show_new_language_popup)
        self.languages_menu.add_command(
            label="Portuguese",
            command=lambda: self.add_new_tab(
                LanguageTab(self, "Portuguese", "pt")))

        self.menu.add_cascade(label="Languages", menu=self.languages_menu)

        self.config(menu=self.menu)

        self.notebook = Notebook(self)

        self.language_tabs = []

        english_tab = ttk.Frame(self.notebook)

        self.translate_button = ttk.Button(english_tab,
                                           text="Translate",
                                           command=self.translate)
        self.translate_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.english_entry = tk.Text(english_tab, bg="white", fg="black")
        self.english_entry.pack(side=tk.TOP, expand=1)

        self.notebook.add(english_tab, text="English")

        self.notebook.pack(fill=tk.BOTH, expand=1)

    def translate(self, text=None):
        if len(self.language_tabs) < 1:
            msg.showerror("No Languages",
                          "No languages added. Please add some from the menu")
            return

        if not text:
            text = self.english_entry.get(1.0, tk.END).strip()

        url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}"

        try:
            for language in self.language_tabs:
                full_url = url.format("en", language.lang_code, text)
                r = requests.get(full_url)
                r.raise_for_status()
                translation = r.json()[0][0][0]
                language.translation_var.set(translation)
        except Exception as e:
            msg.showerror("Translation Failed", str(e))
        else:
            msg.showinfo("Translations Successful",
                         "Text successfully translated")

    def add_new_tab(self, tab):
        self.language_tabs.append(tab)
        self.notebook.add(tab, text=tab.lang_name)

        try:
            self.languages_menu.entryconfig(tab.lang_name, state="disabled")
        except:
            # language isn't in menu.
            pass

    def show_new_language_popup(self):
        NewLanguageForm(self)
Ejemplo n.º 37
0
class PomodoroParams(Frame):
    def __init__(self, parent, **options):
        """ créer le Toplevel permettant de modifier les paramètres """
        Frame.__init__(self, parent, **options)

        self.onglets = Notebook(self)
        self.onglets.pack(fill='both', expand=True)
        self.im_color = PhotoImage(master=self, file=IM_COLOR)
        self.im_plus = PhotoImage(master=self, file=IM_ADD)
        self.im_moins = PhotoImage(master=self, file=IM_DEL)

        self.okfct = self.register(only_nb)

        self.style = Style(self)

        self.nb_task = len(CONFIG.options("PomodoroTasks"))

        # --- Général (temps, police et langue)
        self.general = Frame(self.onglets, padding=10)
        self.general.columnconfigure(1, weight=1)
        self.onglets.add(self.general, text=_("General"))

        # --- --- Temps
        Label(self.general, text=_("Times (min)"),
              style='title.TLabel').grid(row=0,
                                         pady=4,
                                         padx=(2, 10),
                                         sticky="w")
        self.time_frame = Frame(self.general)
        self.time_frame.grid(row=0, column=1, sticky="w", padx=4)
        Label(self.time_frame, text=_("Work")).grid(row=0, padx=4, column=0)
        self.travail = Entry(self.time_frame,
                             width=4,
                             justify='center',
                             validatecommand=(self.okfct, '%P'),
                             validate='key')
        self.travail.insert(0, CONFIG.get("Pomodoro", "work_time"))
        self.travail.grid(row=0, column=1, padx=(0, 10))
        Label(self.time_frame, text=_("Break")).grid(row=0, column=2, padx=4)
        self.pause = Entry(self.time_frame,
                           width=4,
                           justify='center',
                           validatecommand=(self.okfct, '%P'),
                           validate='key')
        self.pause.insert(0, CONFIG.get("Pomodoro", "break_time"))
        self.pause.grid(row=0, column=3, padx=(0, 10))
        Label(self.time_frame, text=_("Rest")).grid(row=0, column=4, padx=4)
        self.rest = Entry(self.time_frame,
                          width=4,
                          justify='center',
                          validatecommand=(self.okfct, '%P'),
                          validate='key')
        self.rest.insert(0, CONFIG.get("Pomodoro", "rest_time"))
        self.rest.grid(row=0, column=5)

        Separator(self.general, orient='horizontal').grid(row=1,
                                                          columnspan=2,
                                                          sticky="ew",
                                                          pady=10)

        # --- --- Police
        Label(self.general, text=_("Font"),
              style='title.TLabel').grid(row=2, sticky='nw', padx=(2, 10))
        self.font = FontFrame(self.general,
                              font=CONFIG.get('Pomodoro', 'font'),
                              sample_text="02:17")
        self.font.grid(row=2, column=1, padx=4, sticky='w')

        Separator(self.general, orient='horizontal').grid(row=3,
                                                          columnspan=2,
                                                          sticky="ew",
                                                          pady=10)

        # --- --- Opacity
        self.opacity = OpacityFrame(self.general)
        self.opacity.grid(row=5, columnspan=2, sticky='w', padx=(2, 4), pady=4)

        Separator(self.general, orient='horizontal').grid(row=6,
                                                          columnspan=2,
                                                          sticky="ew",
                                                          pady=10)

        # --- --- Son
        self.sound = SoundFrame(self.general,
                                CONFIG.get("Pomodoro", "beep"),
                                mute=CONFIG.getboolean("Pomodoro", "mute"),
                                label=_("Sound"),
                                style='title.TLabel')
        self.sound.grid(row=7, columnspan=2, sticky='ew', pady=4)

        # --- Couleurs
        self.couleurs = Frame(self.onglets, padding=10)
        self.couleurs.columnconfigure(3, weight=1)
        self.onglets.add(self.couleurs, text=_("Colors"))

        self.bg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro",
                                                       "background"),
                             _("Background"))
        self.work_bg = ColorFrame(self.couleurs,
                                  CONFIG.get("Pomodoro", "work_bg"),
                                  _("Background"))
        self.break_bg = ColorFrame(self.couleurs,
                                   CONFIG.get("Pomodoro", "break_bg"),
                                   _("Background"))
        self.rest_bg = ColorFrame(self.couleurs,
                                  CONFIG.get("Pomodoro", "rest_bg"),
                                  _("Background"))
        self.fg = ColorFrame(self.couleurs, CONFIG.get("Pomodoro",
                                                       "foreground"),
                             _("Foreground"))
        self.work_fg = ColorFrame(self.couleurs,
                                  CONFIG.get("Pomodoro", "work_fg"),
                                  _("Foreground"))
        self.break_fg = ColorFrame(self.couleurs,
                                   CONFIG.get("Pomodoro", "break_fg"),
                                   _("Foreground"))
        self.rest_fg = ColorFrame(self.couleurs,
                                  CONFIG.get("Pomodoro", "rest_fg"),
                                  _("Foreground"))

        Label(self.couleurs, text=_("General"),
              style='title.TLabel').grid(row=0,
                                         column=0,
                                         pady=4,
                                         padx=(2, 10),
                                         sticky="w")
        self.bg.grid(row=0, column=1, sticky='e', padx=8, pady=4)
        self.fg.grid(row=0, column=2, sticky='e', padx=8, pady=4)
        Separator(self.couleurs, orient='horizontal').grid(row=1,
                                                           sticky="ew",
                                                           pady=10,
                                                           columnspan=4)
        Label(self.couleurs, text=_("Work"),
              style='title.TLabel').grid(row=2,
                                         column=0,
                                         pady=4,
                                         padx=(2, 10),
                                         sticky="w")
        self.work_bg.grid(row=2, column=1, sticky='e', padx=8, pady=4)
        self.work_fg.grid(row=2, column=2, sticky='e', padx=8, pady=4)
        Separator(self.couleurs, orient='horizontal').grid(row=3,
                                                           sticky="ew",
                                                           pady=10,
                                                           columnspan=4)
        Label(self.couleurs, text=_("Break"),
              style='title.TLabel').grid(row=4,
                                         column=0,
                                         pady=4,
                                         padx=(2, 10),
                                         sticky="w")
        self.break_bg.grid(row=4, column=1, sticky='e', padx=8, pady=4)
        self.break_fg.grid(row=4, column=2, sticky='e', padx=8, pady=4)
        Separator(self.couleurs, orient='horizontal').grid(row=5,
                                                           sticky="ew",
                                                           pady=10,
                                                           columnspan=4)
        Label(self.couleurs, text=_("Rest"),
              style='title.TLabel').grid(row=6,
                                         column=0,
                                         pady=4,
                                         padx=(2, 10),
                                         sticky="w")
        self.rest_bg.grid(row=6, column=1, sticky='e', padx=8, pady=4)
        self.rest_fg.grid(row=6, column=2, sticky='e', padx=8, pady=4)

        # --- Tasks
        self.stats = Frame(self.onglets, padding=10)
        self.stats.columnconfigure(0, weight=1)
        self.stats.rowconfigure(2, weight=1)
        self.onglets.add(self.stats, text=_("Tasks"))
        # graph legend
        legend_frame = Frame(self.stats)
        Label(legend_frame,
              style='title.TLabel',
              text=_('Maximum number of rows in the legend')).pack(side='left')
        self.legend_row_nb = Entry(legend_frame,
                                   width=4,
                                   justify='center',
                                   validatecommand=(self.okfct, '%P'),
                                   validate='key')
        self.legend_row_nb.insert(
            0, CONFIG.get('Pomodoro', 'legend_max_height', fallback='6'))
        self.legend_row_nb.pack(side='left', padx=4)

        # task colors
        can = Canvas(self.stats,
                     bg=self.style.lookup('TFrame', 'background'),
                     highlightthickness=0,
                     width=1,
                     relief='flat')
        scroll = AutoScrollbar(self.stats,
                               orient='vertical',
                               command=can.yview)
        can.configure(yscrollcommand=scroll.set)
        self.task_frame = Frame(can)
        can.create_window(0, 0, anchor='nw', window=self.task_frame)

        tasks = CONFIG.options("PomodoroTasks")
        tasks.sort()
        cmap = [CONFIG.get("PomodoroTasks", task) for task in tasks]
        self.tasks = {}
        self._tasks_btns = {}
        for i, (coul, task) in enumerate(zip(cmap, tasks)):
            self.tasks[task] = ColorFrame(self.task_frame, coul,
                                          task.capitalize())
            self.tasks[task].grid(row=i, column=0, sticky='e', padx=4, pady=4)
            b = Button(self.task_frame,
                       image=self.im_moins,
                       padding=2,
                       command=lambda t=task: self.del_task(t))
            b.grid(row=i, column=1, sticky='w', padx=4, pady=4)
            self._tasks_btns[task] = b
        if len(tasks) == 1:
            self._tasks_btns[tasks[0]].state(['disabled'])

        legend_frame.grid(row=0, columnspan=2, sticky='w', pady=4)
        Label(self.stats,
              text=_('Colors in the statistic graph'),
              style='title.TLabel').grid(row=1, column=0, sticky='w', pady=4)
        can.grid(row=2, column=0, sticky='ewns')
        scroll.grid(row=2, column=1, sticky='ns')
        Button(self.stats, image=self.im_plus,
               command=self.add_task).grid(row=3, column=0, sticky='w')

        self.update_idletasks()
        can.configure(width=self.task_frame.winfo_reqwidth())
        can.configure(scrollregion=can.bbox('all'))
        can.bind('<4>', lambda e: self._scroll(e, -1))
        can.bind('<5>', lambda e: self._scroll(e, 1))
        self.task_frame.bind(
            '<Configure>',
            lambda e: can.configure(scrollregion=can.bbox('all')))

    def _scroll(self, event, delta):
        if event.widget.yview() != (0, 1):
            event.widget.yview_scroll(delta, 'units')

    def choix_couleur(self, type_mode):
        """ sélection de la couleur du fond/texte pour chaque mode (travail/pause/repos) """
        coul = askcolor(self.style.lookup(type_mode + ".TButton",
                                          'background'),
                        parent=self)
        if coul:
            self.style.configure(type_mode + ".TButton", background=coul)

    def coul_stat(self, i):
        """ choix des couleurs pour l'affichage des stats """
        coul = askcolor(self.style.lookup("t%i.TButton" % i, "background"),
                        parent=self)
        if coul:
            self.style.configure("t%i.TButton" % i, background=coul)

    def valide(self):
        """Update config and return whether the pomodor timer should be stopped."""
        old_tpsw = CONFIG.getint("Pomodoro", "work_time")
        old_tpsp = CONFIG.getint("Pomodoro", "break_time")
        old_tpsr = CONFIG.getint("Pomodoro", "rest_time")
        try:
            tpsw = int(self.travail.get())
        except ValueError:  # empty entry
            tpsw = 0
        if tpsw == 0:
            tpsw = old_tpsw
        try:
            tpsp = int(self.pause.get())
        except ValueError:
            tpsp = 0
        if tpsp == 0:
            tpsp = old_tpsp
        try:
            tpsr = int(self.rest.get())
        except ValueError:
            tpsr = 0
        if tpsr == 0:
            tpsr = old_tpsr

        sound, mute = self.sound.get()
        font_prop = self.font.get_font()
        font = "{} {}".format(font_prop['family'].replace(' ', '\ '),
                              font_prop['size'])
        try:
            legend_rows = int(self.legend_row_nb.get())
        except ValueError:
            legend_rows = 0
        if legend_rows == 0:
            legend_rows = CONFIG.getint("Pomodoro", "legend_max_height")

        if not os.path.exists(sound):
            showerror(
                _("Error"),
                _("The file {filepath} does not exists, the old file will be used."
                  ).format(filepath=sound))
            sound = CONFIG.get("Pomodoro", "beep")

        CONFIG.set("Pomodoro", "alpha", str(self.opacity.get_opacity()))
        CONFIG.set("Pomodoro", "font", font)
        CONFIG.set("Pomodoro", "background", self.bg.get_color())
        CONFIG.set("Pomodoro", "foreground", self.fg.get_color())
        CONFIG.set("Pomodoro", "work_time", str(tpsw))
        CONFIG.set("Pomodoro", "work_bg", self.work_bg.get_color())
        CONFIG.set("Pomodoro", "work_fg", self.work_fg.get_color())
        CONFIG.set("Pomodoro", "break_time", str(tpsp))
        CONFIG.set("Pomodoro", "break_bg", self.break_bg.get_color())
        CONFIG.set("Pomodoro", "break_fg", self.break_fg.get_color())
        CONFIG.set("Pomodoro", "rest_time", str(tpsr))
        CONFIG.set("Pomodoro", "rest_bg", self.rest_bg.get_color())
        CONFIG.set("Pomodoro", "rest_fg", self.rest_fg.get_color())
        CONFIG.set("Pomodoro", "beep", sound)
        CONFIG.set("Pomodoro", "mute", str(mute))
        CONFIG.set("Pomodoro", "legend_max_height", str(legend_rows))
        for task, widget in self.tasks.items():
            CONFIG.set("PomodoroTasks", task, widget.get_color())

        return old_tpsw != tpsw or old_tpsp != tpsp or old_tpsr != old_tpsr

    def del_task(self, task):
        """ Suppression de tâches """
        rep = askyesno(
            _("Confirmation"),
            _("Are you sure you want to delete the task {task}? This action cannot be undone."
              ).format(task=task.capitalize()))
        if rep:
            CONFIG.remove_option("PomodoroTasks", task)
            # remove stats
            db = sqlite3.connect(PATH_STATS)
            cursor = db.cursor()
            try:
                cursor.execute('DROP TABLE {}'.format(
                    scrub(task.lower().replace(' ', '_'))))
                db.commit()
            except sqlite3.OperationalError:
                pass  # no stats yet
            db.close()
            self.tasks[task].destroy()
            self._tasks_btns[task].destroy()
            del self.tasks[task]
            del self._tasks_btns[task]

            if len(CONFIG.options("PomodoroTasks")) == 1:
                CONFIG.set("PomodoroTasks", _("Work"), CMAP[0])
                self._tasks_btns[CONFIG.options("PomodoroTasks")[0]].state(
                    ['disabled'])
            save_config()

    def add_task(self):
        def ajoute(event=None):
            task = nom.get().lower().strip()
            if task in self.tasks:
                showerror(
                    _("Error"),
                    _("The task {task} already exists.").format(task=task),
                    parent=self)

            elif task:
                coul = CMAP[(len(self.tasks) + 1) % len(CMAP)]
                i = self.task_frame.grid_size()[1] + 1
                self.tasks[task] = ColorFrame(self.task_frame, coul,
                                              task.capitalize())
                self.tasks[task].grid(row=i,
                                      column=0,
                                      sticky='e',
                                      padx=4,
                                      pady=4)
                b = Button(self.task_frame,
                           image=self.im_moins,
                           padding=2,
                           command=lambda t=task: self.del_task(t))
                b.grid(row=i, column=1, sticky='w', padx=4, pady=4)
                self._tasks_btns[task] = b
                self._tasks_btns[CONFIG.options("PomodoroTasks")[0]].state(
                    ['!disabled'])
            top.destroy()

        top = Toplevel(self)
        top.title(_("New task"))
        top.transient(self)
        top.grab_set()
        nom = Entry(top, width=20, justify='center')
        nom.grid(row=0, columnspan=2, sticky="ew")
        nom.focus_set()
        nom.bind('<Key-Return>', ajoute)
        Button(top, text=_("Cancel"), command=top.destroy).grid(row=1,
                                                                column=0)
        Button(top, text=_("Ok"), command=ajoute).grid(row=1, column=1)
        top.wait_window(top)
Ejemplo n.º 38
0
class GUI:

    # Constructor
    def __init__(self,
                 title='PyCX Simulator',
                 interval=0,
                 stepSize=1,
                 parameterSetters=[]):

        ## all GUI variables moved to inside constructor by Hiroki Sayama 10/09/2018

        self.titleText = title
        self.timeInterval = interval
        self.stepSize = stepSize
        self.parameterSetters = parameterSetters
        self.varEntries = {}
        self.statusStr = ""

        self.running = False
        self.modelFigure = None
        self.currentStep = 0

        # initGUI() removed by Hiroki Sayama 10/09/2018

        #create root window
        self.rootWindow = Tk()
        self.statusText = StringVar(
            self.rootWindow,
            value=self.statusStr)  # at this point, statusStr = ""
        # added "self.rootWindow" above by Hiroki Sayama 10/09/2018
        self.setStatusStr("Simulation not yet started")

        self.rootWindow.wm_title(
            self.titleText)  # titleText = 'PyCX Simulator'
        self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI)
        self.rootWindow.geometry('450x300')
        self.rootWindow.columnconfigure(0, weight=1)
        self.rootWindow.rowconfigure(0, weight=1)

        self.notebook = Notebook(self.rootWindow)
        # self.notebook.grid(row=0,column=0,padx=2,pady=2,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:30:25
        self.notebook.pack(side=TOP, padx=2, pady=2)

        # added "self.rootWindow" by Hiroki Sayama 10/09/2018
        self.frameRun = Frame(self.rootWindow)
        self.frameSettings = Frame(self.rootWindow)
        self.frameParameters = Frame(self.rootWindow)
        self.frameInformation = Frame(self.rootWindow)

        self.notebook.add(self.frameRun, text="Run")
        self.notebook.add(self.frameSettings, text="Settings")
        self.notebook.add(self.frameParameters, text="Parameters")
        self.notebook.add(self.frameInformation, text="Info")
        self.notebook.pack(expand=NO, fill=BOTH, padx=5, pady=5, side=TOP)
        # self.notebook.grid(row=0, column=0, padx=5, pady=5, sticky='nswe')   # commented out by toshi on 2016-06-21(Tue) 18:31:02

        self.status = Label(self.rootWindow,
                            width=40,
                            height=3,
                            relief=SUNKEN,
                            bd=1,
                            textvariable=self.statusText)
        # self.status.grid(row=1,column=0,padx=5,pady=5,sticky='nswe') # commented out by toshi on 2016-06-21(Tue) 18:31:17
        self.status.pack(side=TOP, fill=X, padx=5, pady=5, expand=NO)

        # -----------------------------------
        # frameRun
        # -----------------------------------
        # buttonRun
        self.runPauseString = StringVar(
            self.rootWindow
        )  # added "self.rootWindow" by Hiroki Sayama 10/09/2018
        self.runPauseString.set("Run")
        self.buttonRun = Button(self.frameRun,
                                width=30,
                                height=2,
                                textvariable=self.runPauseString,
                                command=self.runEvent)
        self.buttonRun.pack(side=TOP, padx=5, pady=5)
        self.showHelp(
            self.buttonRun,
            "Runs the simulation (or pauses the running simulation)")

        # buttonStep
        self.buttonStep = Button(self.frameRun,
                                 width=30,
                                 height=2,
                                 text='Step Once',
                                 command=self.stepOnce)
        self.buttonStep.pack(side=TOP, padx=5, pady=5)
        self.showHelp(self.buttonStep, "Steps the simulation only once")

        # buttonReset
        self.buttonReset = Button(self.frameRun,
                                  width=30,
                                  height=2,
                                  text='Reset',
                                  command=self.resetModel)
        self.buttonReset.pack(side=TOP, padx=5, pady=5)
        self.showHelp(self.buttonReset, "Resets the simulation")

        # -----------------------------------
        # frameSettings
        # -----------------------------------
        can = Canvas(self.frameSettings)

        lab = Label(can,
                    width=25,
                    height=1,
                    text="Step size ",
                    justify=LEFT,
                    anchor=W,
                    takefocus=0)
        lab.pack(side='left')

        self.stepScale = Scale(can,
                               from_=1,
                               to=50,
                               resolution=1,
                               command=self.changeStepSize,
                               orient=HORIZONTAL,
                               width=25,
                               length=150)
        self.stepScale.set(self.stepSize)
        self.showHelp(
            self.stepScale,
            "Skips model redraw during every [n] simulation steps\nResults in a faster model run."
        )
        self.stepScale.pack(side='left')

        can.pack(side='top')

        can = Canvas(self.frameSettings)
        lab = Label(can,
                    width=25,
                    height=1,
                    text="Step visualization delay in ms ",
                    justify=LEFT,
                    anchor=W,
                    takefocus=0)
        lab.pack(side='left')
        self.stepDelay = Scale(can,
                               from_=0,
                               to=max(2000, self.timeInterval),
                               resolution=10,
                               command=self.changeStepDelay,
                               orient=HORIZONTAL,
                               width=25,
                               length=150)
        self.stepDelay.set(self.timeInterval)
        self.showHelp(
            self.stepDelay,
            "The visualization of each step is delays by the given number of milliseconds."
        )
        self.stepDelay.pack(side='left')

        can.pack(side='top')

        # --------------------------------------------
        # frameInformation
        # --------------------------------------------
        scrollInfo = Scrollbar(self.frameInformation)
        self.textInformation = Text(self.frameInformation,
                                    width=45,
                                    height=13,
                                    bg='lightgray',
                                    wrap=WORD,
                                    font=("Courier", 10))
        scrollInfo.pack(side=RIGHT, fill=Y)
        self.textInformation.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollInfo.config(command=self.textInformation.yview)
        self.textInformation.config(yscrollcommand=scrollInfo.set)

        # --------------------------------------------
        # ParameterSetters
        # --------------------------------------------
        for variableSetter in self.parameterSetters:
            can = Canvas(self.frameParameters)

            lab = Label(can,
                        width=25,
                        height=1,
                        text=variableSetter.__name__ + " ",
                        anchor=W,
                        takefocus=0)
            lab.pack(side='left')

            ent = Entry(can, width=11)
            ent.insert(0, str(variableSetter()))

            if variableSetter.__doc__ != None and len(
                    variableSetter.__doc__) > 0:
                self.showHelp(ent, variableSetter.__doc__.strip())

            ent.pack(side='left')

            can.pack(side='top')

            self.varEntries[variableSetter] = ent

        if len(self.parameterSetters) > 0:
            self.buttonSaveParameters = Button(
                self.frameParameters,
                width=50,
                height=1,
                command=self.saveParametersCmd,
                text="Save parameters to the running model",
                state=DISABLED)
            self.showHelp(
                self.buttonSaveParameters,
                "Saves the parameter values.\nNot all values may take effect on a running model\nA model reset might be required."
            )
            self.buttonSaveParameters.pack(side='top', padx=5, pady=5)
            self.buttonSaveParametersAndReset = Button(
                self.frameParameters,
                width=50,
                height=1,
                command=self.saveParametersAndResetCmd,
                text="Save parameters to the model and reset the model")
            self.showHelp(
                self.buttonSaveParametersAndReset,
                "Saves the given parameter values and resets the model")
            self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5)

    # <<<<< Init >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    def setStatusStr(self, newStatus):
        self.statusStr = newStatus
        self.statusText.set(self.statusStr)

    # model control functions for changing parameters
    def changeStepSize(self, val):
        self.stepSize = int(val)

    def changeStepDelay(self, val):
        self.timeInterval = int(val)

    def saveParametersCmd(self):
        for variableSetter in self.parameterSetters:
            variableSetter(float(self.varEntries[variableSetter].get()))
            self.setStatusStr("New parameter values have been set")

    def saveParametersAndResetCmd(self):
        self.saveParametersCmd()
        self.resetModel()

    # <<<< runEvent >>>>>
    # This event is envoked when "Run" button is clicked.
    def runEvent(self):
        self.running = not self.running
        if self.running:
            self.rootWindow.after(self.timeInterval, self.stepModel)
            self.runPauseString.set("Pause")
            self.buttonStep.configure(state=DISABLED)
            self.buttonReset.configure(state=DISABLED)
            if len(self.parameterSetters) > 0:
                self.buttonSaveParameters.configure(state=NORMAL)
                self.buttonSaveParametersAndReset.configure(state=DISABLED)
        else:
            self.runPauseString.set("Continue Run")
            self.buttonStep.configure(state=NORMAL)
            self.buttonReset.configure(state=NORMAL)
            if len(self.parameterSetters) > 0:
                self.buttonSaveParameters.configure(state=NORMAL)
                self.buttonSaveParametersAndReset.configure(state=NORMAL)

    def stepModel(self):
        if self.running:
            self.modelStepFunc()
            self.currentStep += 1
            self.setStatusStr("Step " + str(self.currentStep))
            self.status.configure(foreground='black')
            if (self.currentStep) % self.stepSize == 0:
                self.drawModel()
            self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize),
                                  self.stepModel)

    def stepOnce(self):
        self.running = False
        self.runPauseString.set("Continue Run")
        self.modelStepFunc()
        self.currentStep += 1
        self.setStatusStr("Step " + str(self.currentStep))
        self.drawModel()
        if len(self.parameterSetters) > 0:
            self.buttonSaveParameters.configure(state=NORMAL)

    def resetModel(self):
        self.running = False
        self.runPauseString.set("Run")
        self.modelInitFunc()
        self.currentStep = 0
        self.setStatusStr("Model has been reset")
        self.drawModel()

    def drawModel(self):
        plt.ion()  #SM 3/26/2020
        if self.modelFigure == None or self.modelFigure.canvas.manager.window == None:
            self.modelFigure = plt.figure()  #SM 3/26/2020
        self.modelDrawFunc()
        self.modelFigure.canvas.manager.window.update()
        plt.show()  # bug fix by Hiroki Sayama in 2016 #SM 3/26/2020

    def start(self, func=[]):
        if len(func) == 3:
            self.modelInitFunc = func[0]
            self.modelDrawFunc = func[1]
            self.modelStepFunc = func[2]
            if (self.modelStepFunc.__doc__ != None
                    and len(self.modelStepFunc.__doc__) > 0):
                self.showHelp(self.buttonStep,
                              self.modelStepFunc.__doc__.strip())
            if (self.modelInitFunc.__doc__ != None
                    and len(self.modelInitFunc.__doc__) > 0):
                self.textInformation.config(state=NORMAL)
                self.textInformation.delete(1.0, END)
                self.textInformation.insert(END,
                                            self.modelInitFunc.__doc__.strip())
                self.textInformation.config(state=DISABLED)

            self.modelInitFunc()
            self.drawModel()
        self.rootWindow.mainloop()

    def quitGUI(self):
        self.running = False  # HS 06/29/2020
        self.rootWindow.quit()
        plt.close('all')  # HS 06/29/2020
        self.rootWindow.destroy()

    def showHelp(self, widget, text):
        def setText(self):
            self.statusText.set(text)
            self.status.configure(foreground='blue')

        def showHelpLeave(self):
            self.statusText.set(self.statusStr)
            self.status.configure(foreground='black')

        widget.bind("<Enter>", lambda e: setText(self))
        widget.bind("<Leave>", lambda e: showHelpLeave(self))
Ejemplo n.º 39
0
class TranslateBook(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title("Interface da Cifra v1")
        self.geometry("500x300")

        self.notebook = Notebook(self)

        english_tab = tk.Frame(self.notebook)
        italian_tab = tk.Frame(self.notebook)

        self.translate_button = tk.Button(english_tab,
                                          text="CIFRAR",
                                          command=self.translate)
        self.translate_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.english_entry = tk.Text(english_tab, bg="white", fg="black")
        self.english_entry.pack(side=tk.TOP, expand=1)

        self.italian_copy_button = tk.Button(italian_tab,
                                             text="Copiar resultados",
                                             command=self.copy_to_clipboard)
        self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.italian_translation = tk.StringVar(italian_tab)
        self.italian_translation.set("")

        self.italian_label = tk.Label(italian_tab,
                                      textvar=self.italian_translation,
                                      bg="lightgrey",
                                      fg="black")
        self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.notebook.add(english_tab, text="Texto Claro")
        self.notebook.add(italian_tab, text="Texto Cifrado")

        self.notebook.pack(fill=tk.BOTH, expand=1)

    def translate(self, target_language="it", text=None):
        if not text:
            text = self.english_entry.get(1.0, tk.END)

        url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}".format(
            "en", target_language, text)

        try:
            data = "Hello there!"
            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)

            enc_data = k.encrypt(data)
            print("texto cifrado: ")
            print(enc_data)
            print(type(enc_data))

            dec_data = k.decrypt(enc_data)
            key = k.getKey()
            print("\n")
            print("Texto claro: ")
            print(dec_data)

            print("\n")
            print("Chave usada: ")
            print(key)

            message = encrypt_message(str(key), 14257, 11)
            decript = decrypt_message(message)

            print("\n")
            print("Chave cifrada com RSA: ")
            print(message)

            print("\n")
            print("Chave decifrada com RSA: ")
            print(decript)

            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)
            enc_data = k.encrypt(text)
            dec_data = k.decrypt(enc_data)
            hashe = md5(text)
            key = k.getKey()
            print(key)
            message = encrypt_message(str(key), 14257, 11)
            mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" +
                  str(hashe))
            self.italian_translation.set(mk)
            msg.showinfo("Cifrado", "Texto cifrado com sucesso")
        except Exception as e:
            msg.showerror("A cifra falhou", str(e))

    def copy_to_clipboard(self, text=None):
        if not text:
            text = self.italian_translation.get()

        self.clipboard_clear()
        self.clipboard_append(text)
        msg.showinfo("Copied Successfully", "Text copied to clipboard")
Ejemplo n.º 40
0
class App:
    # need it for generate reports
    __ast = None
    __sym_table = None
    __sym_table_3d = None

    def __init__(self, ide):

        # setting title
        ide.title("TenorC @danii_mor")

        # setting window size
        width=700
        height=400
        screenwidth = ide.winfo_screenwidth()
        screenheight = ide.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        ide.geometry(alignstr)
        ide.resizable(width=True, height=True)

        # create menubar
        menubar = Menu(ide)

        # file menu
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="New", command=self.newFile)
        filemenu.add_command(label="Open", command=self.file_open)
        filemenu.add_command(label="Save", command=self.file_save)
        filemenu.add_command(label="Save as...", command=self.file_save_as)
        filemenu.add_command(label="Close", command=self.exitTab)

        filemenu.add_separator()

        filemenu.add_command(label="Exit", command=ide.quit)
        

        # edit menu
        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Cut", command=self.donothing)
        editmenu.add_command(label="Copy", command=self.copy_to_clipboard)
        editmenu.add_command(label="Paste", command=self.donothing)

        editmenu.add_separator()

        editmenu.add_command(label="Find", command=self.donothing)
        editmenu.add_command(label="Replace", command=self.donothing)


        # run menu
        runmenu = Menu(menubar, tearoff=0)
        runmenu.add_command(label="Execute Analysis", command=self.execute_current_tab_lef)
        runmenu.add_command(label="Show Intermediate Code", command=self.show3D)

        runmenu.add_separator()

        runmenu.add_command(label="Symbol Table", command=self.show_sym_table)
        runmenu.add_command(label="Error Report", command=self.show_error)
        runmenu.add_command(label="Abstract Syntax Tree", command=self.show_ast)
        runmenu.add_command(label="Grammar", command=self.show_grammar)

        runmenu.add_separator()
        
        runmenu.add_command(label="Debugging", command=self.execute_debug)


        # option menu
        #optionmenu = Menu(menubar, tearoff=0)
        #optionmenu.add_command(label="Theme...", command=self.donothing)
        #optionmenu.add_command(label="Line Numbers...", command=self.donothing)


        # help menu
        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Help", command=self.donothing)
        helpmenu.add_command(label="About...", command=self.show_info)
        

        # setting menu
        menubar.add_cascade(label="File", menu=filemenu)
        menubar.add_cascade(label="Edit", menu=editmenu)
        menubar.add_cascade(label="Run", menu=runmenu)
        menubar.add_cascade(label="Help", menu=helpmenu)
        ide.config(menu=menubar)

        # setting editor area
        self.tabs = Notebook(ide)
        f1 = Frame(self.tabs)
        self.tabs.add(f1, text="+")
        self.tabs.pack(side="top", fill="both", expand=True, padx=10, pady=0)

        self.tabs.bind("<<NotebookTabChanged>>", self.addTab)


        # setting terminal area
        self.terminal= Text(ide)
        ft = tkFont.Font(family="Lucinda Console", size=10)
        self.terminal["font"] = ft
        self.terminal["wrap"] = "word"
        self.terminal["fg"] = "white"
        self.terminal["bg"] = "black"
        self.terminal["insertbackground"] ="white"
        self.terminal["height"] = 5
        self.terminal["width"] = 5
        self.terminal.pack( side = "left", fill = "both", expand=True,  padx=10, pady=10)

        terminal_scroll = Scrollbar(ide)
        terminal_scroll["orient"] = "vertical"
        terminal_scroll["command"] = self.terminal.yview
        terminal_scroll.pack(side="right", fill="y")

        self.terminal.configure(yscrollcommand=terminal_scroll.set)
        self.terminal.bind("<Return>", self.execute_command)

    def copy_to_clipboard(self):
        selectedTab = self.tabs.index("current")
        currentTextArea = self.tabs.winfo_children()[selectedTab+1].textarea
        try:
            selected_text= currentTextArea.get("sel.first", "sel.last")
            currentTextArea.clipboard_append(selected_text)
        except:
            pass

    def show_grammar(self):
        if self.__sym_table:
            window = Toplevel()
            window['bg'] = 'black'
            productions = self.__sym_table.getGrammar()
            keys = list(productions.keys())
            keys.sort()
            grammar = Message(window)
            txt = ''
            for production in keys:
                txt += productions[production] + '\n' 
            grammar['fg'] = 'white'
            grammar['bg'] = 'black'
            grammar['text'] = txt
            grammar.pack(side='left')
    
    def show_error(self):
        if self.__sym_table:
            if self.__sym_table.error != '':
                window = Toplevel()
                window['bg'] = 'black'

                grammar = Message(window)
                grammar['fg'] = 'white'
                grammar['bg'] = 'black'
                grammar['text'] = self.__sym_table.error
                grammar.pack(side='left')
            else:
                window = Toplevel()
                window['bg'] = 'black'

                grammar = Message(window)
                grammar['fg'] = 'white'
                grammar['bg'] = 'black'
                grammar['text'] = 'Not Errors Found'
                grammar.pack(side='left')

    # TODO fix it
    def show_sym_table(self):
        if self.__sym_table:
            showTable(self.__sym_table)

    def show_ast(self):
        self.__ast.graph()
        showAST()

    codeGenerated = None
    def show3D(self):
        if self.codeGenerated != None:
            window = Toplevel()
            window['bg'] = 'black'

            grammar = Text(window)
            grammar['fg'] = 'white'
            grammar['bg'] = 'black'
            grammar.insert(1.0, self.codeGenerated)
            grammar.pack(side='left')

    def show_info(self):
        window = Toplevel()
        window['bg'] = 'black'

        grammar = Message(window)
        grammar['fg'] = 'white'
        grammar['bg'] = 'black'
        grammar['text'] = 'Augus intermediate code by Engr. Espino\nTenorC 1.23.2a Developed by @danii_mor\n 201314810'
        grammar.pack(side='left')

    def update_line_debugg(self, event= None):
        self.count["text"] = "Line: %s" % str(self.c+1)

        lines = self.codeGenerated.split('\n')

        # start execute line by self.c counter
        ply_left_3d = titus.parse()
        if self.c < len(lines):
            if "main:" not in lines[self.c]:
                line = "main:" + lines[self.c]
                result  = ply_left_3d(titus, line)
                if result:
                    ast = result[0]
                    ast.setType("LABEL")
                    ast.setValue("S")
                    ast.root = result[0]

                    if self.__sym_table_3d != None:
                        new_table =  {**self.__sym_table_3d.printTable(), **result[1].printTable()}
                        for sym_id in new_table:
                            sym = new_table[sym_id]
                            if sym != None:
                                if type(sym) == dict:
                                    continue
                                if sym.getValue() == None:
                                    try:
                                        new_table[sym_id] = self.__sym_table_3d.printTable()[sym_id]
                                    except:
                                        pass
                        self.__sym_table_3d.setTable({**self.__sym_table_3d.printTable(), **new_table})
                    else:
                        self.__sym_table_3d = result[1]
                        # define mode for syntax-tree know how to autoexecute
                        self.__sym_table_3d.setMode(1)

                    compute = [None, None]

                    # start execute
                    self.__sym_table_3d.terminal = self.terminal
                    compute = ast.start_execute(self.__sym_table_3d, "MAIN")
                    # lookup the last line
                    index = self.terminal.search(r'\n', "insert", backwards=True, regexp=True)
                    txt = self.terminal.get(str(index),'end-1c')
                    if txt == "":
                        index ="1.0"
                    else:
                        index = self.terminal.index("%s+1c" % index)
                    if compute[0]:
                        self.terminal.insert(str(float(index)+1), compute[0])
                        self.__sym_table_3d.cleanLog()
                    if compute[1]:
                        goto_line = 0
                        for l in lines:
                            if (compute[1]+":") in l:
                                break
                            goto_line = goto_line + 1
                        
                        self.c = goto_line - 1

            if self.__sym_table != None:
                if self.__sym_table.error != '':
                    # lookup the last line
                    index = self.terminal.search(r'\n', "insert", backwards=True, regexp=True)
                    txt = self.terminal.get(str(index),'end-1c')
                    if txt == "":
                        index ="1.0"
                    else:
                        index = self.terminal.index("%s+1c" % index)
                    self.terminal.insert(str(float(index)+1), "\nTenorC>> Error Report Generated\n")

            self.c = self.c + 1
            self.label_last_line["text"] = "Line: %s" % str(self.c+1)

    c = 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()

    def execute_current_tab_lef(self):
        # 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()

            ## start executing

            ply_left_3d = titus.parse()
            result  = ply_left_3d(titus, self.codeGenerated)

            if result:
                ast_3D = result[0]
                ast_3D.setType("LABEL")
                ast_3D.setValue("S")
                ast_3D.root = True

                self.__sym_table_3d = result[1]

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

                goto_called = True
                start_from = "MAIN"
                compute = [None, None]
                while goto_called:
                    goto_called = False
                    self.__sym_table_3d.terminal = self.terminal
                    compute = ast_3D.start_execute(self.__sym_table_3d, start_from)
                    # lookup the last line
                    index = self.terminal.search(r'\n', "insert", backwards=True, regexp=True)
                    txt = self.terminal.get(str(index),'end-1c')
                    if txt == "":
                        index ="1.0"
                    else:
                        index = self.terminal.index("%s+1c" % index)
                    if compute[0]:
                        self.terminal.insert(str(float(index)+1), compute[0])
                        self.__sym_table_3d.cleanLog()
                    if compute[1]:
                        goto_called = True
                        start_from = compute[1]

        elif self.__sym_table.error != '':
            # lookup the last line
            index = self.terminal.search(r'\n', "insert", backwards=True, regexp=True)
            txt = self.terminal.get(str(index),'end-1c')
            if txt == "":
                index ="1.0"
            else:
                index = self.terminal.index("%s+1c" % index)
            self.terminal.insert(str(float(index)+1), "\nTenorC>> Error Report Generated\n")
    
    def execute_command(self, event):
        # lookup the last line
        index = self.terminal.search(r'\n', "insert", backwards=True, regexp=True)
        input = self.terminal.get(str(index),'end-1c')
        if input == "":
            index ="1.0"
        else:
            index = self.terminal.index("%s+1c" % index)
        input = self.terminal.get(index,'end-1c')
        # send the input to the calculate 
        self.__sym_table_3d.read_input.set(input)

    def newFile(self):
        lastindex = self.tabs.index("end")-1

        textarea = Editor(self.tabs)
        self.tabs.insert(lastindex, textarea, text="Tab" + str(lastindex+1))
        self.tabs.select(lastindex)

    def exitTab(self):
        result = self.save_if_modified()
        if result != None: #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified
            selectedTab = self.tabs.index("current")
            currentTab = self.tabs.winfo_children()[selectedTab+1]
            
            self.tabs.select(self.tabs.winfo_children()[selectedTab])
            currentTab.destroy()

    def save_if_modified(self, event=None):
        selectedTab = self.tabs.index("current")
        currentTextArea = self.tabs.winfo_children()[selectedTab+1].textarea
        if currentTextArea.edit_modified(): #modified
            response = messagebox.askyesnocancel("Save?", "This document has been modified. Do you want to save changes?") #yes = True, no = False, cancel = None
            if response: #yes/save
                result = self.file_save()
                if result == "saved": #saved
                    return True
                else: #save cancelled
                    return None
            else:
                return response #None = cancel/abort, False = no/discard
        else: #not modified
            return True

    def file_open(self, event=None, filepath=None):
        if filepath == None:
            filepath = filedialog.askopenfilename()
        if filepath != None  and filepath != '':
            with open(filepath, encoding="utf-8") as f:
                fileContents = f.read()# Get all the text from file.           
            # Set current text to a new Tab file contents
            lastindex = self.tabs.index("end")-1

            textarea = Editor(self.tabs)
            self.tabs.insert(lastindex, textarea, text="Tab" + str(lastindex+1))
            self.tabs.select(lastindex)

            textarea.textarea.insert(1.0, fileContents)
            textarea.textarea.edit_modified(False)
            tab_tittle = os.path.basename(filepath)
            self.tabs.tab(lastindex, text = tab_tittle)

    def file_save(self, event=None):
        selectedTab = self.tabs.index("current")
        currentName = self.tabs.tab(selectedTab, "text")
        if 'Tab' in currentName:
            result = self.file_save_as()
        else:
            result = self.file_save_as(filepath='./' + currentName)
        return result

    def file_save_as(self, event=None, filepath=None):
        if filepath == None:
            filepath = filedialog.asksaveasfilename(filetypes=(('Text files', '*.txt'), ('C files', '*.mc'), ('All files', '*.*'))) #defaultextension='.txt'
        try:
            with open(filepath, 'wb') as f:
                selectedTab = self.tabs.index("current")
                currentTextArea = self.tabs.winfo_children()[selectedTab+1].textarea
                text = currentTextArea.get(1.0, "end-1c")
                f.write(bytes(text, 'UTF-8'))
                currentTextArea.edit_modified(False)
                tab_tittle = os.path.basename(filepath)
                self.tabs.tab(selectedTab, text = tab_tittle)
                return "saved"
        except FileNotFoundError:
            print('TenorC>> File Not Found Error')
            return "cancelled"

    def addTab(self, event):
        selectedTab = self.tabs.index("current")
        lastindex = self.tabs.index("end")-1

        if selectedTab == lastindex :
            textarea = Editor(self.tabs)
            self.tabs.insert(lastindex, textarea, text="Tab" + str(lastindex+1))
            self.tabs.select(lastindex)

    def donothing(self):
        print("clicked")
class TranslateBook(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title("Cifra Completa v2")
        self.geometry("500x300")

        #self.menu = tk.Menu(self, bg="lightgrey", fg="black")

        #self.languages_menu = tk.Menu(self.menu, tearoff=0, bg="lightgrey", fg="black")
        #self.languages_menu.add_command(label="Decifrar", command=self.add_portuguese_tab)

        #self.menu.add_cascade(label="MENU", menu=self.languages_menu)

        #self.config(menu=self.menu)

        self.notebook = Notebook(self)

        english_tab = tk.Frame(self.notebook)
        italian_tab = tk.Frame(self.notebook)
        portuguese_tab = tk.Frame(self.notebook)

        self.italian_translation = tk.StringVar(italian_tab)
        self.italian_translation.set("")

        self.portuguese_translation = tk.StringVar(portuguese_tab)
        self.portuguese_translation.set("")

        self.translate_button = tk.Button(
            english_tab,
            text="CIFRAR",
            command=lambda langs=["it"], elems=[
                self.italian_translation, self.portuguese_translation
            ]: self.translate(langs, None, elems))
        self.translate_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.english_entry = tk.Text(english_tab, bg="white", fg="black")
        self.english_entry.pack(side=tk.TOP, expand=1)

        self.italian_copy_button = tk.Button(italian_tab,
                                             text="Copiar resultados",
                                             command=self.copy_to_clipboard)
        self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.portuguese_copy_button = tk.Button(portuguese_tab,
                                                text="Copiar resultados",
                                                command=self.copy_to_clipboard)
        self.portuguese_copy_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.italian_label = tk.Label(italian_tab,
                                      textvar=self.italian_translation,
                                      bg="lightgrey",
                                      fg="black")
        self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.portuguese_label = tk.Label(portuguese_tab,
                                         textvar=self.portuguese_translation,
                                         bg="lightgrey",
                                         fg="black")
        self.portuguese_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.notebook.add(english_tab, text="Texto Claro")
        self.notebook.add(italian_tab, text="Texto Cifrado")
        self.notebook.add(portuguese_tab, text="Texto Descifrado")

        #self.languages_menu.entryconfig("Texto Descifrado", state="disabled")

        #self.translate_button.config(command=lambda langs=["it","pt"],elems=[self.italian_translation, self.portuguese_translation]:
        #                                               self.translate(langs, None, elems))

        self.notebook.pack(fill=tk.BOTH, expand=1)

    def translate(self, target_languages=None, text=None, elements=None):
        if not text:
            text = self.english_entry.get(1.0, tk.END).strip()
        if not elements:
            elements = [self.italian_translation]
        if not target_languages:
            target_languages = ["it"]

        url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}"

        try:
            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)
            enc_data = k.encrypt(text)
            hashe = md5(text)
            key = k.getKey()
            print(key)
            message = encrypt_message(str(key), 14257, 11)
            mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" +
                  str(hashe))
            self.italian_translation.set(mk)
            msg.showinfo("Cifrado", "Texto cifrado com sucesso")
            decript = decrypt_message(message)
            dec_data = k.decrypt(enc_data)
            to_print = (str(dec_data) + "\n\n\n" + str(decript) + "\n\n\n" +
                        str(hashe))
            self.portuguese_translation.set(to_print)

        except Exception as e:
            msg.showerror("A cifra falhou", str(e))

    def copy_to_clipboard(self, text=None):
        if not text:
            text = self.italian_translation.get()

        self.clipboard_clear()
        self.clipboard_append(text)
        msg.showinfo("Copied Successfully", "Text copied to clipboard")