예제 #1
0
class Menu(Tk):
    def __init__(self):
        global FMagasin
        Tk.__init__(self)
        self.title('Donjon & Python')
        self.magasin = Magasin.Magasin(self)
        self.magasin.grid(row=0, column=0)
        Button(self, text='Jouer', command=self.play, height=2, width=20).grid(row=1, column=1)
        Button(self,text='Options', command=__main__.ouvrirOption, height=2, width=9).grid(row=1, column=2)
        self.framePerso = LabelFrame(self, text='Selection du personnage', width=30)
        self.framePerso.grid(row=0, column=1, columnspan=2)
        self.OR = Label(self, background='Yellow', height=2, width=70)
        self.OR.grid(row=1, column=0)
        self.majOR()
        self.remplirFramePerso()
    def run(self):
        Audio.playMusic('Rogue Legacy - Castle', -1)
        self.majPerso()
        self.mainloop()
        Sauvegarde.sauvegarder(__main__.savePath)
    def majPerso(self):
        for i in range(3):
            self.listeBox[i].maj()
    def majOR(self):
        self.OR.config(text="Pièce d'or : " + str(Magasin.OR))
    def remplirFramePerso(self):
        listePerso = GenerationPersonnage.genererPerso()
        self.listeBox = []
        for i in range(len(listePerso)):
            self.listeBox.append(BoxPerso(self.framePerso, listePerso[i], i))
            self.listeBox[i].pack()
    def play(self):
        if __main__.perso:
            Sauvegarde.sauvegarder(__main__.savePath)
            self.destroy()
            __main__.motGraph = MoteurGraphique()
            # try:    #Les thread entrainent parfois des problèmes d'inconsistance dans pygame
            __main__.motGraph.run()
            __main__.motGraph = None
예제 #2
0
class NetmaskCalcGUI:
    def __init__(self):
        self.subnet = Subnet()

        self.net = Tk()
        self.net.wm_title('Netmask Calculator')

        self.netmask_from_cidr = LabelFrame(self.net,
                                            text='Netmask: CIDR Address')
        self.cidr_label = Label(self.netmask_from_cidr,
                                text='CIDR Address:',
                                width=20)
        self.cidr_entry = Entry(self.netmask_from_cidr, width=25)

        self.netmask_from_ip_range = LabelFrame(
            self.net, text='Netmask: Assignable IP Range')
        self.ip_range_label = Label(self.netmask_from_ip_range,
                                    text='Assignable IP Range:',
                                    width=20)
        self.ip_range_entry = Entry(self.netmask_from_ip_range, width=25)

        self.learning_steps = LabelFrame(self.net, text='Learning Steps')

        self.calculate = Button(self.netmask_from_cidr,
                                text='Calculate',
                                command=lambda: self.get_net_from_cidr())
        self.calculate2 = Button(self.netmask_from_ip_range,
                                 text='Calculate',
                                 command=lambda: self.get_net_from_ip_range())

        self.netmask_from_cidr.grid(row=0)
        self.netmask_from_ip_range.grid(row=1)
        self.learning_steps.grid(row=2, sticky='W')

        self.cidr_label.grid(row=0, column=0, sticky='W')
        self.cidr_entry.grid(row=0, column=1)
        self.calculate.grid(row=0, column=2)

        self.ip_range_label.grid(row=0, column=0, sticky='W')
        self.ip_range_entry.grid(row=0, column=1)
        self.calculate2.grid(row=0, column=2)

        # self.net.mainloop()

    def get_net_from_cidr(self):
        if self.subnet.netmask != '':
            self.clear_and_reset()
        else:
            self.subnet.cidr_address = self.cidr_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_netmask_from_cidr()
                steps = self.subnet.netmask_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                cidr_address = Label(self.learning_steps,
                                     text='CIDR Address: {}'.format(
                                         self.subnet.cidr_address))
                step2 = Label(self.learning_steps, text='Step 2:')
                net_bits = Label(self.learning_steps,
                                 text='Network Bits: {}'.format(
                                     steps[0]['Network Bits']))
                host_bits = Label(self.learning_steps,
                                  text='Host Bits: {}'.format(
                                      steps[0]['Host Bits']))
                step3 = Label(self.learning_steps, text='Step 3:')
                mask_binary = Label(self.learning_steps,
                                    text='Netmask Binary: {}'.format(
                                        steps[1]['Netmask Binary']))
                step4 = Label(self.learning_steps, text='Step 4:')
                netmask = Label(self.learning_steps,
                                text='Netmask: {}'.format(self.subnet.netmask))

                step1.grid(row=0, column=0, sticky='W')
                cidr_address.grid(row=0, column=1, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                net_bits.grid(row=1, column=1, sticky='W')
                host_bits.grid(row=1, column=2, sticky='W')
                step3.grid(row=2, column=0, sticky='W')
                mask_binary.grid(row=2, column=1, columnspan=2, sticky='W')
                step4.grid(row=3, column=0, sticky='W')
                netmask.grid(row=3, column=1, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def get_net_from_ip_range(self):
        if self.subnet.netmask != '':
            self.clear_and_reset()
        else:
            self.subnet.ip_range = self.ip_range_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_netmask_from_ip_range()
                steps = self.subnet.netmask_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                ip_range = Label(self.learning_steps,
                                 text='Assignable IP Range: {}'.format(
                                     self.subnet.ip_range))
                step2 = Label(self.learning_steps, text='Step 2:')
                front = Label(self.learning_steps,
                              text='Front: {}'.format(steps[0]['Front']))
                back = Label(self.learning_steps,
                             text=' Back: {}'.format(steps[0]['Back']))
                step3 = Label(self.learning_steps, text='Step 3:')
                comparison = Label(self.learning_steps,
                                   text='Comparison: {}'.format(
                                       steps[1]['Comparison']))
                step4 = Label(self.learning_steps, text='Step 4:')
                netmask = Label(self.learning_steps,
                                text='Netmask: {}'.format(self.subnet.netmask))

                step1.grid(row=0, column=0, sticky='W')
                ip_range.grid(row=0, column=1, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                front.grid(row=1, column=1, sticky='W')
                back.grid(row=2, column=1, sticky='W')
                step3.grid(row=3, column=0, sticky='W')
                comparison.grid(row=3, column=1, sticky='W')
                step4.grid(row=4, column=0, sticky='W')
                netmask.grid(row=4, column=1, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def clear_and_reset(self):
        self.cidr_entry.delete(0, 'end')
        self.ip_range_entry.delete(0, 'end')
        self.subnet.reset_variables()
        for child in self.learning_steps.winfo_children():
            child.destroy()

    def generate_main(self):
        self.net.mainloop()
예제 #3
0
class MainApp:
    def __init__(self):
        self.root = Tk()
        self.root.title("KCLP Solution - Submitted by Team Vanished Gradient (Deep Raval, Jaymin Suhagiya)")
        self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage(file='../Images/icon.png'))
        #self.root.geometry('360x100')
        self.root.resizable(0,0)
        self.switch_details = []
        
        self.details_lf = LabelFrame(self.root, text = " 1. Enter Rack & Switch Details: ")
        self.details_lf.grid(row = 0, columnspan = 10, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        self.hyperparam_lf = LabelFrame(self.root, text = "2. Hyperparameteres:")
        self.hyperparam_lf.grid(row = 1, column = 0, columnspan = 5, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        self.solve_lf= LabelFrame(self.root, text = "3. Execute and Stats:")
        self.solve_lf.grid(row = 1, column = 5, columnspan = 5, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        Label(self.details_lf, text = "Rack length :").grid(row = 0, column = 0, sticky = 'E', padx = 5, pady = 2)
        self.rack_length = Entry(self.details_lf, width = 15)
        self.rack_length.grid(row = 0, column = 1, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Rack breadth :").grid(row = 0, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.rack_breadth = Entry(self.details_lf, width = 15)
        self.rack_breadth.grid(row = 0, column = 3, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Rack height :").grid(row = 0, column = 4, sticky = 'E', padx = 5, pady = 2)
        self.rack_height = Entry(self.details_lf, width = 15)
        self.rack_height.grid(row = 0, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 1 (l, b, h, value, instances):").grid(row = 1, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s1_l = Entry(self.details_lf, width = 15)
        self.s1_l.grid(row = 1, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s1_b = Entry(self.details_lf, width = 15)
        self.s1_b.grid(row = 1, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s1_h = Entry(self.details_lf, width = 15)
        self.s1_h.grid(row = 1, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s1_v = Entry(self.details_lf, width = 15)
        self.s1_v.grid(row = 1, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s1_i = Entry(self.details_lf, width = 15)
        self.s1_i.grid(row = 1, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 2 (l, b, h, value, instances):").grid(row = 2, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s2_l = Entry(self.details_lf, width = 15)
        self.s2_l.grid(row = 2, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s2_b = Entry(self.details_lf, width = 15)
        self.s2_b.grid(row = 2, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s2_h = Entry(self.details_lf, width = 15)
        self.s2_h.grid(row = 2, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s2_v = Entry(self.details_lf, width = 15)
        self.s2_v.grid(row = 2, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s2_i = Entry(self.details_lf, width = 15)
        self.s2_i.grid(row = 2, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 3 (l, b, h, value, instances):").grid(row = 3, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s3_l = Entry(self.details_lf, width = 15)
        self.s3_l.grid(row = 3, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s3_b = Entry(self.details_lf, width = 15)
        self.s3_b.grid(row = 3, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s3_h = Entry(self.details_lf, width = 15)
        self.s3_h.grid(row = 3, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s3_v = Entry(self.details_lf, width = 15)
        self.s3_v.grid(row = 3, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s3_i = Entry(self.details_lf, width = 15)
        self.s3_i.grid(row = 3, column = 5, sticky = 'E', padx = 5, pady = 2)

        Label(self.details_lf, text = "Switch 4 (l, b, h, value, instances):").grid(row = 4, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s4_l = Entry(self.details_lf, width = 15)
        self.s4_l.grid(row = 4, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s4_b = Entry(self.details_lf, width = 15)
        self.s4_b.grid(row = 4, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s4_h = Entry(self.details_lf, width = 15)
        self.s4_h.grid(row = 4, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s4_v = Entry(self.details_lf, width = 15)
        self.s4_v.grid(row = 4, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s4_i = Entry(self.details_lf, width = 15)
        self.s4_i.grid(row = 4, column = 5, sticky = 'E', padx = 5, pady = 2)

        Label(self.details_lf, text = "Switch 5 (l, b, h, value, instances):").grid(row = 5, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s5_l = Entry(self.details_lf, width = 15)
        self.s5_l.grid(row = 5, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s5_b = Entry(self.details_lf, width = 15)
        self.s5_b.grid(row = 5, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s5_h = Entry(self.details_lf, width = 15)
        self.s5_h.grid(row = 5, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s5_v = Entry(self.details_lf, width = 15)
        self.s5_v.grid(row = 5, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s5_i = Entry(self.details_lf, width = 15)
        self.s5_i.grid(row = 5, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        self.strat_option_var = StringVar(self.root)
        choices = { 'Strategy 2','Strategy 3','Strategy 1'}
        self.strat_option_var.set('Strategy 3') 
        self.strat_option = OptionMenu(self.hyperparam_lf, self.strat_option_var, *choices)
        Label(self.hyperparam_lf, text="Choose a Strategy: ").grid(row = 0, column = 0)
        self.strat_option.grid(row = 0, column = 1)
        
        self.orientation_allowed_var = IntVar()
        self.orientation_allowed = Checkbutton(self.hyperparam_lf,variable = self.orientation_allowed_var, text="Orientation allowed", onvalue = 1, offvalue = 0)
        self.orientation_allowed.grid(row = 0, column=2, pady = 2, sticky = 'WE')
        self.orientation_allowed.select()
                
        self.pairing_allowed_var = IntVar()
        self.pairing_allowed = Checkbutton(self.hyperparam_lf,variable = self.pairing_allowed_var, text="Pairing allowed", onvalue = 1, offvalue = 0)
        self.pairing_allowed.grid(row = 0, column=3, pady = 2, sticky = 'WE')
        self.pairing_allowed.select()

        Label(self.hyperparam_lf, text = "Strategy 1: width,depth: Value||Volume").grid(row = 1, column = 0, columnspan = 3, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        Label(self.hyperparam_lf, text = "Strategy 2: width,depth: Value/Volume").grid(row = 2, column = 0, columnspan = 3, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        Label(self.hyperparam_lf, text = "Strategy 3: width:Value||Volume, depth:Value/Volume (Most Preferred)").grid(row = 3, column = 0, columnspan = 3, sticky='W', padx=5, pady=0, ipadx=5, ipady=4)
        
        self.exec_time_lbl = Label(self.solve_lf, text = "Execution Completed in: - Seconds")
        self.exec_time_lbl.grid(row = 0, column = 0, columnspan = 5 , pady = 2, sticky = 'W')
        
        self.rs_lbl = Label(self.solve_lf, text = "Remaining Switches:- ")
        self.rs_lbl.grid(row = 1, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.val_gain_lbl = Label(self.solve_lf, text = "Total Value gained: - ")
        self.val_gain_lbl.grid(row = 2, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.vol_pack_lbl = Label(self.solve_lf, text = "% of total volume packed: - %")
        self.vol_pack_lbl.grid(row = 3, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.reset_btn = Button(self.solve_lf, text = "Reset", bg = "lightblue", command = self.reset)
        self.reset_btn.grid(row = 4, column = 2, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)        
        self.solve_btn = Button(self.solve_lf, text = "Solve", bg = "lightblue", command = self.solve)
        self.solve_btn.grid(row = 4, column = 3, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)
        self.vis_btn = Button(self.solve_lf, text = "Visualize", bg = "lightblue", command = self.visualize)
        self.vis_btn.grid(row = 4, column = 4, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)

        
    def run(self):
        self.root.mainloop()
        
    def reset(self):
        self.rack_length.delete(0, END)
        self.rack_height.delete(0, END)
        self.rack_breadth.delete(0, END)
        
        self.s1_b.delete(0, END)
        self.s1_h.delete(0, END)
        self.s1_i.delete(0, END)
        self.s1_l.delete(0, END)
        self.s1_v.delete(0, END)
        
        self.s2_b.delete(0, END)
        self.s2_h.delete(0, END)
        self.s2_i.delete(0, END)
        self.s2_l.delete(0, END)
        self.s2_v.delete(0, END)
        
        self.s3_b.delete(0, END)
        self.s3_h.delete(0, END)
        self.s3_i.delete(0, END)
        self.s3_l.delete(0, END)
        self.s3_v.delete(0, END)
        
        self.s4_b.delete(0, END)
        self.s4_h.delete(0, END)
        self.s4_i.delete(0, END)
        self.s4_l.delete(0, END)
        self.s4_v.delete(0, END)
        
        self.s5_b.delete(0, END)
        self.s5_h.delete(0, END)
        self.s5_i.delete(0, END)
        self.s5_l.delete(0, END)
        self.s5_v.delete(0, END)
        
        self.exec_time_lbl["text"] = "Execution Completed in: - Seconds"
        self.rs_lbl["text"] = "Remaining Switches:- "
        self.val_gain_lbl["text"] = "Total Value gained: - "
        self.vol_pack_lbl["text"] = "% of total volume packed: - %"
        
    def solve(self):
        try:
            self.switch_details.clear()
            self.switch_details.append((int(self.rack_length.get()), int(self.rack_breadth.get()), int(self.rack_height.get())))
            self.switch_details.append((int(self.s1_l.get()), int(self.s1_b.get()), int(self.s1_h.get()), int(self.s1_v.get()), int(self.s1_i.get())))
            self.switch_details.append((int(self.s2_l.get()), int(self.s2_b.get()), int(self.s2_h.get()), int(self.s2_v.get()), int(self.s2_i.get())))
            self.switch_details.append((int(self.s3_l.get()), int(self.s3_b.get()), int(self.s3_h.get()), int(self.s3_v.get()), int(self.s3_i.get())))
            self.switch_details.append((int(self.s4_l.get()), int(self.s4_b.get()), int(self.s4_h.get()), int(self.s4_v.get()), int(self.s4_i.get())))
            self.switch_details.append((int(self.s5_l.get()), int(self.s5_b.get()), int(self.s5_h.get()), int(self.s5_v.get()), int(self.s5_i.get())))
        except ValueError:
            messagebox.showerror("An Error Occured", "Please fill all input fields with number !")
            return
        with open("input.txt",'w') as f:
            for i in self.switch_details:
                for j in i:
                    f.write(' '+str(j))
        import subprocess
        o = bool(self.orientation_allowed_var.get())
        p = bool(self.pairing_allowed_var.get())
        s = self.strat_option_var.get()
        if o:
            if p:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S3.exe")
            else:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Orientation_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Orientation_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Orientation_Allowed_S3.exe")                
        else:
            if p:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Pairing_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Pairing_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Pairing_Allowed_S3.exe")
            else:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_S3.exe")                
                
        with open("forgui.txt") as f:
            data = f.readlines()
        self.exec_time_lbl["text"] = data[0]
        self.rs_lbl["text"] = data[1]
        self.val_gain_lbl["text"] = data[2]
        self.vol_pack_lbl["text"] = data[3]
        self.visualize()
    
    def visualize(self):
        if self.exec_time_lbl["text"] == "Execution Completed in: - Seconds":
            messagebox.showerror("An error occured !", "Solve problem before visulaizing it !")
            return 
        import matplotlib.pyplot as plt

        #5 different colors for 5 different switches (RGBA)
        colors = [(1, 0.1, 0.1, 1), (0.1, 1, 0.1, 1), (0.1, 181/255., 204/255., 1), (1, 0.5, 0.1, 1), (0.23, 0.23, 0.23, 1)]

        #Opening "output.txt" which have info about switches position and their orientation
        with open("output.txt",'r') as f:
            data = f.readlines()

        
        rz, ry, rx = [int(x) for x in data[0].split()]
        data.pop(0)
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        #Making Boundary to fill smooth orientations
        ax.bar3d(0, 0, 0, max(ry,rz,rx), max(ry,rz,rx), max(ry,rz,rx), color = (0, 0, 0, 0), shade = False)
        #Making legend
        type_0 = plt.Rectangle((0, 0), 1, 1, fc = colors[0])
        type_1 = plt.Rectangle((0, 0), 1, 1, fc = colors[1])
        type_2 = plt.Rectangle((0, 0), 1, 1, fc = colors[2])
        type_3 = plt.Rectangle((0, 0), 1, 1, fc = colors[3])
        type_4 = plt.Rectangle((0, 0), 1, 1, fc = colors[4])
        ax.legend([type_0, type_1, type_2, type_3, type_4],['Type 0', 'Type 1', 'Type 2', 'Type 3', 'Type 4'])
        #Creating transparant rack  
        ax.bar3d(0, 0, 0, rx, ry, rz, color = (0, 0, 0, 0.1), shade = False)
        for line in data:
            #Creating switch with appropiate colors
            t, dz, dy, dx, x, y, z = [int(x) for x in line.split()]
            ax.bar3d(x, y, z, dx, dy, dz, color = colors[t], edgecolor = (0, 0, 0, 1), shade = False) 
            
        ax.set_title('Visualization of placed switches')
        plt.show()
예제 #4
0
#Todas las entradas necesarias para una cita
agendar_cita_frame=LabelFrame(ventana_principal,relief=FLAT, bg=Charade,bd=0)
agendar_cita_frame.pack(side=LEFT,fill=Y, expand=True, padx=40, pady=40)
agendar_cita_label=Label(agendar_cita_frame, text="Agendar Cita",font=titulo_font,bg=CuriousBlue, highlightthickness=0)
agendar_cita_label.pack(fill=X)

buscar_medico_frame=LabelFrame(agendar_cita_frame,text="Buscar Medico",width=30, bg=Charade, font=subtitulo_font, labelanchor=N)
buscar_medico_frame.pack(fill=BOTH, expand=True, padx=30, pady=10)
buscar_doctor_label=Label(buscar_medico_frame, text="Ingrese su Busqueda:", bg=Charade, font=subtitulo2_font)
buscar_doctor_label.grid(row=0,column=0,sticky=W)
buscar_doctor_entry=Entry(buscar_medico_frame, width=30, highlightthickness=0,relief=FLAT)
buscar_doctor_entry.grid(row=1,column=0, sticky=W)


framelistbox=LabelFrame(buscar_medico_frame, relief=FLAT)
framelistbox.grid(row=2,column=0)
lista_medicos_listbox=Listbox(framelistbox,width=45,height=4)
lista_medicos_listbox.pack(side=LEFT)
medico_seleccionado_label=Label(buscar_medico_frame, bg=Charade, font=subtitulo5_font)
buscar_doctor_label=Label(buscar_medico_frame, text="Medico escogido:", bg=Charade, font=subtitulo2_font)
buscar_doctor_label.grid(row=3,column=0,sticky=W)
medico_seleccionado_label.grid(row=4,column=0,sticky=W)
scrollbar = Scrollbar(framelistbox)
scrollbar.pack(side=RIGHT,fill=Y)
lista_medicos_listbox.config(yscrollcommand=scrollbar.set)
 
scrollbar.config(command=lista_medicos_listbox.yview)

    #Ingreso de datos del paciente

ingresar_paciente=LabelFrame(agendar_cita_frame,text="Datos del Paciente", bg=Charade, font=subtitulo_font, labelanchor=N)
예제 #5
0
    def fm_request(self):
        token = self.token
        update_frame(self.additional_fr)
        frame_hr = Frame(self.additional_fr)
        frame_hr.grid(row=0, column=0)
        label_project_reference = Label(frame_hr, text="Project Reference")
        label_required_amount = Label(frame_hr, text="Required Amount (SEK)")
        label_reason = Label(frame_hr, text="Reason")

        button_submit = Button(frame_hr, text="Submit", width=10, height=1)

        requesting_department_labelframe = LabelFrame(
            frame_hr, text='Requesting Department', relief=GROOVE, bd=2)
        entry_project_reference = Entry(frame_hr)
        entry_required_amount = Entry(frame_hr)
        entry_reason = Text(frame_hr, height=20, width=10)

        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="administration",
                    text="Administration").grid(row=2, column=0, pady=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="services",
                    text="Services").grid(row=2, column=1, pady=20, padx=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="production",
                    text="Production").grid(row=3, column=0, pady=10, padx=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="financial",
                    text="Financial").grid(row=3, column=1, pady=10, padx=20)

        requesting_department_labelframe.grid(row=1, column=2, pady=20)
        label_project_reference.grid(row=3, column=1, pady=20)
        entry_project_reference.grid(row=3, column=2, pady=20)
        label_required_amount.grid(row=4, column=1, pady=20)
        entry_required_amount.grid(row=4, column=2, pady=20)
        label_reason.grid(row=5, column=1, pady=20)
        entry_reason.grid(row=5, column=2, pady=20, ipady=60, ipadx=35)

        button_submit.grid(row=6, column=1, pady=20)
        label_error = Label(frame_hr,
                            text="",
                            fg="red",
                            font="Helvetica 9 bold")
        requesting_department = self.requesting_department

        def send_form(*args):
            body = {
                "request_department": requesting_department.get(),
                "project_reference": entry_project_reference.get(),
                'required_amount': entry_required_amount.get(),
                'reason': entry_reason.get()
            }
            header = {'Authorization': 'Bearer {}'.format(token)}
            http_request.request("POST",
                                 "/create_financial_request/",
                                 headers=header,
                                 body=json.dumps(body))
            response = http_request.getresponse()
            if response.status > 200:
                frame_hr.config(highlightcolor="red",
                                highlightbackground="red",
                                highlightthickness=3,
                                relief=SOLID,
                                bd=0)
                label_error.config(text="Error click here to get details")
                frame_hr.after(3000, lambda: label_error.config(text=""))
                frame_hr.after(2000, lambda: frame_hr.config(relief=FLAT))
                try:
                    decoded_response = json.loads(response.read().decode())
                    self.error_response = decoded_response["error"]
                except (KeyError, json.decoder.JSONDecodeError):
                    self.status_response = "400 or 500"
                    self.error_response = "No information given by server, information were not properly given"
                label_error.bind("<Button-1>", self.display_error)
            else:
                self.display_validation()

        button_submit.bind("<Button-1>", send_form)
        # self.additional_fr.bind("<Return>", self.send_form)
        frame_hr.bind("<Return>", send_form)
        self.additional_fr.pack()
예제 #6
0
    def create_event_request(self):
        token = self.token
        update_frame(self.additional_fr)
        sub_frame = Frame(self.additional_fr)
        sub_frame.grid(row=0, column=0)
        label_record_number = Label(sub_frame, text="Record Number (Client)")
        label_client_name = Label(sub_frame, text="Client Name")
        label_event_type = Label(sub_frame, text="Event Type")
        label_from_date = Label(sub_frame, text="From Date")
        label_to_date = Label(sub_frame, text="To Date")
        label_number_attendees = Label(sub_frame,
                                       text="Expected number of attendees")
        label_excepted_budget = Label(sub_frame, text="Expected Budget (SEK)")

        entry_number_attendees = Entry(sub_frame)
        entry_expected_budget = Entry(sub_frame)
        preferences_labelframe = LabelFrame(sub_frame,
                                            text='Preferences',
                                            relief=GROOVE,
                                            bd=2)
        preferences_name = self.preferences_name
        entry_to_date = Entry(sub_frame)
        entry_from_date = Entry(sub_frame)
        entry_event_type = Entry(sub_frame)
        entry_client_name = Entry(sub_frame)
        entry_record_number = Entry(sub_frame)
        entry_from_date.insert(END, "yyyy/mm/dd")
        entry_to_date.insert(END, "yyyy/mm/dd")
        button_submit = Button(sub_frame, text="Submit", width=10, height=1)
        label_error = Label(sub_frame,
                            text="",
                            fg="red",
                            font="Helvetica 9 bold")

        Radiobutton(preferences_labelframe,
                    variable=preferences_name,
                    value="decorations",
                    text="Decoration").grid(row=1, column=0, pady=20)
        Radiobutton(preferences_labelframe,
                    variable=preferences_name,
                    value="parties",
                    text="Parties").grid(row=2, column=0, pady=10)
        Radiobutton(preferences_labelframe,
                    variable=preferences_name,
                    value="photos_filming",
                    text="Photos/filming").grid(row=3, column=0, pady=10)
        Radiobutton(preferences_labelframe,
                    variable=preferences_name,
                    value="breakfast_launch_dinner",
                    text="Breakfast, launch, dinner").grid(row=1,
                                                           column=1,
                                                           pady=20,
                                                           padx=20)
        Radiobutton(preferences_labelframe,
                    variable=preferences_name,
                    value="drinks",
                    text="Soft/hot drinks").grid(row=2,
                                                 column=1,
                                                 pady=10,
                                                 padx=20)

        label_record_number.grid(row=1, column=0, pady=20)
        entry_record_number.grid(row=1, column=1, padx=10, pady=20)
        label_client_name.grid(row=2, column=0, pady=20)
        entry_client_name.grid(row=2, column=1, padx=10, pady=20)
        label_event_type.grid(row=3, column=0, pady=20)
        entry_event_type.grid(row=3, column=1, padx=10, pady=20)
        label_from_date.grid(row=4, column=0, pady=20)
        entry_from_date.grid(row=4, column=1, pady=20, padx=10)
        label_to_date.grid(row=4, column=4, pady=20)
        entry_to_date.grid(row=4, column=5, pady=20, padx=10)
        label_number_attendees.grid(row=5, column=0, pady=20)
        entry_number_attendees.grid(row=5, column=1, padx=10, pady=20)
        preferences_labelframe.grid(row=6, column=1, pady=20)
        label_excepted_budget.grid(row=7, column=0, pady=20)
        entry_expected_budget.grid(row=7, column=1, pady=20, padx=10)
        button_submit.grid(row=8, column=1, pady=20)
        label_error.grid(row=8, column=2)

        def send_form(*args):
            body = {
                "record_number": entry_record_number.get(),
                "client_name": entry_client_name.get(),
                "event_type": entry_event_type.get(),
                "from_date": entry_from_date.get(),
                "to_date": entry_to_date.get(),
                "expected_number_attendees": entry_number_attendees.get(),
                "preferences": preferences_name.get()
            }
            print(body)
            header = {'Authorization': 'Bearer {}'.format(token)}
            http_request.request("POST",
                                 "/event_creation/",
                                 headers=header,
                                 body=json.dumps(body))
            response = http_request.getresponse()
            if response.status > 200:
                sub_frame.config(highlightcolor="red",
                                 highlightbackground="red",
                                 highlightthickness=3,
                                 relief=SOLID,
                                 bd=0)
                label_error.config(text="Error click here to get details")
                sub_frame.after(3000, lambda: label_error.config(text=""))
                sub_frame.after(2000, lambda: sub_frame.config(relief=FLAT))
                try:
                    decoded_response = json.loads(response.read().decode())
                    self.error_response = decoded_response["error"]
                except (KeyError, json.decoder.JSONDecodeError):
                    self.status_response = "400 or 500"
                    self.error_response = "No information given by server, information were not properly given"
                label_error.bind("<Button-1>", self.display_error)
            else:
                self.display_validation()

        button_submit.bind("<Button-1>", send_form)
        self.additional_fr.bind("<Return>", send_form)
        self.additional_fr.pack()
예제 #7
0
class FormChildAED:
    def __init__(self, frm_parent, title, connection):
        self.connection = connection
        self.directive = Message()
        self.title = title
        self.decide = True
        self.id_selected = 0
        self.frm_child_list = LabelFrame(frm_parent)
        self.frm_child_crud = LabelFrame(frm_parent)
        self.frm_child_crud.config(fg=TEXT_COLOR, font=SUBTITLE_FONT)
        self.initialize_components()

    def initialize_components(self):
        """
        Method that initialize the visual components for each form associated with the local administration
        """
        # Resources for the Forms
        self.new_icon = PhotoImage(file=r"./Resources/create.png")
        self.modify_icon = PhotoImage(file=r"./Resources/modify.png")
        self.remove_icon = PhotoImage(file=r"./Resources/delete.png")
        self.save_icon = PhotoImage(file=r"./Resources/save.png")
        self.cancel_icon = PhotoImage(file=r"./Resources/cancel.png")

        # Components for List Form
        lbl_sep1 = Label(self.frm_child_list)
        lbl_sep1.grid(row=0, column=0, padx=10, pady=25)
        self.trv_available = Treeview(self.frm_child_list,
                                      height=15,
                                      columns=('N', 'Name', 'Surname',
                                               'E-mail'))
        self.trv_available.heading('#0', text='ID', anchor=CENTER)
        self.trv_available.heading('#1', text='N', anchor=CENTER)
        self.trv_available.heading('#2', text='Name', anchor=CENTER)
        self.trv_available.heading('#3', text='Surname', anchor=CENTER)
        self.trv_available.heading('#4', text='E-mail', anchor=CENTER)
        self.trv_available.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_available.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_available.column('#2', width=200, minwidth=200, stretch=NO)
        self.trv_available.column('#3', width=200, minwidth=200, stretch=NO)
        self.trv_available.column('#4', width=400, minwidth=400, stretch=NO)
        self.trv_available.grid(row=0, column=1, sticky=W, pady=25)
        vsb_trv_av = Scrollbar(self.frm_child_list,
                               orient="vertical",
                               command=self.trv_available.yview)
        vsb_trv_av.grid(row=0, column=2, pady=25, sticky=NS)
        self.trv_available.configure(yscrollcommand=vsb_trv_av.set)
        frm_aux4 = Frame(self.frm_child_list)
        btn_new = Button(frm_aux4, image=self.new_icon, command=self.click_new)
        btn_new.grid(row=0, column=0, pady=5, padx=5, sticky=E)
        btn_new_ttp = CreateToolTip(btn_new, 'New ' + self.title.lower())
        btn_edit = Button(frm_aux4,
                          image=self.modify_icon,
                          command=self.click_update)
        btn_edit.grid(row=1, column=0, pady=5, padx=5, sticky=E)
        btn_edit_ttp = CreateToolTip(btn_edit, 'Edit ' + self.title.lower())
        btn_delete = Button(frm_aux4,
                            image=self.remove_icon,
                            command=self.click_delete)
        btn_delete.grid(row=2, column=0, pady=5, padx=5, sticky=E)
        btn_delete_ttp = CreateToolTip(btn_delete,
                                       'Delete ' + self.title.lower())
        frm_aux4.grid(row=0, column=3, pady=25, padx=25, sticky=NW)

        # Components for CRUD FRM
        lbl_name = Label(self.frm_child_crud, text='Name*')
        lbl_name.config(fg=TEXT_COLOR, font=LABEL_FONT)
        lbl_name.grid(row=0, column=0, pady=10, padx=20, sticky=W)
        lbl_surname = Label(self.frm_child_crud, text='Surname*')
        lbl_surname.config(fg=TEXT_COLOR, font=LABEL_FONT)
        lbl_surname.grid(row=1, column=0, pady=10, padx=20, sticky=W)
        lbl_email = Label(self.frm_child_crud, text='E-mail*')
        lbl_email.config(fg=TEXT_COLOR, font=LABEL_FONT)
        lbl_email.grid(row=2, column=0, pady=10, padx=20, sticky=W)
        self.lbl_old_passwd = Label(self.frm_child_crud, text='Old password*')
        self.lbl_old_passwd.config(fg=TEXT_COLOR, font=LABEL_FONT)
        self.lbl_passwd = Label(self.frm_child_crud, text='New password*')
        self.lbl_passwd.config(fg=TEXT_COLOR, font=LABEL_FONT)
        self.lbl_passwd_conf = Label(self.frm_child_crud,
                                     text='Confirm new password*')
        self.lbl_passwd_conf.config(fg=TEXT_COLOR, font=LABEL_FONT)
        self.txt_name = Entry(self.frm_child_crud)
        self.txt_name.grid(row=0, column=1, pady=10, padx=20, sticky=W)
        self.txt_surname = Entry(self.frm_child_crud)
        self.txt_surname.grid(row=1, column=1, pady=10, padx=20, sticky=W)
        self.txt_email = Entry(self.frm_child_crud)
        self.txt_email.grid(row=2, column=1, pady=10, padx=20, sticky=W)
        self.txt_old_passwd = Entry(self.frm_child_crud, show="*")
        self.txt_passwd = Entry(self.frm_child_crud, show="*")
        self.txt_passwd_conf = Entry(self.frm_child_crud, show="*")
        sep_aux2 = Separator(self.frm_child_crud, orient=VERTICAL)
        sep_aux2.grid(row=0, column=2, sticky=NS, rowspan=6)
        frm_aux = Frame(self.frm_child_crud)
        btn_save = Button(frm_aux,
                          image=self.save_icon,
                          command=self.click_save)
        btn_save.grid(row=0, column=0, padx=5, pady=5, sticky=E)
        btn_save_ttp = CreateToolTip(btn_save, 'Save ' + self.title.lower())
        btn_cancel = Button(frm_aux,
                            image=self.cancel_icon,
                            command=self.click_cancel)
        btn_cancel.grid(row=1, column=0, padx=5, pady=5, sticky=E)
        btn_cancel_ttp = CreateToolTip(btn_cancel, 'Cancel')
        frm_aux.grid(row=0, column=3, pady=10, padx=25, sticky=N, rowspan=6)

    def retrieve_list(self):
        """
        Method that retrieve users information from the server and displays them in the TreeView from
        the List Form
        """
        # Remove existing elements in the list
        for item in self.trv_available.get_children():
            self.trv_available.delete(item)
        # Retrieve information from the server
        if self.title == 'Experimenter':
            self.directive = Message(action=17)
        elif self.title == 'Designer':
            self.directive = Message(action=22)
        elif self.title == 'Administrator':
            self.directive = Message(action=12)
        else:
            raise Exception('Error en recuperacion: tipo de usuario')
        self.connection = self.directive.send_directive(self.connection)
        # Adding elements in the list
        for index, item in enumerate(self.connection.message.information):
            elements = item.split('¥')
            self.trv_available.insert('',
                                      'end',
                                      text=elements[0],
                                      values=(index + 1, elements[1],
                                              elements[2], elements[3]))
        # Mark first element of the treeview if exist
        if len(self.trv_available.get_children()) != 0:
            self.trv_available.selection_set(
                self.trv_available.get_children()[0])

    def show_frm(self):
        """
        Show the List form when the User administration is called
        """
        self.retrieve_list()
        self.frm_child_list.grid(row=1,
                                 column=0,
                                 columnspan=9,
                                 rowspan=8,
                                 pady=10,
                                 padx=10)

    def hide_frm(self):
        """
        Hide the User administration Forms
        """
        self.clear_fields()
        self.frm_child_list.grid_forget()
        self.frm_child_crud.grid_forget()

    def click_new(self):
        """
        Initialize CRUD Form for creating a new user.
        """
        self.user = Designer()
        self.frm_child_list.grid_forget()
        self.txt_name.focus_set()
        self.frm_child_crud['text'] = 'New ' + self.title.lower()
        self.lbl_passwd.grid(row=3, column=0, pady=10, padx=20, sticky=W)
        self.lbl_passwd_conf.grid(row=4, column=0, pady=10, padx=20, sticky=W)
        self.txt_passwd.grid(row=3, column=1, pady=10, padx=20, sticky=W)
        self.txt_passwd_conf.grid(row=4, column=1, pady=10, padx=20, sticky=W)
        self.frm_child_crud.grid(row=1,
                                 column=0,
                                 columnspan=9,
                                 rowspan=8,
                                 pady=10,
                                 padx=10)

    def click_update(self):
        """
        Initialize CRUD Form for updating a user. It loads information of selected User into visual components
        """
        if len(self.trv_available.selection()) == 1:
            id_selected = int(
                self.trv_available.item(
                    self.trv_available.selection())['text'])
            if self.title == 'Experimenter':
                self.directive = Message(action=20, information=[id_selected])
            elif self.title == 'Designer':
                self.directive = Message(action=25, information=[id_selected])
            else:
                self.directive = Message(action=15, information=[id_selected])
            self.connection = self.directive.send_directive(self.connection)
            if self.connection.message.action == 5:  # An error ocurred while trying to update the item
                messagebox.showerror(
                    parent=self.frm_child_list,
                    title='Can not update the item',
                    message=self.connection.message.information[0])
            else:
                self.user = Designer(
                    id=id_selected,
                    name=self.connection.message.information[0],
                    surname=self.connection.message.information[1],
                    user=self.connection.message.information[2],
                    password=self.connection.message.information[3])
                self.txt_name.insert(0, self.user.name)
                self.txt_surname.insert(0, self.user.surname)
                self.txt_email.insert(0, self.user.user)
                self.frm_child_list.grid_forget()
                self.txt_name.focus_set()
                self.frm_child_crud['text'] = 'Update ' + self.title.lower()
                self.lbl_old_passwd.grid(row=3,
                                         column=0,
                                         pady=10,
                                         padx=20,
                                         sticky=W)
                self.lbl_passwd.grid(row=4,
                                     column=0,
                                     pady=10,
                                     padx=20,
                                     sticky=W)
                self.lbl_passwd_conf.grid(row=5,
                                          column=0,
                                          pady=10,
                                          padx=20,
                                          sticky=W)
                self.txt_old_passwd.grid(row=3,
                                         column=1,
                                         pady=10,
                                         padx=20,
                                         sticky=W)
                self.txt_passwd.grid(row=4,
                                     column=1,
                                     pady=10,
                                     padx=20,
                                     sticky=W)
                self.txt_passwd_conf.grid(row=5,
                                          column=1,
                                          pady=10,
                                          padx=20,
                                          sticky=W)
                self.frm_child_crud.grid(row=1,
                                         column=0,
                                         columnspan=9,
                                         rowspan=8,
                                         pady=10,
                                         padx=10)
        else:
            messagebox.showwarning(parent=self.frm_child_list,
                                   title='No selection',
                                   message='You must select one item')

    def click_delete(self):
        """
        Method that removes a selected user from the initial list (changes are updated in DB)
        """
        if len(self.trv_available.selection()) == 1:
            decision = messagebox.askyesno(
                parent=self.frm_child_list,
                title='Confirmation',
                message='Are you sure you want to delete the item?')
            if decision:
                id_selected = int(
                    self.trv_available.item(
                        self.trv_available.selection())['text'])
                if self.title == 'Experimenter':
                    self.directive = Message(action=19,
                                             information=[id_selected])
                elif self.title == 'Designer':
                    self.directive = Message(action=24,
                                             information=[id_selected])
                else:
                    self.directive = Message(action=14,
                                             information=[id_selected])
                self.connection = self.directive.send_directive(
                    self.connection)
                if self.connection.message.action == 5:  # An error ocurred while deleting the item
                    messagebox.showerror(
                        parent=self.frm_child_list,
                        title='Can not delete the item',
                        message=self.connection.message.information[0])
                else:
                    self.retrieve_list()
        else:
            messagebox.showwarning(parent=self.frm_child_list,
                                   title='No selection',
                                   message='You must select one item')

    def click_save(self):
        """
        Saves information of the user inserted into the visual components and sends to the server
        """
        if self.validate_fields():
            self.user.name = self.txt_name.get()
            self.user.surname = self.txt_surname.get()
            self.user.user = self.txt_email.get()
            self.user.password = self.txt_passwd.get()
            if self.user.id == 0:  # Creating an user
                if self.title == 'Experimenter':
                    self.directive = Message(
                        action=16,
                        information=[
                            self.user.name, self.user.surname, self.user.user,
                            hashlib.sha1(
                                self.user.password.encode()).hexdigest()
                        ])
                elif self.title == 'Designer':
                    self.directive = Message(
                        action=21,
                        information=[
                            self.user.name, self.user.surname, self.user.user,
                            hashlib.sha1(
                                self.user.password.encode()).hexdigest()
                        ])
                else:
                    self.directive = Message(
                        action=11,
                        information=[
                            self.user.name, self.user.surname, self.user.user,
                            hashlib.sha1(
                                self.user.password.encode()).hexdigest()
                        ])
            else:  # Updating an user
                if self.title == 'Experimenter':
                    self.directive = Message(
                        action=18,
                        information=[
                            self.user.id, self.user.name, self.user.surname,
                            self.user.user,
                            hashlib.sha1(
                                self.user.password.encode()).hexdigest()
                        ])
                elif self.title == 'Designer':
                    self.directive = Message(
                        action=23,
                        information=[
                            self.user.id, self.user.name, self.user.surname,
                            self.user.user,
                            hashlib.sha1(
                                self.user.password.encode()).hexdigest()
                        ])
                else:
                    self.directive = Message(action=13,
                                             information=[
                                                 self.user.id, self.user.name,
                                                 self.user.surname,
                                                 self.user.user,
                                                 self.user.password
                                             ])
            self.connection = self.directive.send_directive(self.connection)
            if self.connection.message.action == 5:
                messagebox.showwarning(parent=self.frm_child_crud,
                                       title='Repeated e-mail',
                                       message=self.connection.message.comment)
            else:
                self.clear_fields()
                self.frm_child_crud.grid_forget()
                self.show_frm()

    def click_cancel(self):
        """
        Function activated when 'Cancel' button is pressed in frm_child_crud
        """
        decision = True
        if self.txt_name.get() != self.user.name or \
                self.txt_surname.get() != self.user.surname or \
                self.txt_email.get() != self.user.user or len(self.txt_passwd.get()) != 0 or \
                len(self.txt_passwd_conf.get()) != 0:
            if self.user.id != 0 and len(
                    self.txt_passwd_conf.get()) != 0 or self.user.id == 0:
                decision = messagebox.askyesno(
                    parent=self.frm_child_crud,
                    title='Cancel',
                    message='Are you sure you want to cancel?')
        if decision:
            self.clear_fields()
            self.frm_child_crud.grid_forget()
            self.show_frm()

    def validate_fields(self):
        if len(self.txt_name.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must insert a name for the {}'.format(
                    self.title.lower()))
            return False
        if len(self.txt_surname.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must insert a surname for the {}'.format(
                    self.title.lower()))
            return False
        if len(self.txt_email.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must insert an e-mail for the {}'.format(
                    self.title.lower()))
            return False
        # If updating an user
        if self.user.id != 0 and len(self.txt_old_passwd.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must insert the old password for the {}'.format(
                    self.title.lower()))
            return False
        if len(self.txt_passwd.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must insert a new password for the {}'.format(
                    self.title.lower()))
            return False
        if len(self.txt_passwd_conf.get()) == 0:
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Missing information',
                message='You must confirm the new password for the {}'.format(
                    self.title.lower()))
            return False
        if self.txt_passwd.get() != self.txt_passwd_conf.get():
            messagebox.showwarning(
                parent=self.frm_child_crud,
                title='Password field',
                message=
                'The new password you provided does not match the confirmation'
            )
            return False
        # If updating an user
        if self.user.id != 0 and self.user.password != hashlib.sha1(
                self.txt_old_passwd.get().encode()).hexdigest():
            messagebox.showwarning(parent=self.frm_child_crud,
                                   title='Old password field',
                                   message='The old password is incorrect')
            return False
        return True

    def clear_fields(self):
        self.txt_name.delete(0, END)
        self.txt_surname.delete(0, END)
        self.txt_email.delete(0, END)
        self.txt_old_passwd.delete(0, END)
        self.txt_passwd.delete(0, END)
        self.txt_passwd_conf.delete(0, END)
        self.lbl_old_passwd.grid_forget()
        self.lbl_passwd.grid_forget()
        self.lbl_passwd_conf.grid_forget()
        self.txt_old_passwd.grid_forget()
        self.txt_passwd.grid_forget()
        self.txt_passwd_conf.grid_forget()
'''

from tkinter import Tk, Button, LabelFrame

ROOT = Tk()
ROOT.geometry('200x60')
ROOT.title('Button Test')


def clk_but(butn_num):
    '''A button was clicked, print which one'''
    print(butn_num)


FRAME0 = LabelFrame(ROOT, text='')
FRAME0.grid()

BUT1 = Button(FRAME0,
              bg='skyblue',
              text='Click Me 1',
              command=lambda: clk_but("clicked button 1"))
BUT1.grid()

BUT2 = Button(FRAME0,
              bg='orange',
              text='Click Me 2',
              command=lambda: clk_but("clicked button 2"))
BUT2.grid()

ROOT.mainloop()
예제 #9
0
class CreateGUI:
    def __init__(self, parent):
        self.parent = parent
        parent.title("Cross section 2000")
        parent.geometry('450x500')
        parent.resizable(False, False)

        # Add icon for the window
        parent.iconbitmap('icon_beam_2000.ico')

        # Add exit button
        self.exit = Button(parent, text="Exit", command=self.exit, width=20)
        self.exit.grid(row=4, column=1, padx=60, pady=10)

        # Input - Geometric input ======================================================================================

        # Create a lableframe to store the geometry entrys in
        self.geometryframe = LabelFrame(parent,
                                        text="Geometry",
                                        padx=10,
                                        pady=10)
        self.geometryframe.grid(row=0, column=0, columnspan=4, sticky=W + E)

        self.labeld = Label(self.geometryframe, text="d [m]")
        self.labeld.grid(row=0, column=0, sticky=E, padx=4)

        self.entryd = Entry(self.geometryframe, width=8)
        self.entryd.grid(row=0, column=1, padx=4, columnspan=1)

        self.labelb = Label(self.geometryframe, text="b [m]")
        self.labelb.grid(row=1, column=0, sticky=E, padx=4)

        self.entryb = Entry(self.geometryframe, width=8)
        self.entryb.grid(row=1, column=1, padx=4, columnspan=1)

        self.labeln = Label(self.geometryframe, text="No\u0332 bars")
        self.labeln.grid(row=2, column=0, padx=4, columnspan=1)

        self.entryn = Entry(self.geometryframe, width=8)
        self.entryn.grid(row=2, column=1, padx=4, columnspan=1)

        # Input - Reinforcement type ===================================================================================

        # Import reinforcement specs
        self.reinforcement_table = pd.read_excel('InputData.xlsx',
                                                 'Reinforcement')

        # Use the diamter as index
        self.reinforcement_table.set_index('Diameter', inplace=True)

        # Add a column with reinforcement name
        self.reinforcement_table[
            'name'] = '\u03D5' + self.reinforcement_table.index.astype(
                str) + 'B500B'

        # Create drop down menu
        self.initial_value_reinforcement = StringVar(parent)
        self.initial_value_reinforcement.set(self.reinforcement_table.iloc[3,
                                                                           -1])

        self.popupMenu = OptionMenu(self.geometryframe,
                                    self.initial_value_reinforcement,
                                    *self.reinforcement_table.name)
        self.popupMenu.grid(row=3, column=0, columnspan=2)

        # Create canvas for drawing a beam illustration ================================================================

        self.canvas = Canvas(self.geometryframe, width=300, height=140)
        self.canvas.grid(row=0, column=2, columnspan=1, rowspan=4)

        # Call draw_beam to draw a cross section of a beam
        Illustrator(self.parent, self.canvas)

        # Labelframe for material properties ===========================================================================

        # Create a labelframe for material inputs
        self.materialframe = LabelFrame(parent,
                                        text="Material properties",
                                        padx=40,
                                        pady=10)
        self.materialframe.grid(row=2, column=0, columnspan=4, sticky=W + E)

        # Create a labeframe to store the partial coefficient entrys in
        self.partialframe = LabelFrame(self.materialframe,
                                       text="Partial coefficients" + " \u03B3")
        self.partialframe.grid(row=0, column=0, columnspan=1, rowspan=1)

        self.label_concrete = Label(self.partialframe, text="concrete")
        self.label_concrete.grid(row=0, sticky=E, pady=5)

        self.entry_concrete = Entry(self.partialframe, width=8)
        self.entry_concrete.grid(row=0, column=1, pady=5, padx=20, sticky=W)

        self.label_steel = Label(self.partialframe, text="steel")
        self.label_steel.grid(row=1, sticky=E, pady=5)

        self.entry_steel = Entry(self.partialframe, width=8)
        self.entry_steel.grid(row=1, column=1, pady=5, padx=20, sticky=W)

        # Input - Concrete type ========================================================================================

        # Create labelframe for concrete strength
        self.concreteframe = LabelFrame(self.materialframe,
                                        text="Concrete properties")
        self.concreteframe.grid(row=0,
                                column=1,
                                columnspan=1,
                                rowspan=1,
                                padx=30)

        self.label_steel = Label(self.concreteframe,
                                 text="Choose concrete strength")
        self.label_steel.grid(row=0, sticky=E, pady=5, padx=20)

        # Import concrete specs
        self.concrete_series = pd.read_excel('InputData.xlsx', 'Concrete')
        self.concrete_series['name'] = (self.concrete_series['Strength'] /
                                        1e+6).astype(str) + ' MPa'

        # Create drop down menu
        self.initial_value_concrete = StringVar(parent)
        self.initial_value_concrete.set(self.concrete_series.iloc[0, -1])

        self.dropdownmenu_concrete = OptionMenu(self.concreteframe,
                                                self.initial_value_concrete,
                                                *self.concrete_series.name)
        self.dropdownmenu_concrete.grid(row=1, column=0)

        # Labelframe for analysis ======================================================================================

        self.analysisframe = LabelFrame(parent,
                                        text="Analysis",
                                        padx=40,
                                        pady=10)
        self.analysisframe.grid(row=3, column=0, columnspan=4, sticky=W + E)

        self.calculate = Button(self.analysisframe,
                                text="Calculate",
                                command=self.calculate_moment_capacity,
                                width=20)
        self.calculate.grid(row=3, column=1, pady=15, padx=15)

        # Adding entry to accomondate the answer
        self.answerentry = Entry(self.analysisframe, text='', borderwidth=3)
        self.answerentry.grid(row=3, column=2, sticky=W, pady=15, padx=35)

    def exit(self):
        parent.destroy()

    def calculate_moment_capacity(self):

        # Retrieve values from GUI window
        d = float(self.entryd.get())
        b = float(self.entryb.get())
        n = float(self.entryn.get())
        partial_coefficient_concrete = float(self.entry_concrete.get())
        partial_coefficient_steel = float(self.entry_steel.get())
        reinforcement_type = self.initial_value_reinforcement.get()
        fck_name = self.initial_value_concrete.get()

        # Calculate reinforcement area
        Asi = self.reinforcement_table.loc[self.reinforcement_table['name'] ==
                                           reinforcement_type, 'Area'].item()
        As = n * Asi

        # Retrieve value for steel stiffness
        Es = self.reinforcement_table.loc[self.reinforcement_table['name'] ==
                                          reinforcement_type,
                                          'Stiffness'].item()

        # Calculate design values based on partial coefficients
        fyk = self.reinforcement_table.loc[self.reinforcement_table['name'] ==
                                           reinforcement_type,
                                           'Strength'].item()
        fyd = partial_coefficient_steel * fyk

        fck = self.concrete_series.loc[self.concrete_series['name'] ==
                                       fck_name, 'Strength'].item()

        fcd = partial_coefficient_concrete * fck

        answer_MRd = M_Rd(d, b, As, fcd, fyd, Es)

        # Display answer
        self.answerentry.insert(0, str(round(answer_MRd / 1e+3, 2)) + " kNm")
예제 #10
0
    def __init__(self, pokerController):
        super().__init__()

        # Name of the window.
        self.title("FireCashGame")

        # Truc pour le redimensionnement automatique des éléments de la fenêtre.
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        # Placing labels
        etiq = Label(self , text="BobTracker")
        etiq.grid()

        fra_stats = LabelFrame(self, text="Stats")
        fra_stats.grid(row=1,column=1, sticky=N+S)

        playerName = StringVar()
        playerName.set("Bobsleigh37")


        self.averageGain = StringVar()
        self.maxGain = StringVar()
        self.maxLoss = StringVar()
        self.amountOfHands = StringVar()


        lab_playerName = Label(fra_stats, text="Player Name", anchor=W)
        lab_playerName.grid(row=0,column=0,sticky=N+W+E)
        lab_playerNameVar = Label(fra_stats, textvariable=playerName, anchor=W)
        lab_playerNameVar.grid(row=0,column=1,sticky=E)
        lab_avg = Label(fra_stats, text = "Average gain", anchor=W)
        lab_avg.grid(row=1,column=0,sticky=N+W+E)
        self.lab_avgVar = Label(fra_stats, textvariable=self.averageGain, anchor=E)
        self.lab_avgVar.grid(row=1,column=1,sticky=E)
        lab_maxGain = Label(fra_stats, text="Maximum gain", anchor=W)
        lab_maxGain.grid(row=2,column=0,sticky=N+W+E)
        lab_maxGainVar = Label(fra_stats, textvariable=self.maxGain, anchor=E)
        lab_maxGainVar.grid(row=2,column=1,sticky=E)
        lab_maxLoss = Label(fra_stats, text="Maximum loss", anchor=W)
        lab_maxLoss.grid(row=3,column=0,sticky=N+W+E)
        lab_maxLossVar = Label(fra_stats, textvariable = self.maxLoss, anchor=E)
        lab_maxLossVar.grid(row=3,column=1,sticky=E)
        lab_amountOfHands = Label(fra_stats, text="Hands in file", anchor=W)
        lab_amountOfHands.grid(row=4,column=0,sticky=N+W+E)
        lab_amountOfHandsVar = Label(fra_stats, textvariable= self.amountOfHands, anchor=E)
        lab_amountOfHandsVar.grid(row=4,column=1,sticky=E)

        self.pokerController = pokerController
        self.cashGame = CashGame()

        f = Figure(figsize=(10,6), dpi=100)
        a = f.add_subplot(111)
        a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
        a.set_title('Chips Tracking')
        a.set_xlabel('Hand number')
        a.set_ylabel('Chip count')

        # Create frame for the canvas
        frame = Frame(self)
        label = Label(frame, text="Graph Page!")
        frame.grid()

        # Create canvas to display the graph plot
        canvas = FigureCanvasTkAgg(f, master=self)
        canvas.get_tk_widget().grid(row=1, column=0,padx=20,pady=20)

        btn_cash_session = Button(self, text='Update Stats', command= lambda: self.updateSession(a, canvas))
        btn_cash_session.grid()

        self.openCashSession()
예제 #11
0
class QuizMe(Frame):

    PROMPT = 'What testbank do you want to open?'

    def __init__(self, master):
        # Initialize the Frame object.
        super().__init__(master)
        # Create every opening widget.
        self.intro = Label(self, text=self.PROMPT)
        self.group = LabelFrame(self, text='Filename')
        self.entry = Entry(self.group, width=35)
        self.click = Button(self.group, text='Browse ...', command=self.file)
        self.enter = Button(self, text='Continue', command=self.start)
        # Make Windows entry bindings.
        def select_all(event):
            event.widget.selection_range(0, tkinter.END)
            return 'break'
        self.entry.bind('<Control-Key-a>', select_all)
        self.entry.bind('<Control-Key-/>', lambda event: 'break')
        # Position them in this frame.
        options = {'sticky': tkinter.NSEW, 'padx': 5, 'pady': 5}
        self.intro.grid(row=0, column=0, **options)
        self.group.grid(row=1, column=0, **options)
        self.entry.grid(row=0, column=0, **options)
        self.click.grid(row=0, column=1, **options)
        self.enter.grid(row=2, column=0, **options)

    def file(self):
        # Find filename for self.entry
        options = {'defaultextension': '.xml',
                   'filetypes': [('All', '*'), ('XML', '.xml')],
                   'initialdir': os.path.join(os.getcwd(), 'tests'),
                   'parent': self,
                   'title': 'Testbank to Open'}
        filename = askopenfilename(**options)
        if filename:
            self.entry.delete(0, tkinter.END)
            self.entry.insert(0, filename)

    def start(self):
        # Validate self.entry and begin
        path = self.entry.get()
        if os.path.exists(path):
            if os.path.isfile(path):
                try:
                    bank = testbank.parse(path)
                    engine = teach_me.FAQ(bank)
                except xml.sax._exceptions.SAXParseException as error:
                    title = error.getMessage().title()
                    LN = error.getLineNumber()
                    CN = error.getColumnNumber()
                    message = 'Line {}, Column {}'.format(LN, CN)
                    showerror(title, message, master=self)
                except AssertionError as error:
                    title = 'Validation Error'
                    message = error.args[0]
                    showerror(title, message, master=self)
                except:
                    title = 'Error'
                    message = 'Unknown exception was thrown!'
                    showerror(title, message, master=self)
                else:
                    self.done = False
                    self.next_event = iter(engine).__next__
                    self.after_idle(self.execute_quiz)
            else:
                title = 'Warning'
                message = 'File does not exist.'
                showwarning(title, message, master=self)
        else:
            title = 'Information'
            message = 'Path does not exist.'
            showinfo(title, message, master=self)

    def execute_quiz(self):
        # Follow the logic from the last program.
        # This will be called to handle an event.
        try:
            event = self.next_event()
        except StopIteration:
            assert self.done, 'Final event not processed!'
        else:
            if isinstance(event, teach_me.Enter):
                gui_logs.ShowStatus(self, 'Entering', event, self.execute_quiz)
            elif isinstance(event, teach_me.Exit):
                gui_logs.ShowStatus(self, 'Exiting', event, self.execute_quiz)
                self.last_exit = event.kind
            elif isinstance(event, teach_me.Question):
               gui_logs. AskQuestion(self, event, self.execute_quiz)
            elif isinstance(event, teach_me.Report):
                flag = [True]
                if self.last_exit == 'Section' and event.wrong:
                    flag[0] = False
                    gui_logs.ReviewProblems(self, event, flag)
                if flag[0]:
                    gui_logs.ShowReport(self, event, self.execute_quiz)
                if event.final:
                    title = 'Congratulations!'
                    message = 'You have finished the test.'
                    showinfo(title, message, master=self)
                    self.done = True
            else:
                title = 'Type Error'
                message = repr(event)
                showerror(title, message, master=self)
예제 #12
0
class Main:
    def __init__(self, master):  # we will define everything in the UI below
        logger.info("Program start")
        self.master = master
        self.master.wm_title("Lautaloader v.1.03")  # title of window
        self.master.resizable(width=FALSE, height=FALSE)  # window is not resizable
        self.master.geometry('420x240')  # resolution of the window in pixels
        self.master.grid_propagate(False)  # window will not resize in any case

        self.r_selection = IntVar()  # these are radiobuttons and checkbuttons
        self.c1_selection = IntVar()
        self.c2_selection = IntVar()
        self.c1_selection.set(0)  # checkbuttons will be off at launch
        self.c2_selection.set(0)
        self.r_selection.set(1)  # we need one radiobutton selected at start

        self.status_text = StringVar()  # status text is visible at the bottom of GUI
        self.status_text.set('Ready to work')  # we can (and will) set the status text like this
        self.save_folder = ''  # we will save into this folder
        self.filenames = []  # this is our folder filenames list
        self.url_text = StringVar()
        self.num_pics = 0
        self.num_mp4 = 0
        self.num_mp3 = 0
        self.image_url = ''
        self.name_of_file = ''
        self.res = ''
        self.imagefile = ''
        self.filesize = ''
        self.imagewritten = False
        self.read_timeout = 1.0
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
            'Upgrade-Insecure-Requests': '1',
            'Referer': '',
            'DNT': '1',
            'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        }  # need to send some headers or server refuses connection

        self.lf = LabelFrame(master, text=' Get ')
        self.lf.grid(row=1, column=1, rowspan=4)

        self.lf2 = LabelFrame(master, text=' Options ')
        self.lf2.grid(row=1, column=2)

        self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1)
        self.R1.grid(row=1, column=1, sticky=W)

        self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2)
        self.R2.grid(row=2, column=1, sticky=W)

        self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3)
        self.R3.grid(row=3, column=1, sticky=W)

        self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4)
        self.R4.grid(row=4, column=1, sticky=W)

        self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection,
                              state=NORMAL, onvalue=1, offvalue=0)
        self.C1.grid(row=1, column=2, sticky=W)

        self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection,
                              state=NORMAL, onvalue=1, offvalue=0)
        self.C2.grid(row=2, column=2, sticky=W)

        self.folder_label = Label(master, text="Folder: ")
        self.folder_label.grid(row=5, sticky=E)

        self.url_label = Label(root, text="URL: ")
        self.url_label.grid(row=6, sticky=E)

        self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50)
        self.folder_entry.grid(row=5, column=1, columnspan=2)

        self.url_entry = Entry(master, textvariable=self.url_text, width=50)
        self.url_entry.grid(row=6, column=1, columnspan=2)

        self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder)
        self.selectbutton.grid(row=5, column=3, sticky=W)

        self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder)
        self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22)

        self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic)
        self.urlbutton.grid(row=6, column=3, sticky=W)

        self.status = Label(master, textvariable=self.status_text, wraplength=300)
        self.status.grid(row=9, columnspan=4, sticky=W)

        self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate")
        self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3)

        self.manage_config()  # process through config file

        self.url_1 = config.get('basic_config', 'url_1')
        logging.debug("url_1 set to %s" % self.url_1)
        self.url_2 = config.get('basic_config', 'url_2')
        logging.debug("url_2 set to %s" % self.url_2)

        if self.save_folder != '':  # if save folder is not empty, we probably have a valid folder
            self.urlbutton['state'] = 'normal'   # so we can enable urlbutton already
            self.openfolderbutton['state'] = 'normal'  # and we can also enable open folder button

    def manage_config(self):
        if not os.path.isfile(os.path.expanduser("~\\documents\\lloader_cfg.ini")):
            with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile:
                config.add_section('basic_config')  # cfg file not exists so we make it
                config.set('basic_config', 'save_folder', self.save_folder)
                config.set('basic_config', 'html_tag1', ".filecontainer figcaption a")
                config.set('basic_config', 'html_tag2', ".filecontainer .file a")
                config.set('basic_config', 'url_1', "ylilauta.org")
                config.set('basic_config', 'url_2', "www.ylilauta.org")
                # .filecontainer .file a = ALL images (np included) but not mp4
                # .filecontainer figcaption a = not np images, but all uploaded images & mp4
                config.write(cfgfile)
                logger.debug("Created a config file")
        else:
            try:
                config.read(os.path.expanduser('~\\documents\\lloader_cfg.ini'))
                self.folder_entry['state'] = 'normal'  # make the folder field writable
                self.folder_entry.delete(0, END)
                self.save_folder = config.get('basic_config', 'save_folder')  # get save folder from file
                self.folder_entry.insert(0, self.save_folder)  # write to folder field
                self.folder_entry['state'] = 'readonly'  # make it read-only again
                logger.debug("Read from config")

            except (IOError, OSError):
                logger.exception("Config error")
            except (configparser.MissingSectionHeaderError, configparser.NoSectionError):  # correct section not found from file
                os.remove(os.path.expanduser("~\\documents\\lloader_cfg.ini"))
                self.manage_config()  # delete file and try to create it from start

    def get_folder(self):
        dir_opt = options = {}  # define options for get folder function
        options['initialdir'] = self.save_folder
        options['mustexist'] = False
        options['parent'] = self.master
        options['title'] = 'Choose a directory'

        self.save_folder = filedialog.askdirectory(**dir_opt)  # actual function to get the folder name

        with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile:
            config.set('basic_config', 'save_folder', self.save_folder)
            config.write(cfgfile)  # write new save folder to config file

        self.folder_entry['state'] = 'normal'  # make the folder field writable
        self.folder_entry.delete(0, END)
        self.folder_entry.insert(0, self.save_folder)  # update folder field
        self.folder_entry['state'] = 'readonly'  # make it read-only again

        self.clear_savefolder_list()

        self.openfolderbutton['state'] = 'normal'  # we can now press the open folder and url buttons
        self.urlbutton['state'] = 'normal'  # because we have defined a save folder

    def openfolder(self):
        os.startfile(self.save_folder)  # opens the save folder

    def clear_savefolder_list(self):
        del self.filenames[:]  # clears the list of files in a folder
        self.filenames.append(next(os.walk(self.save_folder))[2])  # adds every file in folder to list

    def check_for_url(self):
        parse = urlparse(self.url_texti.lower())  # checks if url is ylilauta
        logging.debug("url started with %s" % parse.netloc)
        if (parse.netloc.startswith(self.url_1) or
                parse.netloc.startswith(self.url_2)):
            return True
        else:
            return False

    def is_image(self):
        if (self.image_url.lower().endswith(".jpg") or
                self.image_url.lower().endswith(".jpeg") or
                self.image_url.lower().endswith(".png")):  # link seems to be image
            return True
        else:
            return False

    def is_mp4(self):
        if self.image_url.lower().endswith(".mp4"):  # link ends in mp4 so its mp4
            return True
        else:
            return False

    def is_mp3(self):
        if self.image_url.lower().endswith(".mp3"):  # link ends in mp3 so its mp3
            return True
        else:
            return False

    def we_want_it_anyway(self):
        if self.c2_selection.get() == 1:  # checkbutton2 is selected so we want all files
            return True
        else:
            return False

    def getting_both(self):
        if self.r_selection.get() == 1:  # first radio button is selected so dl both
            return True
        else:
            return False

    def getting_img(self):
        if self.r_selection.get() == 2:  # second radio button is selected so dl images only
            return True
        else:
            return False

    def getting_mp4(self):
        if self.r_selection.get() == 3:  # third radio button is selected so dl mp4 only
            return True
        else:
            return False

    def getting_mp3(self):
        if self.r_selection.get() == 4:  # fourth radio button is selected so we get mp3 only
            return True
        else:
            return False

    def rename_file(self):
        get_filetype = os.path.splitext(os.path.basename(self.image_url))[1]  # get filetype
        new_file_name_start = ''

        for i in range(0, 15):
            new_file_name_start += str(random.randint(0, 9))  # create random string of numbers

        self.name_of_file = (new_file_name_start + get_filetype)  # create the whole new name

    def write_file(self):
        self.status_text.set('Downloading %s' % self.name_of_file)
        logger.info('Downloading %s' % self.name_of_file)
        self.master.update()
        self.res = requests.get(self.image_url)
        self.res.raise_for_status()
        try:
            with open(os.path.join(self.save_folder,
                                   self.name_of_file), 'wb') as self.imagefile:
                for chunk in self.res.iter_content(100000):
                    self.imagefile.write(chunk)
            self.imagewritten = True
        except IOError:
            logger.exception("Exception with file write")
            self.status_text.set('File error')
            self.master.update()



    def file_get_logic(self):
        self.clear_savefolder_list()  # need to update this list between files
        self.imagewritten = False  # need to change this here because if same thread has same pictures
        if self.c1_selection.get() == 1:  # if want new random name
                self.rename_file()
        else:
            self.name_of_file = os.path.basename(self.image_url)  # using default filename

        if self.name_of_file in self.filenames[0]:  # file exists
            if self.c2_selection.get() == 1:  # we want to overwrite
                self.write_file()
            else:
                pass

        elif self.name_of_file not in self.filenames[0]:  # file does not exist in folder
            self.write_file()  # so we take it in

        self.master.update()

    def connect_logic(self):
        try:
            self.res = requests.get(self.url_texti, headers=self.headers,
                                    timeout=(10.0, self.read_timeout))
            self.res.raise_for_status()
        except (requests.exceptions.ReadTimeout, requests.exceptions.HTTPError):
            logger.exception("Connection exception")
            self.status_text.set("Network error %s" % self.res.status_code)
            self.master.update()

    def logic(self):
        self.clear_savefolder_list()
        self.num_pics = 0  # make these 0 because we just called the function
        self.num_mp4 = 0
        self.num_mp3 = 0
        self.imagewritten = False
        self.url_texti = ''
        self.progressbar["value"] = 0
        done = False

        if self.url_text != '':
            self.url_texti = (self.url_text.get())  # if url text is not empty we will set it to variable

        if not self.url_text or self.check_for_url() is False:  # if url is wrong or empty
            self.status_text.set('URL not supported')
            logger.debug("URL is false: %s" % self.url_texti)

        while not done and self.check_for_url() is True:
            self.urlbutton['state'] = 'disabled'  # disable buttons so they cant be pressed while run
            self.selectbutton['state'] = 'disabled'  # we will enable them again in the end
            self.R1['state'] = 'disabled'
            self.R2['state'] = 'disabled'
            self.R3['state'] = 'disabled'
            self.R4['state'] = 'disabled'
            self.C1['state'] = 'disabled'
            self.C2['state'] = 'disabled'
            self.url_entry['state'] = 'readonly'

            self.status_text.set(("Getting from %s" % self.url_texti))
            self.progressbar['value'] = 0
            self.master.update()

            self.connect_logic()

            soup = bs4.BeautifulSoup(self.res.text, 'html.parser')  # create soup
            total_stuff = 0
            html_tag1 = config.get('basic_config', 'html_tag1')  # we will fetch from these tags
            html_tag2 = config.get('basic_config', 'html_tag2')

            list_of_links = []

            for imglink in soup.select(html_tag1):  # grab items from tags and put them to list
                if imglink.get('href') not in list_of_links:
                    list_of_links.append(str(imglink.get('href')))

            for imglink in soup.select(html_tag2):
                if imglink.get('href') not in list_of_links:
                    list_of_links.append(str(imglink.get('href')))

            try:
                list_of_links = [x for x in list_of_links if x != "None"]  # clear "none"s from list

            except ValueError:  # there is no "none" in list
                pass

            total_stuff = len(list_of_links)  # variable helps with progressbar
            logger.debug("total stuff is: %s" % total_stuff)

            for link in list_of_links:  # iterate through list of links
                link = 'http:' + link  # make item a valid link
                self.image_url = link  # file get logic still uses global variable lol
                if (link.lower().endswith('.jpg') or
                    link.lower().endswith('png') or
                        link.lower().endswith('jpeg')):  # we have an image
                    if self.getting_both() or self.getting_img():  # we want an image
                        self.file_get_logic()  # we get an image
                        if self.imagewritten:  # logic is complete and image is written
                            self.num_pics += 1
                if link.lower().endswith('.mp4'):  # same as above but with mp4
                    if self.getting_both() or self.getting_mp4():
                        self.file_get_logic()
                        if self.imagewritten:
                            self.num_mp4 += 1
                if link.lower().endswith('.mp3'):
                    if self.getting_both() or self.getting_mp3():
                        self.file_get_logic()
                        if self.imagewritten:
                            self.num_mp3 += 1

                self.progressbar['value'] += 100 / total_stuff  # progressbar fills

            self.status_text.set('Downloaded %s images, %s mp4, %s mp3.' % (self.num_pics,
                                                                            self.num_mp4,
                                                                            self.num_mp3))
            self.urlbutton['state'] = 'normal'
            self.url_entry['state'] = 'normal'
            self.selectbutton['state'] = 'normal'
            self.R1['state'] = 'normal'
            self.R2['state'] = 'normal'
            self.R3['state'] = 'normal'
            self.R4['state'] = 'normal'
            self.C1['state'] = 'normal'
            self.C2['state'] = 'normal'  # we have enabled all buttons to be used again
            logger.info("Done.")

            break

        logging.shutdown()
예제 #13
0
파일: main.py 프로젝트: kr1/roqba
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((host, port))
        self.grid()
        self.columnconfigure(0, minsize=100)
        self.columnconfigure(1, minsize=200)
        self.columnconfigure(2, minsize=200)
        self.columnconfigure(3, minsize=150)
        self.columnconfigure(4, minsize=150)
        self.columnconfigure(5, minsize=150)
        self.columnconfigure(6, minsize=150)
        self.create_widgets()
        self.settables = self.assemble_settables()
        self.gui_logger = logging.getLogger('gui')
        self.request_update()

    def create_widgets(self):
        self.create_monitor()
        self.create_check_buttons()
        self.create_ranges()
        self.create_scales()
        self.create_radio_buttons()
        self.create_voices()
        self.quitButton = Button(self, text='Quit', command=self.quit)
        self.quitButton.grid(columnspan=7, sticky=E + W)

    def assemble_settables(self):
        settables = self.winfo_children()
        for w in settables:
            settables += w.winfo_children()
        return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']]

    def create_radio_buttons(self):
        # Scale related
        entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR',
                   'GREEK_CHROMATIC', 'GREEK_ENHARMONIC']
        self.scale = StringVar()
        self.scale.set('DIATONIC')
        self.rb_frame = Frame(self)
        for e in entries:
            rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W,
                             command=self.send_scale, variable=self.scale)
            rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W)
        self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3)

    def create_monitor(self):
        self.monitor_frame = LabelFrame(self, text="Monitor and Transport")
        this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL,
                           from_=1, to=16, resolution=1)
        this_cycle.disable, this_cycle.enable = (None, None)
        this_cycle.ref = 'cycle_pos'
        this_cycle.grid(column=0, row=0, sticky=E + W)
        self.updateButton = Button(self.monitor_frame,
                                   text='Reload all Settings',
                                   command=self.request_update)
        self.updateButton.grid(row=1, sticky=E + W)
        self.ForceCaesuraButton = Button(self.monitor_frame,
                                         text='Force Caesura',
                                         command=self.force_caesura)
        self.ForceCaesuraButton.grid(row=2, sticky=E + W)
        self.saveBehaviourButton = Button(self.monitor_frame,
                                          text='Save current behaviour',
                                          command=self.request_saving_behaviour)
        self.saveBehaviourButton.grid(row=3, sticky=E + W)
        self.saveBehaviourNameEntry = Entry(self.monitor_frame)
        self.saveBehaviourNameEntry.grid(row=4, sticky=E + W)
        self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour)
        self.selected_behaviour = StringVar()
        self.selected_behaviour.trace('w', self.new_behaviour_chosen)
        self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
                                              self.selected_behaviour, None,)
        self.savedBehavioursMenu.grid(row=5, sticky=E + W)
        self.monitor_frame.grid(column=0, row=10, sticky=E + W)

    def request_update(self):
        self.send({'sys': 'update'})

    def request_saving_behaviour(self, event=None):
        """callback for save behaviour button and textentry"""
        if event and event.widget == self.saveBehaviourNameEntry:
            if event.keysym == 'Return':
                name = self.saveBehaviourNameEntry.get()
                self.saveBehaviourNameEntry.delete(0, len(name))
            else:
                return
        else:  # button was pressed
            name = self.saveBehaviourNameEntry.get()
        if name:
            self.send({'sys': ['save_behaviour', name]})

    def force_caesura(self):
        self.send({'force_caesura': True})

    def create_voices(self):
        voice_ids = ['1', '2', '3', '4']
        SCALES = OrderedDict([
                  ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}),
                  ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}),
                  ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}),
                  ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}),
                  ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01})
                ])

        for vid in voice_ids:
            counter = 0
            for sca in SCALES:
                name = 'voice_' + vid + '_' + sca
                setattr(self, 'min_' + name, SCALES[sca]['min'])
                setattr(self, 'max_' + name, SCALES[sca]['max'])
                this_sca = Scale(self, label=sca, orient=HORIZONTAL,
                                 from_=getattr(self, 'min_' + name),
                                 to=getattr(self, 'max_' + name),
                                 resolution=SCALES[sca]['res'])
                this_sca.enable = ('enable' in list(SCALES[sca].keys()) and
                                   SCALES[sca]['enable'] or None)
                this_sca.disable = ('disable' in list(SCALES[sca].keys()) and
                                    SCALES[sca]['disable'] or None)
                this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W)
                this_sca.bind("<ButtonRelease>", self.scale_handler)
                this_sca.ref = name
                counter += 1
        CHECK_BUTTONS = OrderedDict(
                 [('mute', False),
                  ('automate_binaural_diffs', True),
                  ('automate_note_duration_prop', True),
                  ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}),
                  ('automate_pan', True),
                  ('automate_wavetables', True)])
        for vid in voice_ids:
            counter = 0
            cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid))
            setattr(self, 'voice_' + vid + '_cb_frame', cb_frame)
            for cb in CHECK_BUTTONS:
                options = CHECK_BUTTONS[cb]
                name = 'voice_' + vid + '_' + cb
                if isinstance(options, dict) and 'label' in list(options.keys()):
                    label = options['label']
                else:
                    label = cb[9:] if cb[:9] == 'automate_' else cb
                setattr(self, name, IntVar(
                    value=type(options) == dict and options['val'] or options))
                self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name))
                self.this_cb.bind('<Button-1>', self.check_boxes_handler)
                self.this_cb.disable = None
                self.this_cb.grid(sticky=W, column=0, row=counter)
                self.this_cb.ref = name
                counter += 1
            # add trigger wavetable-button
            trigWavetableButton = Button(cb_frame, text='Next Wavetable')
            trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler)
            trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable"
            trigWavetableButton.grid(row=counter)
            cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8)
        for vid in voice_ids:
            generation_types = ["random", "random_harmonic", "harmonic"]
            partial_pools = ["even", "odd", "all"]
            prefix = 'voice_' + vid + '_'
            types_name = prefix + 'wavetable_generation_type'
            pools_name = prefix + 'partial_pool'
            setattr(self, types_name, StringVar())
            getattr(self, types_name).set("random")
            setattr(self, pools_name, StringVar())
            getattr(self, pools_name).set("all")
            target_frame = getattr(self, 'voice_' + vid + '_cb_frame')
            gen_typ_frame = LabelFrame(target_frame, text="type")
            gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W)
            for gen_t in generation_types:
                gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W,
                                          variable=getattr(self, types_name))
                gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler)
                gen_t_entry.ref = types_name
                gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W)
            pp_frame = LabelFrame(target_frame, text="harmonics")
            for pp in partial_pools:
                pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W,
                                       variable=getattr(self, pools_name))
                pp_entry.bind('<ButtonRelease-1>', self.wt_handler)
                pp_entry.ref = pools_name
                pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL,
                                      from_=1, to=24, resolution=1)
            this_num_partials.ref = prefix + 'num_partials'
            this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials.bind("<ButtonRelease>", self.scale_handler)
            pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)

    def wt_handler(self, event):
        print(event.widget.tk)
        ref = event.widget.ref
        self.send({ref: getattr(self, ref).get()})

    def create_check_buttons(self):
        self.cb_frame = LabelFrame(self, text="Global Settings")
        for cb in CHECK_BUTTONS:
            label = cb
            target_parent = self.cb_frame
            if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()):
                target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame'])
            setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and
                                     CHECK_BUTTONS[cb]['val'] or
                                     CHECK_BUTTONS[cb]))
            self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb))
            self.this_cb.bind('<Button-1>', self.check_boxes_handler)
            self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and
                                    'disable' in list(CHECK_BUTTONS[cb].keys()))
            self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children()))
            self.this_cb.ref = cb
        for but in GLOBAL_BUTTONS:
            label = but
            ele = GLOBAL_BUTTONS[but]
            this_but = Button(self.cb_frame, text=but)
            this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler']))
            this_but.ref = but
            this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children()))
        self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N)

    def new_behaviour_chosen(self, a, b, c):
        self.send({'sys': ['change_behaviour', self.selected_behaviour.get()]})

    def set_value(self, name, val):
        '''sets a widget to the specified value

        various different widget types need custom setting functionality'''

        direct = ['scale', 'wavetable_generation_type', 'partial_pool']
        if [x for x in direct if match("(voice_\d_|)" + x, name)]:
            self.gui_logger.info("setting: '{0}' to '{1}' in GUI".format(name, val))
            getattr(self, name).set(val)
            return
        if name == 'saved_behaviours' and len(val):
            self.savedBehavioursMenu.destroy()
            self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
                                                  self.selected_behaviour, *sorted(val))
            self.savedBehavioursMenu.grid(row=5, sticky=E + W)
            return
        for w in self.settables:
            typ = w.__class__.__name__
            if w.ref == name:
                # print "setting '{0}' of type: '{1}' to: {2}".format(name, typ, val)
                if typ == 'Scale':
                    w.set(val)
                elif typ == "Checkbutton":
                    w.select() if val else w.deselect()

    def check_boxes_handler(self, event):
        '''handles checkbox events.

        shows and hides gui elements according to their enable/disable fields'''
        # print event.__dict__
        # print event.widget.__dict__
        ref = event.widget.ref
        val = not getattr(self, ref).get()  # because is read before the var is changed
        self.send({ref: val})
        # print ref, val
        # handle gui elements
        # enable/disable functionality temporarily(?) commented on:
        # Wed Aug 17 09:39:54 CEST 2011
#        if event.widget.disable:
#            for w in self.children.values():
#
#                # this try clause is for debugging, remove when stable
#                try:
#                    w.ref
#                    #print w.ref
#                except:
#                    pass
#                if (w.__class__.__name__ == 'Scale' and
#                    (w.disable or w.enable)):
#                    if w.disable == ref:
#                        if val:
#                            w.grid()
#                        else:
#                            w.grid_remove()
#                    elif w.enable == ref:
#                        if val:
#                            w.grid_remove()
#                        else:
#                            w.grid()
#                    #print w.disable, w.enable

    def create_scales(self):
        counter = 0
        for sca in SCALES:
            label = SCALES[sca]['label'] if 'label' in list(SCALES[sca].keys()) else sca
            setattr(self, 'min_' + sca, SCALES[sca]['min'])
            setattr(self, 'max_' + sca, SCALES[sca]['max'])
            self.this_scale = Scale(self, label=label, orient=HORIZONTAL,
                                    from_=getattr(self, 'min_' + sca),
                                    to=getattr(self, 'max_' + sca),
                                    resolution=SCALES[sca]['res'])
            self.this_scale.set(SCALES[sca]['start'])
            self.this_scale.enable = ('enable' in list(SCALES[sca].keys()) and
                                      SCALES[sca]['enable'] or None)
            self.this_scale.disable = ('disable' in list(SCALES[sca].keys()) and
                                       SCALES[sca]['disable'] or None)
            if 'pos' in list(SCALES[sca].keys()):
                pos = SCALES[sca]['pos']
                col = pos['c']
                row = pos['r']
            else:
                row = counter
                col = 1
                counter += 1
            self.this_scale.grid(column=col, row=row, sticky=E + W)
            self.this_scale.ref = sca
            self.this_scale.bind("<ButtonRelease>", self.scale_handler)

    def scale_handler(self, event):
        self.send({event.widget.ref: event.widget.get()})
        self.gui_logger.info("handling scale: {0}, with new value: {1}".format(
                  event.widget.ref, event.widget.get()))

    def trigger_waveform_handler(self, event):
        self.send({event.widget.ref: True})
        # print event.widget.ref, "- triggering wavetable"

    def send_scale(self):
        do = {'scale': self.scale.get()}
        self.send(do)

    def send(self, msg):
        self.gui_logger.info("sending: {0}".format(msg))
        self.send_sock.sendto(json.dumps(msg), (remote_host, send_port))

    def create_ranges(self):
        counter = 0
        for ran in RANGES:
            setattr(self, 'min_' + ran, RANGES[ran]['min'])
            setattr(self, 'max_' + ran, RANGES[ran]['max'])
            self.this_min_scale = Scale(self, label='min ' + ran, orient=HORIZONTAL,
                                        from_=getattr(self, 'min_' + ran),
                                        to=getattr(self, 'max_' + ran),
                                        resolution=RANGES[ran]['res'])
            self.this_max_scale = Scale(self, label='max ' + ran, orient=HORIZONTAL,
                                        from_=getattr(self, 'min_' + ran),
                                        to=getattr(self, 'max_' + ran),
                                        resolution=RANGES[ran]['res'])
            self.this_min_scale.set(RANGES[ran]['min_start'])
            self.this_max_scale.set(RANGES[ran]['max_start'])
            self.this_min_scale.enable = ('enable' in list(RANGES[ran].keys()) and
                                          RANGES[ran]['enable'] or None)
            self.this_min_scale.disable = ('disable' in list(RANGES[ran].keys()) and
                                           RANGES[ran]['disable'] or None)
            self.this_max_scale.enable = ('enable' in list(RANGES[ran].keys()) and
                                          RANGES[ran]['enable'] or None)
            self.this_max_scale.disable = ('disable' in list(RANGES[ran].keys()) and
                                           RANGES[ran]['disable'] or None)
            self.this_min_scale.grid(column=2, row=counter, sticky=E + W)
            self.this_max_scale.grid(column=2, row=counter + 1, sticky=E + W)
            self.this_min_scale.ref = 'min_' + ran
            self.this_max_scale.ref = 'max_' + ran
            self.this_min_scale.bind("<ButtonRelease>", self.scale_handler)
            self.this_max_scale.bind("<ButtonRelease>", self.scale_handler)
            counter += 2

    def socket_read_handler(self, file, mask):
        data_object = json.loads(file.recv(1024))
        do = list(data_object.items())[0]
        self.set_value(do[0], do[1])
예제 #14
0
파일: main.py 프로젝트: kr1/roqba
    def create_voices(self):
        voice_ids = ['1', '2', '3', '4']
        SCALES = OrderedDict([
                  ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}),
                  ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}),
                  ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}),
                  ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}),
                  ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01})
                ])

        for vid in voice_ids:
            counter = 0
            for sca in SCALES:
                name = 'voice_' + vid + '_' + sca
                setattr(self, 'min_' + name, SCALES[sca]['min'])
                setattr(self, 'max_' + name, SCALES[sca]['max'])
                this_sca = Scale(self, label=sca, orient=HORIZONTAL,
                                 from_=getattr(self, 'min_' + name),
                                 to=getattr(self, 'max_' + name),
                                 resolution=SCALES[sca]['res'])
                this_sca.enable = ('enable' in list(SCALES[sca].keys()) and
                                   SCALES[sca]['enable'] or None)
                this_sca.disable = ('disable' in list(SCALES[sca].keys()) and
                                    SCALES[sca]['disable'] or None)
                this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W)
                this_sca.bind("<ButtonRelease>", self.scale_handler)
                this_sca.ref = name
                counter += 1
        CHECK_BUTTONS = OrderedDict(
                 [('mute', False),
                  ('automate_binaural_diffs', True),
                  ('automate_note_duration_prop', True),
                  ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}),
                  ('automate_pan', True),
                  ('automate_wavetables', True)])
        for vid in voice_ids:
            counter = 0
            cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid))
            setattr(self, 'voice_' + vid + '_cb_frame', cb_frame)
            for cb in CHECK_BUTTONS:
                options = CHECK_BUTTONS[cb]
                name = 'voice_' + vid + '_' + cb
                if isinstance(options, dict) and 'label' in list(options.keys()):
                    label = options['label']
                else:
                    label = cb[9:] if cb[:9] == 'automate_' else cb
                setattr(self, name, IntVar(
                    value=type(options) == dict and options['val'] or options))
                self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name))
                self.this_cb.bind('<Button-1>', self.check_boxes_handler)
                self.this_cb.disable = None
                self.this_cb.grid(sticky=W, column=0, row=counter)
                self.this_cb.ref = name
                counter += 1
            # add trigger wavetable-button
            trigWavetableButton = Button(cb_frame, text='Next Wavetable')
            trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler)
            trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable"
            trigWavetableButton.grid(row=counter)
            cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8)
        for vid in voice_ids:
            generation_types = ["random", "random_harmonic", "harmonic"]
            partial_pools = ["even", "odd", "all"]
            prefix = 'voice_' + vid + '_'
            types_name = prefix + 'wavetable_generation_type'
            pools_name = prefix + 'partial_pool'
            setattr(self, types_name, StringVar())
            getattr(self, types_name).set("random")
            setattr(self, pools_name, StringVar())
            getattr(self, pools_name).set("all")
            target_frame = getattr(self, 'voice_' + vid + '_cb_frame')
            gen_typ_frame = LabelFrame(target_frame, text="type")
            gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W)
            for gen_t in generation_types:
                gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W,
                                          variable=getattr(self, types_name))
                gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler)
                gen_t_entry.ref = types_name
                gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W)
            pp_frame = LabelFrame(target_frame, text="harmonics")
            for pp in partial_pools:
                pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W,
                                       variable=getattr(self, pools_name))
                pp_entry.bind('<ButtonRelease-1>', self.wt_handler)
                pp_entry.ref = pools_name
                pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL,
                                      from_=1, to=24, resolution=1)
            this_num_partials.ref = prefix + 'num_partials'
            this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W)
            this_num_partials.bind("<ButtonRelease>", self.scale_handler)
            pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)
예제 #15
0
    def initUI(self):
        self.home_dir = os.getcwd()
        self.master.title("Veraxx SOFASTe PDAL Manager")

        # Menu Bar
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # File Menu
        file = Menu(menu, tearoff=0)
        file.add_command(label="Open PDAL", command=self.open_pdal)
        # add File Menu to Menu Bar
        menu.add_cascade(label="File", menu=file)

        # Actions Menu
        edit = Menu(menu, tearoff=0)
        edit.add_command(label="Scan for PDFs", command=self.pdfs_exist)
        edit.add_command(label="Remove .bak files", command=self.remove_bak)
        edit.add_command(label="Scan all for superseded", command=self.find_superseded)
        edit.add_command(label="Scan folder for superseded", command=self.find_superseded_in_folder)
        edit.add_command(label="Scan CAE filenames", command=self.CAE_filenames_valid)
        edit.add_command(label="Find \"forgot to introduce\"", command=self.find_files_not_introduced)
        # Add Validate Menu to Menu Bar
        menu.add_cascade(label="Actions", menu=edit)

        # Help Menu
        helpmenu = Menu(menu, tearoff=0)
        helpmenu.add_command(label="How to", command=self.howto_popup)
        menu.add_cascade(label="Help",menu=helpmenu)

        # Style and padding
        Style().configure("TButton", padding=(3, 5, 3, 5), font='serif 10')
        self.columnconfigure(0, pad=3) 
        self.rowconfigure(0, pad=3)

        # Widget variables
        # Full path to PDAL
        self.pdal_dir = StringVar()
               
        # Name of PDAL TLD
        self.pdal_name = StringVar()
        self.pdal_name.set("No PDAL selected")

        self.load_persistent()

        # Listbox for drawing filenames
        self.lstbox_lbl = StringVar()
        self.lstbox_lbl.set("Files:")
        self.lstbox_export_fn = "export.txt"

        # Full path to cable CSV file
        self.cable_csv_path = StringVar()
        self.cable_csv_path.set("No CSV file selected")
        # Cable assy dwg number
        self.cable_assy_num = StringVar()
        self.cable_assy_num.set("No cable labels")

        # Configure the main widget group
        grp_main = LabelFrame(self.master, text="PDAL")
        grp_main.grid(row=0, column=0)
        grp_main.config(padx=50, pady=20)

        # PDAL directory
        label_pdal_name = Label(grp_main, textvariable = self.pdal_name, width=40)
        label_pdal_name.grid(row=0, column=1)
        
        # Listbox
        lstbx_files_lbl = Label(grp_main, textvariable = self.lstbox_lbl)
        lstbx_files_lbl.grid(row=0, column=2)
        self.lstbx_files = Listbox(grp_main, selectmode="extended", width=80)
        self.lstbx_files.grid(row=1, column=2)
        btn_export_lstbx = Button(grp_main, text="Export Listbox", command=self.export_listbox)
        btn_export_lstbx.grid(row=2, column=2)

        # Configure the cable labels widget group
        grp_cbllbl = LabelFrame(self.master, text="Cable Labels")
        grp_cbllbl.grid(row=1, column=0)
        grp_cbllbl.config(padx=50, pady=20)
        
        # Cable label file path
        cable_label_file = Label(grp_cbllbl, textvariable = self.cable_csv_path, width=40)
        cable_label_file.grid(row=0, column=0)
        btn_open_cable_csv = Button(grp_cbllbl, text="Open cable label CSV", command=self.open_cable_csv)
        btn_open_cable_csv.grid(row=1, column=0)

        # Cable Label Listbox
        lstbx_cables_lbl = Label(grp_cbllbl, textvariable = self.cable_assy_num)
        lstbx_cables_lbl.grid(row=0, column=1)
        self.lstbx_cables = Listbox(grp_cbllbl, selectmode="extended", width=80)
        self.lstbx_cables.grid(row=1, column=1)
        
        btn_print_labels = Button(grp_cbllbl, text="Print labels", command=self.print_labels)
        btn_print_labels.grid(row=2, column=1)

        btn_quit = Button(self.master, text="Quit", command=self.master.destroy)
        btn_quit.grid(row=3, column=0)
예제 #16
0
def loadMCSettings():
    global gui, TListGui, HListGui, MCparamGui, xaxisStr, xAxisGui, modelGui, modelStr, algorithmGui, algoStr, corrGui, spinFrameGui, coreGui
    SettingFrame = LabelFrame(gui, text='Other settings')
    SettingFrame.grid(row=3, column=0, sticky=(W, E))

    temp_base = Frame(SettingFrame)
    temp_base.grid(row=0, column=0)
    TListGui = toolbox.NoteFrm(
        temp_base,
        init_notes=['T start:', 'T end', 'total points:'],
        init_data=[0.9, 1.2, 8],
        row=True,
        entryWidth=6)

    field_base = Frame(SettingFrame)
    field_base.grid(row=1, column=0)
    HListGui = toolbox.NoteFrm(
        field_base,
        init_notes=['H start:', 'H end', 'total points:'],
        init_data=[0, 0.1, 1],
        row=True,
        entryWidth=6)

    MCparam_base = Frame(SettingFrame)
    MCparam_base.grid(row=2, column=0, sticky='W')
    MCparamGui = toolbox.NoteFrm(MCparam_base,
                                 init_notes=['nthermal:', 'nsweep:', 'tau:'],
                                 init_data=[40000, 80000, 1],
                                 row=True)

    model_base = Frame(SettingFrame)
    model_base.grid(row=3, column=0, sticky='W')

    label0 = Label(model_base, text='xAxis:')
    label0.grid(row=0, column=0)
    xaxisStr = StringVar()
    xAxisGui = Spinbox(model_base,
                       from_=1,
                       to=2,
                       values=['T', 'H'],
                       textvariable=xaxisStr,
                       width=2)
    xAxisGui.grid(row=0, column=1)

    label1 = Label(model_base, text='Model:')
    label1.grid(row=0, column=2)
    modelStr = StringVar()
    modelGui = Spinbox(model_base,
                       from_=1,
                       to=3,
                       values=['Ising', 'XY', 'Heisenberg'],
                       textvariable=modelStr,
                       width=6)
    modelGui.grid(row=0, column=3)
    modelStr.set('XY')

    label2 = Label(model_base, text='Algorithm:')
    label2.grid(row=0, column=4)
    algoStr = StringVar()
    algorithmGui = Spinbox(model_base,
                           from_=1,
                           to=3,
                           values=['Wolff', 'Metropolis', 'Swedsen-Wang'],
                           textvariable=algoStr,
                           width=6)
    algorithmGui.grid(row=0, column=5)

    corr_base = Frame(SettingFrame)
    corr_base.grid(row=4, column=0, sticky='W')
    corrGui = toolbox.NoteFrm(
        corr_base,
        init_notes=['Mesure corr. si', 'sj', 'overLat:', '', ''],
        init_data=[0, 0, 0, 0, 0],
        entryWidth=3,
        row=True)

    lastline = Frame(SettingFrame)
    lastline.grid(row=5, column=0, sticky='W')

    spinFrame_base = Frame(lastline)
    spinFrame_base.grid(row=0, column=0, sticky='W')
    spinFrameGui = toolbox.NoteFrm(spinFrame_base,
                                   init_notes=['nFrame:'],
                                   init_data=[0],
                                   entryWidth=3)

    core_base = Frame(lastline)
    core_base.grid(row=0, column=1, sticky='W')
    coreGui = toolbox.NoteFrm(core_base,
                              init_notes=['core:'],
                              init_data=[np.max([1, int(cpu_count() / 2)])],
                              entryWidth=3)
예제 #17
0
# frame_mainContent ROW 0
frame_track = LabelFrame(frame_mainContent, text="Track")

trackFaces = tk.Button(frame_track,
                       text="Track Faces",
                       command=TrackImages,
                       font=('times', 15, ' bold '))
trackFaces.grid(row=0, column=0)

takeAttendance = tk.Button(frame_track,
                           text="Take Attendance",
                           command=takeAttendance,
                           font=('times', 15, ' bold '))
takeAttendance.grid(row=0, column=1)

frame_track.grid(row=0, ipady=10, ipadx=10)
# Center buttons in frame
frame_track.grid_rowconfigure(0, weight=1)
frame_track.grid_columnconfigure(0, weight=1)
frame_track.grid_columnconfigure(1, weight=1)

# frame_mainContent ROW 1
frame_addUser = LabelFrame(frame_mainContent, text="Add User")

frame_enterData = Frame(frame_addUser)
# frame_enterData ROW 0
lbl_enterID = tk.Label(frame_enterData,
                       text="Enter ID",
                       font=('times', 15, ' bold '))
lbl_enterID.grid(row=0, column=0, sticky="W")
txt_enterID = tk.Entry(frame_enterData, font=('times', 15, ' bold '))
예제 #18
0
def Tempmal():
    base_url = 'https://www.mailinator.com/v3/index.jsp?zone=public&query='
    base_email = '@mailinator.com'

    root = Tk()
    # Stop early showing of GUI until messagebox clicked.
    root.withdraw()
    messagebox.showinfo(
        'Mailinator GUI', 'To create a quick disposable, anonymous'
        ' email address,\nJust type some text (to create a user '
        'name) into the input box,\nthen click on the Create Email '
        'button\n\nIf you type nothing in, a random name'
        ' will be generated for you.')

    # Create GUI frame.
    root = Tk()
    root.title('Temp_Mail')
    root.config(background='black')

    root.geometry('300x150')
    main_frame = LabelFrame(root)
    main_frame.grid(padx=70, pady=20)

    def clk_but():
        """Create Email button was clicked"""
        # Get content of entry box.
        e_name = entry_box.get()

        if not e_name:
            # If no username entered, create random one.
            allchar = string.ascii_lowercase + string.digits
            e_name = ''.join(choice(allchar) for x in range(randint(6, 8)))
        # Construct email address.
        email_address = e_name + base_email
        messagebox.showinfo(
            'Info', 'your new email address is ' + str(email_address) + '\n\n'
            'The address has been copied to your clipboard.\n'
            'Click OK to go to your inbox')
        # Copy email address to clipboard.
        pyperclip.copy(email_address)
        # Open inbox in browser.
        webbrowser.open(base_url + e_name)

    def about_menu():
        """About program."""
        messagebox.showinfo('About', 'Tempmail By Dev Patel.\n'
                            'Updated 24 Dec 2020.')

    def visit_blog():
        """Visit my blog."""
        webbrowser.open('https://www.linkedin.com/in/dev-patel-a483a61aa/')

    # Create entry box.
    entry_box = Entry(main_frame, bd=3, bg='slategray1')
    entry_box.grid(padx=5, pady=5)

    # Create Email button.
    create_mail_btn = Button(main_frame,
                             fg='white',
                             bg='black',
                             text='Create Email',
                             command=clk_but)
    create_mail_btn.grid(pady=15, padx=15)

    # Standard dropdown menu.
    menu_bar = Menu(root)
    file_menu = Menu(menu_bar, tearoff=0)
    menu_bar.add_cascade(label='Menu', menu=file_menu)
    file_menu.add_command(label='Visit Blog', command=visit_blog)
    file_menu.add_separator()
    file_menu.add_command(label='About', command=about_menu)
    file_menu.add_command(label='Exit', command=root.destroy)
    root.config(menu=menu_bar)
예제 #19
0
titleframe.configure(background=bg_colour)
titleframe.grid(row=0, column=0)

editframeTitle = Label(root,
                       text="Manage Entries",
                       background=bg_colour,
                       pady=5)

editframe = LabelFrame(root,
                       text="Manage Entries",
                       borderwidth=1,
                       labelanchor='n',
                       labelwidget=editframeTitle,
                       font=("Myriad Pro Bold", 10))
editframe.configure(background=bg_colour)
editframe.grid(row=2, column=0, padx=40, pady=25)

roadtax_tab = ttk.Notebook(root)

bodyframe = Frame(roadtax_tab)
bodyframe.configure(background=bg_colour)
bodyframe.grid()

roadtax_tab.add(bodyframe, text="Roadtax")
roadtax_tab.enable_traversal()
roadtax_tab.grid(row=1, column=0, sticky=S)

title = Label(titleframe,
              font=("Courier", 28),
              text="Road-Tax Renewal Tracker",
              bg=bg_colour)
class App:
    def __init__(self,master):
        self.master = master
        master.title('Impedimetric analysis')
        master.geometry("500x400")
        
        # Drop down boxes
        self.options = ["CV-analysis", 
                   "EIS-analysis", 
                   "Plot imported files"]
        self.clicked = StringVar()
        self.clicked.set(self.options[0])
        
        # Make frame
        self.frame = LabelFrame(master,text="Select analysis", height=5, width=5)
        self.frame.grid(row=0,column=1)
        #_____________________________
        # Dropdown menu
        #_____________________________
        dropAnalys = OptionMenu(self.frame, self.clicked, *self.options)
        dropAnalys.grid(row=0, column=1)
        
        self.clicked.trace("w",self.change) #track if something happens to variable
        
        #_____________________________
        # Initial Entry boxes
        #_____________________________
        self.variable1 = self.entry_box('values_row_start',2,1,3)
        self.variable2 = self.entry_box('potential_column',3,1,1)
        self.variable3 = self.entry_box('current_column',4,1,3)
        self.variable4 = self.entry_box('scan_column (0 if none)',5,1,5)
        self.variable5 = self.entry_box('Scan_number',6,1,3)
        self.variable6 = self.entry_box('LinReg_start_index',7,1,15)
        self.variable7 = self.entry_box('R2_accept_value',8,1,0.90)
        self.variable8 = self.entry_box('potential_unit',9,1,"V")
        self.variable9 = self.entry_box('current_unit',10,1,"A")
        self.variable10 = self.entry_box('Number of decimals',11,1,3)
        
        #_____________________________
        # Info boxes
        #_____________________________
        self.button1 = Button(master, text = "info",command=self.info_box1).grid(row=2, column=2)
        self.button2 = Button(master, text = "info", command=self.info_box2).grid(row=3, column=2)
        self.button3 = Button(master, text = "info", command=self.info_box3).grid(row=4, column=2)
        self.button4 = Button(master, text = "info", command=self.info_box4).grid(row=5, column=2)
        self.button5 = Button(master, text = "info", command=self.info_box5).grid(row=6, column=2)
        self.button6 = Button(master, text = "info", command=self.info_box6).grid(row=7, column=2)
        self.button7 = Button(master, text = "info", command=self.info_box7).grid(row=8, column=2)
        self.button8 = Button(master, text = "info", command=self.info_box8).grid(row=9, column=2)
        self.button9 = Button(master, text = "info", command=self.info_box9).grid(row=10, column=2)
        self.button10 = Button(master, text = "info", command=self.info_box10).grid(row=11, column=2)

                
        #_____________________________
        # Run button
        #_____________________________
        self.run_button = Button(master,text="Run!",command = self.onclick)
        self.run_button.grid(row=12,column=1)
        
    #_____________________________
    # Info boxes - Text definitions
    #_____________________________ 
    def info_box1(self):
        Text = "The row for which the First value appears in the excel/csv file."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box2(self):
        if self.clicked.get() == self.options[0]:
            Text = "Check your excel/csv file and list the column number of where the Potential (V) values appear."
        elif self.clicked.get() == self.options[1]:
            Text = "Check your excel/csv file and list the column number of where the Real part of impedance values appear."
        elif self.clicked.get() == self.options[2]:
            Text = "CCheck your excel/csv file and list the column number of where the x-values appear."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box3(self):
        if self.clicked.get() == self.options[0]:
            Text = "Check your excel/csv file and list the column number of where the Current (I) values appear."
        elif self.clicked.get() == self.options[1]:
            Text = "Check your excel/csv file and list the column number of where the Imaginary part of impedance values appear."
        elif self.clicked.get() == self.options[2]:
            Text = "Check your excel/csv file and list the column number of where the y-values appear."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box4(self):
        if self.clicked.get() == self.options[0]:
            Text = "Check your excel/csv file and list the column number of where the Scan number indication appear."
        elif self.clicked.get() == self.options[1]:
            Text = "Insert value for Start interval of Real part of impedance values. NB: both Z_R_start and Z_R_end must be inserted for the interval range to be created."
        elif self.clicked.get() == self.options[2]:
            Text = "Insert value for Start interval of x-values. NB: both x_start and x_end must be inserted for the interval range to be created."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box5(self):
        if self.clicked.get() == self.options[0]:
            Text = "The Scan number you want to include for plotting."
        elif self.clicked.get() == self.options[1]:
            Text = "Insert value for End interval of Real part of impedance values. NB: both Z_R_start and Z_R_end must be inserted for the interval range to be created."
        elif self.clicked.get() == self.options[2]:
            Text = "Insert value for End interval of x-values. NB: both x_start and x_end must be inserted for the interval range to be created."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box6(self):
        if self.clicked.get() == self.options[0]:
            Text = "The number of indexes away from start and end value, in between regression is made."
        elif self.clicked.get() == self.options[1]:
            Text = "Insert value for Start interval of Imaginary part of impedance values. NB: both Z_Im_start and Z_Im_end must be inserted for the interval range to be created."
        elif self.clicked.get() == self.options[2]:
            Text = "Insert value for Start interval of y-values. NB: both y_start and y_end must be inserted for the interval range to be created."
        tk.messagebox.showinfo("Info",str(Text))
    
    def info_box7(self):
        if self.clicked.get() == self.options[0]:
            Text = "Minimum value for how good linear reression must be in order to create mandatory baselines."
        elif self.clicked.get() == self.options[1]:
            Text = "Insert value for End interval of Imaginary part of impedance values. NB: both Z_Im_start and Z_Im_end must be inserted for the interval range to be created."
        elif self.clicked.get() == self.options[2]:
            Text = "Insert value for End interval of y-values. NB: both y_start and y_end must be inserted for the interval range to be created."
        tk.messagebox.showinfo("Info",str(Text))        

    def info_box8(self):
        if self.clicked.get() == self.options[0]:
            Text = "Type the Potential unit."
        elif self.clicked.get() == self.options[1]:
            Text = "Type the Impedance unit."
        elif self.clicked.get() == self.options[2]:
            Text = "Type the x-label."
        tk.messagebox.showinfo("Info",str(Text))  
    
    def info_box9(self):
        if self.clicked.get() == self.options[0]:
            Text = "Type the Current unit."
        elif self.clicked.get() == self.options[1]:
            Text = "Type the starting index number to be used in the semicircle fit."
        elif self.clicked.get() == self.options[2]:
            Text = "Type the y-label."
        tk.messagebox.showinfo("Info",str(Text))  
    
    def info_box10(self):
        if self.clicked.get() == self.options[0]:
            Text = "Number of decimals to be displayed in output plots."
        elif self.clicked.get() == self.options[1]:
            Text = "Type the number of indexes to the left of the semicircle end that defines the final interval of the semicircle fit."
        elif self.clicked.get() == self.options[2]:
            Text = "Type the plot-title."
        tk.messagebox.showinfo("Info",str(Text))  
    #_____________________________
    # Entry boxes
    #_____________________________
    def entry_box(self,Text, row, column, default_input, width = 20):
        Text = str(Text)
        Label(self.master, text=str(Text),width = width).grid(row=row)
        E = Entry(self.master)
        E.insert(END,str(default_input))
        E.grid(row=row, column=column) 
        return E

    def change(self, *args):
        if self.clicked.get() == self.options[0]:
            self.variable1 = self.entry_box('values_row_start',2,1,3)
            self.variable2 = self.entry_box('potential_column',3,1,1)
            self.variable3 = self.entry_box('current_column',4,1,3)
            self.variable4 = self.entry_box('scan_column (0 if none)',5,1,5)
            self.variable5 = self.entry_box('Scan_number',6,1,3)
            self.variable6 = self.entry_box('LinReg_start_index',7,1,15)
            self.variable7 = self.entry_box('R2_accept_value',8,1,0.90)
            self.variable8 = self.entry_box('potential_unit',9,1,"V")
            self.variable9 = self.entry_box('current_unit',10,1,"A")
            self.variable10 = self.entry_box('Number of decimals',11,1,3)
        
         
        elif self.clicked.get() == self.options[1]:
            self.variable1 = self.entry_box('values_row_start',2,1,2)
            self.variable2 = self.entry_box('Z_R_column',3,1,3)
            self.variable3 = self.entry_box('Z_Im_column',4,1,4)
            self.variable4 = self.entry_box('Z_R_start',5,1,"")
            self.variable5 = self.entry_box('Z_R_end',6,1,"")
            self.variable6 = self.entry_box('Z_Im_start',7,1,"")
            self.variable7 = self.entry_box('Z_Im_end',8,1,"")
            self.variable8 = self.entry_box('impedance_unit',9,1,"Ω")
            self.variable9 = self.entry_box('circle_point1_index',10,1,0)
            self.variable10 = self.entry_box('circle_point2_index',11,1,0)
        

        
        elif self.clicked.get() == self.options[2]:
            self.variable1 = self.entry_box('values_row_start',2,1,2)
            self.variable2 = self.entry_box('x_column',3,1,2)
            self.variable3 = self.entry_box('y_column',4,1,5)
            self.variable4 = self.entry_box('x_start',5,1,"")
            self.variable5 = self.entry_box('x_end',6,1,"")
            self.variable6 = self.entry_box('y_start',7,1,"")
            self.variable7 = self.entry_box('y_end',8,1,"")
            self.variable8 = self.entry_box('x_label',9,1,"")
            self.variable9 = self.entry_box('y_label',10,1,"")
            self.variable10 = self.entry_box('plot_title',11,1,"")
        else:
            pass

    #_____________________________
    # Save input in entry boxes and function for run-command
    #_____________________________
    
    def onclick(self,*args): 
        self.variable1_get = self.variable1.get()
        self.variable2_get = self.variable2.get()
        self.variable3_get = self.variable3.get()
        self.variable4_get = self.variable4.get()
        self.variable5_get = self.variable5.get()
        self.variable6_get = self.variable6.get()
        self.variable7_get = self.variable7.get()
        self.variable8_get = self.variable8.get()
        self.variable9_get = self.variable9.get()
        self.variable10_get = self.variable10.get()
        values = [int(self.variable1_get),int(self.variable2_get),int(self.variable3_get),str(self.variable4_get),str(self.variable5_get),
                  str(self.variable6_get),str(self.variable7_get),str(self.variable8_get),str(self.variable9_get),str(self.variable10_get)]
        
        #option to close tkinter window
        self.close_window

        if self.clicked.get() == self.options[0]:
            Analysis_CV(values[0], values[1],values[2],values[3],values[4],values[5],values[6],values[7],values[8],values[9])
            
        elif self.clicked.get() == self.options[1]:
            Analysis_EIS(values[0], values[1],values[2],values[3],values[4],values[5],values[6],values[7],values[8],values[9])
            
        elif self.clicked.get() == self.options[2]:
            Plots_all_imported(values[0], values[1],values[2],values[3],values[4],values[5],values[6],values[7],values[8],values[9])
        else:
            pass
        
    def close_window(self): 
        self.master.destroy()
예제 #21
0
def main():
    def genpress():
        generator_output.delete(0, 'end')
        global leng
        sym = s_var.get()
        num = n_var.get()
        upp = u_var.get()
        low = l_var.get()
        new_pass = generator.genPass(leng, sym, num, upp, low)
        generator_output.insert(0, new_pass)

    def set_leng(selection):
        global leng
        leng = selection

    # Initialise root
    root = Tk()
    root.title("Password Tools")
    # root.geometry("300x450")
    titlefont = ("times", 30, "bold")
    entryfont = ("times", 25)

    # Create app title
    title_label = Label(root,
                        text="PASSWORD TOOLS",
                        font=titlefont,
                        pady="10",
                        padx="10")
    title_label.grid(row=0, column=0)

    # Create label frame for generation options
    generator_labelframe = LabelFrame(root, text="Generator")
    generator_labelframe.grid(row=1, column=0, padx=10, pady=10)
    # Creating option menu and label, with length string leng = ""
    length_label = Label(generator_labelframe, text="Password Length:")
    length_label.grid(row=0, column=0)
    leng = "0"
    leng_options = [
        "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
        "18", "19", "20"
    ]
    var1 = StringVar()
    pass_length = OptionMenu(generator_labelframe,
                             var1,
                             *leng_options,
                             command=set_leng)
    pass_length.grid(row=1, column=0)
    # Create 'Generate' button
    generator_button = Button(generator_labelframe,
                              text="Generate!",
                              command=lambda: genpress())
    generator_button.grid(row=2, column=0, rowspan="2")
    # Creating the three checkboxes
    s_var = IntVar()
    symbols_box = Checkbutton(generator_labelframe,
                              text="Symbols",
                              variable=s_var)
    symbols_box.grid(row=0, column=1)
    n_var = IntVar()
    numbers_box = Checkbutton(generator_labelframe,
                              text="Numbers",
                              variable=n_var)
    numbers_box.grid(row=1, column=1)
    u_var = IntVar()
    uppers_box = Checkbutton(generator_labelframe,
                             text="Uppercase",
                             variable=u_var)
    uppers_box.grid(row=2, column=1)
    l_var = IntVar()
    lowers_box = Checkbutton(generator_labelframe,
                             text="Lowercase",
                             variable=l_var)
    lowers_box.grid(row=3, column=1)
    # Create field for generated password
    generator_output = Entry(generator_labelframe,
                             width="27",
                             relief="ridge",
                             bg="systembuttonface",
                             font=entryfont)
    generator_output.grid(row=4, column=0, columnspan=2, padx=10, pady=10)

    # Create label frame from strength tester
    strength_labelframe = LabelFrame(root, text="Strength Tester")
    strength_labelframe.grid(row=2, column=0, padx=10, pady=10)
    # Entry for password strength checker
    strength_entry = Entry(strength_labelframe, width="25", font=entryfont)
    strength_entry.pack()
    # Label for result of the strength test
    result_label = Label(strength_labelframe,
                         text="RESULTS ARE IN: YOU ARE WEAK")
    result_label.pack()

    close_button = Button(root, text="Close", command=lambda: root.destroy())
    close_button.grid(row=3, column=0)

    root.mainloop()
예제 #22
0
    def hr_request(self):
        token = self.token
        update_frame(self.additional_fr)
        frame_hr = Frame(self.additional_fr)
        frame_hr.grid(row=0, column=0)
        label_year = Label(frame_hr, text="Year(s) (Integer)")
        label_job_title = Label(frame_hr, text="Job title")
        label_job_description = Label(frame_hr, text="Job description")

        button_submit = Button(frame_hr, text="Submit", width=10, height=1)

        requesting_department_labelframe = LabelFrame(
            frame_hr, text='Requesting Department', relief=GROOVE, bd=2)
        contract_type_labelframe = LabelFrame(frame_hr,
                                              text='Contract Type',
                                              relief=GROOVE,
                                              bd=2)
        entry_years = Entry(frame_hr)
        entry_job_title = Entry(frame_hr)
        entry_job_description = Entry(frame_hr)
        entry_job_description.grid(ipady=50, ipadx=35)

        Radiobutton(contract_type_labelframe,
                    variable=self.contract_type,
                    value=True,
                    text="Full Time").grid(row=1, column=0, pady=20)
        Radiobutton(contract_type_labelframe,
                    variable=self.contract_type,
                    value=False,
                    text="Part Time").grid(row=1, column=1, pady=10)

        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="administration",
                    text="Administration").grid(row=2, column=0, pady=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="services",
                    text="Services").grid(row=2, column=1, pady=20, padx=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="production",
                    text="Production").grid(row=3, column=0, pady=10, padx=20)
        Radiobutton(requesting_department_labelframe,
                    variable=self.requesting_department,
                    value="financial",
                    text="Financial").grid(row=3, column=1, pady=10, padx=20)

        contract_type_labelframe.grid(row=1, column=2, pady=20)
        requesting_department_labelframe.grid(row=2, column=2, pady=20)
        label_year.grid(row=3, column=1, pady=20)
        entry_years.grid(row=3, column=2, pady=20)
        label_job_title.grid(row=4, column=1, pady=20)
        entry_job_title.grid(row=4, column=2, pady=20)
        label_job_description.grid(row=5, column=1, pady=20)
        entry_job_description.grid(row=5, column=2, pady=20)
        button_submit.grid(row=6, column=1, pady=20)
        label_error = Label(frame_hr,
                            text="",
                            fg="red",
                            font="Helvetica 9 bold")
        contract_type = self.contract_type
        requesting_department = self.requesting_department

        def send_form(*args):
            body = {
                "is_full_time": contract_type.get(),
                "request_department": requesting_department.get(),
                "year_experience_min": int(entry_years.get()),
                'job_title': entry_job_title.get(),
                'job_description': entry_job_description.get()
            }
            header = {'Authorization': 'Bearer {}'.format(token)}
            http_request.request("POST",
                                 "/create_staff_request/",
                                 headers=header,
                                 body=json.dumps(body))
            response = http_request.getresponse()
            if response.status > 200:
                frame_hr.config(highlightcolor="red",
                                highlightbackground="red",
                                highlightthickness=3,
                                relief=SOLID,
                                bd=0)
                label_error.config(text="Error click here to get details")
                frame_hr.after(3000, lambda: label_error.config(text=""))
                frame_hr.after(2000, lambda: frame_hr.config(relief=FLAT))
                try:
                    decoded_response = json.loads(response.read().decode())
                    self.error_response = decoded_response["error"]
                except (KeyError, json.decoder.JSONDecodeError):
                    self.status_response = "400 or 500"
                    self.error_response = "No information given by server, information were not properly given"
                label_error.bind("<Button-1>", self.display_error)
            else:
                self.display_validation()

        button_submit.bind("<Button-1>", send_form)
        # self.additional_fr.bind("<Return>", self.send_form)
        frame_hr.bind("<Return>", send_form)
        self.additional_fr.pack()
예제 #23
0
class TotalHostCalcGUI:
    def __init__(self):
        self.subnet = Subnet()

        self.total = Tk()
        self.total.wm_title('Total Host Count Calculator')

        self.count_from_cidr = LabelFrame(
            self.total, text='Total Host Count: CIDR Address')
        self.cidr_label = Label(self.count_from_cidr,
                                text='CIDR Address:',
                                width=20)
        self.cidr_entry = Entry(self.count_from_cidr, width=25)

        self.count_from_netmask = LabelFrame(self.total,
                                             text='Total Host Count: Netmask')
        self.netmask_label = Label(self.count_from_netmask,
                                   text='Netmask:',
                                   width=20)
        self.netmask_entry = Entry(self.count_from_netmask, width=25)

        self.count_from_ip_range = LabelFrame(
            self.total, text='Total Host Count: Assignable IP Range')
        self.ip_range_label = Label(self.count_from_ip_range,
                                    text='Assignable IP Range:',
                                    width=20)
        self.ip_range_entry = Entry(self.count_from_ip_range, width=25)

        self.learning_steps = LabelFrame(self.total, text='Learning Steps')

        self.calculate = Button(self.count_from_cidr,
                                text='Calculate',
                                command=lambda: self.get_count_from_cidr())
        self.calculate2 = Button(self.count_from_netmask,
                                 text='Calculate',
                                 command=lambda: self.get_count_from_netmask())
        self.calculate3 = Button(
            self.count_from_ip_range,
            text='Calculate',
            command=lambda: self.get_count_from_ip_range())

        self.count_from_cidr.grid(row=0)
        self.count_from_netmask.grid(row=1)
        self.count_from_ip_range.grid(row=2)
        self.learning_steps.grid(row=3, sticky='W')

        self.cidr_label.grid(row=0, column=0, sticky='W')
        self.cidr_entry.grid(row=0, column=1)
        self.calculate.grid(row=0, column=2)

        self.netmask_label.grid(row=0, column=0, sticky='W')
        self.netmask_entry.grid(row=0, column=1)
        self.calculate2.grid(row=0, column=2)

        self.ip_range_label.grid(row=0, column=0, sticky='W')
        self.ip_range_entry.grid(row=0, column=1)
        self.calculate3.grid(row=0, column=2)

        # self.total.mainloop()
        pass

    def get_count_from_cidr(self):
        if self.subnet.total_host_count != '':
            self.clear_and_reset()
        else:
            self.subnet.cidr_address = self.cidr_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_total_host_count_from_cidr()
                steps = self.subnet.total_host_count_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                cidr_address = Label(self.learning_steps,
                                     text='CIDR Address: {}'.format(
                                         self.subnet.cidr_address))
                step2 = Label(self.learning_steps, text='Step 2:')
                cidr = Label(self.learning_steps,
                             text='CIDR: {}'.format(steps[0]['CIDR']))
                step3 = Label(self.learning_steps, text='Step 3:')
                host = Label(self.learning_steps,
                             text='Host Bits: {}'.format(
                                 steps[1]['Host Bits']))
                step4 = Label(self.learning_steps, text='Step 4:')
                count = Label(self.learning_steps,
                              text='Total Host Count: 2{} = {}'.format(
                                  exponent(
                                      steps[1]['Host Bits'].split(' ')[-1]),
                                  self.subnet.total_host_count))

                step1.grid(row=0, column=0, sticky='W')
                cidr_address.grid(row=0, column=1, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                cidr.grid(row=1, column=1, sticky='W')
                step3.grid(row=2, column=0, sticky='W')
                host.grid(row=2, column=1, sticky='W')
                step4.grid(row=3, column=0, sticky='W')
                count.grid(row=3, column=1, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def get_count_from_netmask(self):
        if self.subnet.total_host_count != '':
            self.clear_and_reset()
        else:
            self.subnet.netmask = self.netmask_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_total_host_count_from_netmask()
                steps = self.subnet.total_host_count_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                netmask = Label(self.learning_steps,
                                text='Netmask: {}'.format(self.subnet.netmask))
                step2 = Label(self.learning_steps, text='Step 2:')
                netmask_binary = Label(self.learning_steps,
                                       text='Netmask Binary: {}'.format(
                                           steps[0]['Netmask Binary']))
                step3 = Label(self.learning_steps, text='Step 3:')
                host = Label(self.learning_steps,
                             text='Host Bits: {}'.format(
                                 steps[1]['Host Bits']))
                step4 = Label(self.learning_steps, text='Step 4:')
                count = Label(self.learning_steps,
                              text='Total Host Count: 2{} = {}'.format(
                                  exponent(str(steps[1]['Host Bits'])),
                                  self.subnet.total_host_count))

                step1.grid(row=0, column=0, sticky='W')
                netmask.grid(row=0, column=1, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                netmask_binary.grid(row=1, column=1, sticky='W')
                step3.grid(row=2, column=0, sticky='W')
                host.grid(row=2, column=1, sticky='W')
                step4.grid(row=3, column=0, sticky='W')
                count.grid(row=3, column=1, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def get_count_from_ip_range(self):
        if self.subnet.total_host_count != '':
            self.clear_and_reset()
        else:
            self.subnet.ip_range = self.ip_range_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_total_host_count_from_ip_range()
                steps = self.subnet.total_host_count_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                ip_range = Label(self.learning_steps,
                                 text='Assignable IP Range: {}'.format(
                                     self.subnet.ip_range))
                step2 = Label(self.learning_steps, text='Step 2:')
                front = Label(self.learning_steps,
                              text='Front: {}'.format(steps[0]['Front']))
                back = Label(self.learning_steps,
                             text=' Back: {}'.format(steps[0]['Back']))
                step3 = Label(self.learning_steps, text='Step 3:')
                comparison = Label(self.learning_steps,
                                   text='Comparison: {}'.format(
                                       steps[1]['Comparison']))
                step4 = Label(self.learning_steps, text='Step 4:')
                host = Label(self.learning_steps,
                             text='Host Bits: {}'.format(
                                 steps[2]['Host Bits']))
                step5 = Label(self.learning_steps, text='Step 5:')
                count = Label(self.learning_steps,
                              text='Total Host Count: 2{} = {}'.format(
                                  exponent(str(steps[2]['Host Bits'])),
                                  self.subnet.total_host_count))

                step1.grid(row=0, column=0, sticky='W')
                ip_range.grid(row=0, column=1, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                front.grid(row=1, column=1, sticky='W')
                back.grid(row=2, column=1, sticky='W')
                step3.grid(row=3, column=0, sticky='W')
                comparison.grid(row=3, column=1, sticky='W')
                step4.grid(row=4, column=0, sticky='W')
                host.grid(row=4, column=1, sticky='W')
                step5.grid(row=5, column=0, sticky='W')
                count.grid(row=5, column=1, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def clear_and_reset(self):
        self.cidr_entry.delete(0, 'end')
        self.netmask_entry.delete(0, 'end')
        self.ip_range_entry.delete(0, 'end')
        self.subnet.reset_variables()
        for child in self.learning_steps.winfo_children():
            child.destroy()

    def generate_main(self):
        self.total.mainloop()
예제 #24
0
    def task_request(self):
        token = self.token
        update_frame(self.additional_fr)
        frame_hr = Frame(self.additional_fr)
        frame_hr.grid(row=0, column=0)
        label_project_reference = Label(frame_hr, text="Project Reference")
        label_assigned_to = Label(frame_hr, text="Assigned To")
        label_description = Label(frame_hr, text="Description")

        button_submit = Button(frame_hr, text="Submit", width=10, height=1)

        requesting_priority = LabelFrame(frame_hr,
                                         text='Priority',
                                         width=75,
                                         height=40,
                                         relief=GROOVE,
                                         bd=2)

        entry_project_reference = Entry(frame_hr)
        entry_assigned_to = Entry(frame_hr)
        entry_description = Entry(frame_hr)

        Radiobutton(requesting_priority,
                    variable=self.priority,
                    value="very_high",
                    text="Very High").grid(row=2, column=0, padx=20)
        Radiobutton(requesting_priority,
                    variable=self.priority,
                    value="high",
                    text="High").grid(row=3, column=0, padx=20)
        Radiobutton(requesting_priority,
                    variable=self.priority,
                    value="medium",
                    text="Medium").grid(row=4, column=0, padx=20)

        label_project_reference.grid(row=5, column=1, pady=20)
        entry_project_reference.grid(row=5, column=2, pady=20)
        label_description.grid(row=6, column=1, pady=20)
        entry_description.grid(row=6, column=2, pady=20)
        label_assigned_to.grid(row=7, column=1, pady=20)
        entry_assigned_to.grid(row=7, column=2, pady=20)
        requesting_priority.grid(row=8, column=1, pady=20, padx=20)

        button_submit.grid(row=9, column=1, pady=20)
        label_error = Label(frame_hr,
                            text="",
                            fg="red",
                            font="Helvetica 9 bold")
        label_error.grid(row=9, column=2, pady=20)

        def send_form(*args):
            body = {
                "project_reference": entry_project_reference.get(),
                'description': entry_description.get(),
                "user_assigned": entry_assigned_to.get(),
                "priority": self.priority.get()
            }
            header = {'Authorization': 'Bearer {}'.format(token)}
            http_request.request("POST",
                                 "/create_task/",
                                 headers=header,
                                 body=json.dumps(body))
            response = http_request.getresponse()
            if response.status > 200:
                frame_hr.config(highlightcolor="red",
                                highlightbackground="red",
                                highlightthickness=3,
                                relief=SOLID,
                                bd=0)
                label_error.config(text="Error click here to get details")
                frame_hr.after(3000, lambda: label_error.config(text=""))
                frame_hr.after(2000, lambda: frame_hr.config(relief=FLAT))
                try:
                    decoded_response = json.loads(response.read().decode())
                    self.error_response = decoded_response["error"]
                except (KeyError, json.decoder.JSONDecodeError):
                    self.status_response = "400 or 500"
                    self.error_response = "No information given by server, information were not properly given"
                label_error.bind("<Button-1>", self.display_error)
            else:
                self.display_validation()

        button_submit.bind("<Button-1>", send_form)
        # self.additional_fr.bind("<Return>", self.send_form)
        frame_hr.bind("<Return>", send_form)
        self.additional_fr.pack()
예제 #25
0
class OptimizerMainWindow():
    '''
    classdocs
    '''
    
    #TODO: change that name
    def reactToClick(self, event):
        a = AddRestrictionDialog(self)

    def __init__(self, optimizer):
        
        # always have a reference to model/controller
        self.optimizer = optimizer
        
        # setup main GUI and make stretchable
        self.guiRoot = Tk()
        self.guiRoot.title("OPTIMIZR")
        self.guiRoot.columnconfigure(1, weight=1)
        self.guiRoot.rowconfigure(0, weight=1)
        
        # left (settings) and right (sequences) part
        self.frameLeft = Frame(self.guiRoot)
        self.frameLeft.grid(row=0, column=0, sticky=W+E+N+S)
        self.frameLeft.columnconfigure(0, weight=1)
        self.frameRight = Frame(self.guiRoot)
        self.frameRight.grid(row=0, column=1, sticky=W+E+N+S)
        self.frameRight.columnconfigure(0, weight=1)
        self.frameRight.rowconfigure(0, weight=1)
        self.frameRight.rowconfigure(1, weight=1)
        
        
        self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10)
        self.frameSpeciesControll.columnconfigure(1, weight=1)
        self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10)
        self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10)
        self.frameSpeciesControll.grid(row=0, column=0, sticky=W+E, padx=10, pady=10)
        self.frameOptimizationControll.grid(row=1, column=0, sticky=W+E, padx=10, pady=10)
        self.frameRestrictionControll.grid(row=2, column=0, sticky=W+E, padx=10, pady=10)
        
        # Species Controll
        Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0)
        Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0)
        
        self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly")
        self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew")
        self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly")
        self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we")        
        self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List")
        self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e")
        
        self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
        self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
        
        # Optimization Controll
        Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0)
        self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly")
        self.comboOptimizationStrategy.grid(row=0, column=1)
        self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies
        self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
        
        # Restriction Enzymes
        self.listRestriction = Listbox(self.frameRestrictionControll)
        self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W+E)
        self.frameRestrictionControll.columnconfigure(0, weight=1)
        self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ")
        self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ")
        self.buttonRestricionAdd.grid(row=1, column=1, padx=5)
        self.buttonRestricionDel.grid(row=1, column=2, padx=5)
        
        # Source Sequence Frame
        self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10)
        self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10)
        self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10)
        self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10)
        
        
        self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ")
        self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10)
        self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5)
        self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens")
        self.frameSourceSequence.columnconfigure(0, weight=1)
        self.frameSourceSequence.rowconfigure(1, weight=1)
        self.textSourceSeq.frame.columnconfigure(1, weight=1)
        self.textSourceSeq.frame.rowconfigure(0, weight=1)
        
        self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ")
        self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize)
        
        self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ")
        self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion)
        
        self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ")
        self.textResultSequence = ScrolledText(self.frameResultSequence, height=10)
        self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w")
        self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w")
        self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens")
        self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e")
        self.frameResultSequence.columnconfigure(2, weight=1)
        self.frameResultSequence.rowconfigure(1, weight=1)
        self.textResultSequence.frame.columnconfigure(1, weight=1)
        self.textResultSequence.frame.rowconfigure(0, weight=1)
        
        self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified)
        self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified)
        
        #generate color tags for textboxes
        for i in range(101):
            
            #green for normal codons
            (r,g,b) = colorsys.hsv_to_rgb(210/360, i/100, 1.0)            
            colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255))
            
            self.textSourceSeq.tag_config("normal"+str(i), background=colorHex)
            self.textResultSequence.tag_config("normal"+str(i), background=colorHex)
            
            #red for codons with restriction sites
            (r,g,b) = colorsys.hsv_to_rgb(5/360, i/100, 1.0)            
            colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255))
            
            self.textSourceSeq.tag_config("restrict"+str(i), background=colorHex)
            self.textResultSequence.tag_config("restrict"+str(i), background=colorHex)
        
        
        # Set (minimum + max) Window size 
        self.guiRoot.update()
        self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height())
        
        self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick)
        self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete)
        self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton)
        
        self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence)
        self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence)
        
        # TEST
#         self.listRestriction.insert("end", "EcoRI")
#         self.listRestriction.insert("end", "BamHI")
#         
        
        # dummy event to manually trigger update
        self.guiRoot.bind("<<Update>>", self.actionUpdate)
        
        self.actionUpdate(None)
        
        self.guiRoot.mainloop()
    
    def actionRestrictionEnzymeDelete(self, event):
        try:
            selectedEnzyme = self.listRestriction.selection_get()
            self.optimizer.restrictionEnzymeList.remove(selectedEnzyme)
            self.guiRoot.event_generate("<<Update>>")
        except tkinter.TclError :
            # no selection
            pass    
        
    def actionUpdate(self, event):
#         print("update called")

        # clear list of restriction enzymes
        self.listRestriction.delete(0, "end")        
        for r in self.optimizer.restrictionEnzymeList:
            self.listRestriction.insert("end", r)
            
        self.comboSourceSpecies.delete(0, "end")
        self.comboTargetSpecies.delete(0, "end")
        
        speciesValues = list()        
        for (taxid, name) in self.optimizer.speciesList:
            speciesValues.append(taxid + ": " + name)
            
        self.comboSourceSpecies["values"] = speciesValues
        self.comboTargetSpecies["values"] = speciesValues
        
        if self.comboSourceSpecies.get() not in speciesValues:
            self.comboSourceSpecies.set("")
        if self.comboTargetSpecies.get() not in speciesValues:
            self.comboTargetSpecies.set("")
            
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)
        
        self.optimizer.saveConfig("config.ini")
            
    def actionEditSpeciesButton(self, event):
        speciesListDialog = SpeciesListDialog(self)
        
    def actionOptimizerSettingsChanged(self, event=None):
#         print("Something happened")
        strategy = self.comboOptimizationStrategy.get()
        sourceString = self.comboSourceSpecies.get()
        targetString = self.comboTargetSpecies.get()
        
        if not (strategy and sourceString and targetString):
            return
        
        sourceTaxid = sourceString.split(":")[0]
        targetTaxid = targetString.split(":")[0]
        
        self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy)
        
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)
#         self.optimizer.testPrint()

    def actionOptimize(self, event=None):
        self.optimizer.runOptimization()
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)
        
    def actionRemoveRestricion(self, event=None):
        self.optimizer.runRestricionRemoval()
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)
        
    def actionSequenceModified(self, event=None):
        # necessary if, otherwise -> infinite loop
        if self.textSourceSeq.edit_modified():
            
            seq = self.textSourceSeq.get("1.0", "end").strip()
            seq = stripCharsNotInList(seq.upper(), ['A', 'C', 'G', 'T'])
            self.optimizer.setSourceSeq(seq)
            
            oldInsert = self.textSourceSeq.index("insert")
            self.textSourceSeq.delete("1.0", "end")
            
            sourceCodons = self.optimizer.getCodonsForPrint(True)
            if not sourceCodons:
                self.textSourceSeq.insert("end", self.optimizer.sourceSequence)
            else:
                for (co, sc, r) in sourceCodons:
                    if sc:
                        if not r:
                            self.textSourceSeq.insert("end", co, "normal"+str(int(sc*100)))
                            #print("normal"+str(int(sc*100)))
                        else:
                            self.textSourceSeq.insert("end", co, "restrict"+str(int(sc*100)))
                    else:
                        # remainder without color
                        self.textSourceSeq.insert("end", co)
                    
                
            self.textSourceSeq.mark_set("insert", oldInsert)

            # reset the modified status at the very end
            self.textSourceSeq.edit_modified(False)

        if self.textResultSequence.edit_modified():
            
            seq = self.textResultSequence.get("1.0", "end").strip()
#             self.optimizer.setOptimizedSeq(seq)
            
            oldInsert = self.textResultSequence.index("insert")
            self.textResultSequence.delete("1.0", "end")
            
            targetCodons = self.optimizer.getCodonsForPrint(False)
            if not targetCodons:
                self.textSourceSeq.insert("end", self.optimizer.optimizedSequence)
            else:
                for (co, sc, r) in targetCodons:
                    if sc:
                        if not r:
                            self.textResultSequence.insert("end", co, "normal"+str(int(sc*100)))
                            #print("normal"+str(int(sc*100)))
                        else:
                            self.textResultSequence.insert("end", co, "restrict"+str(int(sc*100)))
                    else:
                        # remainder without color
                        self.textResultSequence.insert("end", co)
                    
                
            self.textSourceSeq.mark_set("insert", oldInsert)
            
            self.textResultSequence.edit_modified(False)

    def actionLoadSequence(self, event=None):
        filename = tkinter.filedialog.askopenfilename()
        if filename:
            seq = sequenceIO.readFile(filename)
            self.textSourceSeq.delete("1.0", "end")
            self.textSourceSeq.insert("end", seq)            
            self.textSourceSeq.edit_modified(True)
            
    def actionSaveSequence(self, event=None):
        filename = tkinter.filedialog.asksaveasfilename()
        if filename:
#             print("file is " + filename)
            with open(filename, mode='w') as fd:
                fd.write(self.optimizer.optimizedSequence)
예제 #26
0
    """Makea small donation to author, you know it makes sense."""
    webbrowser.open('https:\\paypal.me/photocolourizer')


# Check all required files are in place.
check_favs_exists()
check_mp3s_folder()
check_saved_insults_exists()
check_rude_folder()
check_clean_folder()
check_logo_present()

# The Tkinter GUI.
# Create frames.
logo_frame = LabelFrame(root)
logo_frame.grid(padx=4, pady=4)

btn_frame = Frame(root)
btn_frame.grid(padx=0, pady=4, row=1, column=0)

insults_using_frame = Label(root)
insults_using_frame.grid(row=3, column=0)
w = Label(insults_using_frame,
          bg='gold',
          fg='black',
          text='     USING CLEAN INSULTS, ' + str(Glo.tim_lang) + '     ')
w.grid()

listbox_frame = LabelFrame(root)
listbox_frame.grid(padx=8, pady=8)
예제 #27
0
root.title('Check Buttons examples')

def var_states():
    """Check and show which buttons user has selected"""
    if VAR1.get() == 1 and VAR2.get() == 1:
        msg_box_txt = 'Both buttons checked'

    if VAR1.get() == 1 and VAR2.get() == 0:
        msg_box_txt = 'Python V2 checked'

    if VAR1.get() == 0 and VAR2.get() == 1:
        msg_box_txt = 'Python V3 checked'

    if VAR1.get() == 0 and VAR2.get() == 0:
        msg_box_txt = 'Nothing checked'

    messagebox.showinfo('Checkbutton', msg_box_txt)

main_frame = LabelFrame(root, text='Please select what Python you use')
main_frame.grid(padx=10, pady=10)

VAR1 = IntVar()
Checkbutton(main_frame, text='Python V2', variable=VAR1).grid(row=0, sticky=W)

VAR2 = IntVar()
Checkbutton(main_frame, text='Python V3', variable=VAR2).grid(row=1, sticky=W)
Button(main_frame, text='Show', bg='plum', command=var_states).grid  \
      (row=3, column=1, sticky=E, pady=5)

root.mainloop()
예제 #28
0
class PCRLibrarianApp(Tk):
    """
    Main window for thePCR Librarian app
    """
    def __init__(self):
        super(PCRLibrarianApp, self).__init__()

        # Screen metrics
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        # TODO Position and size main window
        self.title("PCR Librarian")

        # ttk theme
        # s = ttk.Style()
        # s.theme_use('classic')
        self.background_color = "#ffffff"
        self.highlight_color = "#e0e0e0"

        # Create window widgets
        self._create_widgets(sw, sh)

        # Size the main window according to its contents
        self.update()
        w = self.winfo_width()
        h = self.winfo_height()
        # Centered
        x = int((sw - w) / 2)
        y = int((sh - h) / 2)
        # width x height + x + y
        geo = "{0}x{1}+{2}+{3}".format(w, h, x, y)
        self.geometry(geo)
        # self.resizable(width=True, height=True)
        self.resizable(width=True, height=False)

        # Handle app exit
        self.protocol("WM_DELETE_WINDOW", self._on_close)

        # Restore last used directory
        self._set_directory(Configuration.get_last_recent())

    def _create_widgets(self, sw, sh):
        """
        Create the UI widgets
        :param sw: Screen width
        :param sh: Screen height
        :return:
        """
        MIN_WIDTH = 100

        # Create a menu bar for the current OS
        self._create_menu()

        # Control/widget experimentation
        self.config(padx=10)
        self.config(pady=10)

        # Around control map directory widgets
        self._ctrl_frame = LabelFrame(master=self,
                                      padx=10,
                                      pady=10,
                                      text="Control Map Directory")
        self._ctrl_frame.grid(row=0, column=0, sticky="ew")

        # Container for action buttons
        self._button_frame = Frame(master=self, bd=5, padx=5, pady=5)
        self._button_frame.grid(row=2, column=0, pady=5)

        self.columnconfigure(0, weight=1, minsize=MIN_WIDTH)
        self._ctrl_frame.columnconfigure(0, weight=1)

        # Control frame row tracker
        r = 0

        # Directory entry
        self._ent_directory = Entry(master=self._ctrl_frame, width=MIN_WIDTH)
        self._ent_directory.grid(row=r, column=0, sticky="ew")
        r += 1

        # Frame for directory widgets
        self._fr_dir = Frame(master=self._ctrl_frame)

        # Select a directory
        self._btn_dir_button = Button(master=self._fr_dir,
                                      text="Select Control Map Directory",
                                      command=self._on_select_directory)
        self._btn_dir_button.grid(row=0, column=0, padx=5, pady=5)

        # Recently used directories
        self._cb_recent_dirs = Combobox(master=self._fr_dir,
                                        width=50,
                                        values=Configuration.get_recent())
        self._cb_recent_dirs.grid(row=0, column=1, padx=5, pady=5)
        self._cb_recent_dirs.bind("<<ComboboxSelected>>",
                                  self._on_recent_directory)

        self._fr_dir.grid(row=r, column=0, padx=10)
        r += 1

        # Control map file listbox with scrollbar
        self._lb_frame = LabelFrame(self._ctrl_frame,
                                    text="Control Map Files",
                                    pady=5,
                                    padx=5)
        self._lb_scrollbar = Scrollbar(self._lb_frame, orient=tkinter.VERTICAL)
        self._lb_filelist = Listbox(master=self._lb_frame, width=100)
        self._lb_scrollbar.config(command=self._lb_filelist.yview)
        self._lb_scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self._lb_filelist.pack()
        self._lb_frame.grid(row=r, column=0, pady=5)
        r += 1

        # Action buttons are inside the button frame on one row

        self._btn_receive_current_button = Button(
            master=self._button_frame,
            text="Receive Current Map",
            state=tkinter.DISABLED,
            command=self._on_receive_current_map)
        self._btn_receive_current_button.grid(row=0, column=0, padx=5)

        self._btn_receive_all_button = Button(
            master=self._button_frame,
            text="Receive All Maps",
            state=tkinter.DISABLED,
            command=self._on_receive_all_maps)
        self._btn_receive_all_button.grid(row=0, column=1, padx=5)

        self._btn_send_button = Button(master=self._button_frame,
                                       text="Send Control Map Files",
                                       state=tkinter.DISABLED,
                                       command=self._on_send)
        self._btn_send_button.grid(row=0, column=2, padx=5)

        self._btn_quit_button = Button(master=self._button_frame,
                                       text="Quit",
                                       command=self._on_close)
        self._btn_quit_button.grid(row=0, column=3, padx=5)

        # MIDI in/out ports listboxes
        self._lb_midiports_frame = LabelFrame(self,
                                              text="MIDI Ports",
                                              pady=5,
                                              padx=5)

        self._lbl_inports = Label(master=self._lb_midiports_frame, text="In")
        self._lb_midiin_ports = Listbox(master=self._lb_midiports_frame,
                                        width=30,
                                        height=5,
                                        selectmode=tkinter.SINGLE,
                                        exportselection=0)
        self._lbl_inports.grid(row=0, column=0)
        self._lb_midiin_ports.grid(row=1, column=0, padx=5, pady=5)

        self._lbl_outports = Label(master=self._lb_midiports_frame, text="Out")
        self._lb_midiout_ports = Listbox(master=self._lb_midiports_frame,
                                         width=30,
                                         height=5,
                                         selectmode=tkinter.SINGLE,
                                         exportselection=0)
        self._lbl_outports.grid(row=0, column=1)
        self._lb_midiout_ports.grid(row=1, column=1, padx=5, pady=5)

        self._lb_midiports_frame.grid(row=1, column=0, pady=5)

        # Populate midin ports listbox
        self._in_ports = get_midiin_ports()
        for p in self._in_ports:
            self._lb_midiin_ports.insert(tkinter.END, p)

        # Populate midout ports listbox
        self._out_ports = get_midiout_ports()
        for p in self._out_ports:
            self._lb_midiout_ports.insert(tkinter.END, p)

        # Minimize the height of the ports listboxes
        max_height = max(len(self._in_ports), len(self._out_ports))
        self._lb_midiin_ports.config(height=max_height)
        self._lb_midiout_ports.config(height=max_height)

        # Default midi port selections
        self._lb_midiin_ports.select_set(0)
        self._lb_midiout_ports.select_set(0)

        # Status bar
        self._v_statusbar = StringVar(value="Select control map directory")
        self._lbl_statusbar = Label(master=self,
                                    textvariable=self._v_statusbar,
                                    bd=5,
                                    relief=tkinter.RIDGE,
                                    anchor=tkinter.W)
        self._lbl_statusbar.grid(row=3, column=0, pady=5, padx=5, sticky="ew")

        # Put the focus in the directory text box
        self._ent_directory.focus_set()

    def _create_menu(self):
        # will return x11 (Linux), win32 or aqua (macOS)
        gfx_platform = self.tk.call('tk', 'windowingsystem')

        # App menu bar
        self._menu_bar = Menu(self)

        if gfx_platform == "aqua":
            # macOS app menu covering things specific to macOS X
            self._appmenu = Menu(self._menu_bar, name='apple')
            self._appmenu.add_command(label='About PCR Librarian',
                                      command=self._show_about)
            self._appmenu.add_separator()
            self._menu_bar.add_cascade(menu=self._appmenu,
                                       label='PCRLibrarian')

            self.createcommand('tk::mac::ShowPreferences',
                               self._show_preferences)

            filemenu = Menu(self._menu_bar, tearoff=0)
            filemenu.add_command(label="Clear recent directories list",
                                 command=self._on_clear_recent)
            self._menu_bar.add_cascade(label="File", menu=filemenu)
        elif gfx_platform in ["win32", "x11"]:
            # Build a menu for Windows or Linux
            filemenu = Menu(self._menu_bar, tearoff=0)
            filemenu.add_command(label="Clear recent directories list",
                                 command=self._on_clear_recent)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self._on_close)
            self._menu_bar.add_cascade(label="File", menu=filemenu)

            helpmenu = Menu(self._menu_bar, tearoff=0)
            helpmenu.add_command(label="About", command=self._show_about)
            self._menu_bar.add_cascade(label="Help", menu=helpmenu)

        self.config(menu=self._menu_bar)

    def _set_statusbar(self, text):
        """
        Update the status bar
        :param text:
        :return:
        """
        self._v_statusbar.set(text)
        # Force the widget to update now
        self._lbl_statusbar.update()

    def _on_recent_directory(self, event=None):
        directory = self._cb_recent_dirs.get()
        self._set_directory(directory)

        self._set_statusbar("Ready")

    def _on_select_directory(self):
        """
        Select a directory as the source or target of control map(s)
        :return:
        """
        directory = filedialog.askdirectory(
            initialdir=os.getcwd(), title="Select source/target directory")
        self._set_directory(directory)

        self._set_statusbar("Ready")

    def _on_clear_recent(self):
        Configuration.clear_recent()
        self._cb_recent_dirs.config(values=Configuration.get_recent())

    def _set_directory(self, directory):
        if directory:
            Configuration.set_recent(directory)

            self._ent_directory.delete(0, tkinter.END)
            self._ent_directory.insert(0, directory)

            self._load_files()

            self._btn_receive_current_button["state"] = tkinter.NORMAL
            self._btn_receive_all_button["state"] = tkinter.NORMAL

            self._fill_files_listbox()
            self._cb_recent_dirs.config(values=Configuration.get_recent())

    def _on_send(self):
        """
        Send control map(s). Sends all .syx files from selected directory.
        :return:
        """
        selected_port = self._lb_midiout_ports.curselection()
        dlg = SendDlg(self,
                      title="Send Control Map Sysex Files",
                      port=selected_port[0],
                      files=self._files)

    def _on_receive_current_map(self):
        self._set_statusbar("Ready to receive current control map")
        self._on_receive_control_maps(ReceiveDlg.SINGLE)

    def _on_receive_all_maps(self):
        self._set_statusbar("Ready to receive all 15 control maps")
        self._on_receive_control_maps(ReceiveDlg.ALL)

    def _on_receive_control_maps(self, count):
        # Delete existing .syx files
        self._delete_existing_files()

        selected_port = self._lb_midiin_ports.curselection()
        # Modal dialog box for receiving sysex messages from PCR
        dlg = ReceiveDlg(self,
                         title="Receive Current Control Map",
                         port=selected_port[0],
                         dir=self._ent_directory.get(),
                         control_map=count)

        dlg.begin_modal()

        if dlg.result:
            self._set_statusbar("Current control map(s) received")
        else:
            self._set_statusbar("Canceled")
        self._load_files()
        self._fill_files_listbox()

        del dlg

    def _delete_existing_files(self):
        """
        Delete existing .syx files
        :return:
        """
        for file in self._files:
            os.remove(file)
        self._files.clear()
        self._fill_files_listbox()

    def _load_files(self):
        """
        Load all of the .syx files in the selected directory
        :return:
        """
        self._files = []
        directory = self._ent_directory.get()
        self._files.extend(
            sorted([
                os.path.join(directory, fn) for fn in os.listdir(directory)
                if fn.lower().endswith('.syx')
            ]))
        if len(self._files) >= 50:
            self._btn_send_button["state"] = tkinter.NORMAL
        else:
            self._btn_send_button["state"] = tkinter.DISABLED

    def _fill_files_listbox(self):
        """
        Load the files listbox with all of the .syx files in the selected diretory
        :return:
        """
        self._lb_filelist.delete(0, tkinter.END)
        for f in self._files:
            self._lb_filelist.insert(tkinter.END, f)

    def _on_close(self):
        """
        App is closing. Warn user if unsaved changes.
        :return:
        """
        print(self._ent_directory.get())
        # Save the directory setting?
        Configuration.set_last_recent(self._ent_directory.get())
        # Essentially, this terminates the app by destroying the main window
        self.destroy()
        return True

    def _show_about(self):
        about_text = \
            "© 2020 by Dave Hocker\n" + \
            "\n" + \
            "Source: https://github.com/dhocker/pcr_librarian\n" + \
            "License: GNU General Public License v3\n" + \
            "as published by the Free Software Foundation, Inc. "

        # Locate logo image file
        cwd = os.path.realpath(
            os.path.abspath(
                os.path.split(inspect.getfile(inspect.currentframe()))[0]))
        if os.path.exists(cwd + "/pcr_librarian.gif"):
            image_path = cwd + "/pcr_librarian.gif"
        elif os.path.exists(cwd + "/resources/pcr_librarian.gif"):
            image_path = cwd + "/resources/pcr_librarian.gif"
        else:
            image_path = "pcr_librarian.gif"

        # This is a modal message box
        mb = TextMessageBox(self,
                            title="About PCR Librarian",
                            text=about_text,
                            heading="PCR Librarian {}".format(app_version()),
                            image=image_path,
                            width=150,
                            height=110,
                            orient=tkinter.HORIZONTAL)
        mb.show()
        self.wait_window(window=mb)

    def _show_preferences(self):
        tkinter.messagebox.showinfo("Preferences for PCR Librarian",
                                    "None currently defined")
예제 #29
0
class IPRangeCalcGUI:
    def __init__(self):
        self.subnet = Subnet()

        self.range = Tk()
        self.range.wm_title('Assignable IP Range Calculator')

        self.ip_range_from_cidr = LabelFrame(self.range, text='Assignable IP Range: CIDR Address')
        self.cidr_label = Label(self.ip_range_from_cidr, text='CIDR Address:', width=25)
        self.cidr_entry = Entry(self.ip_range_from_cidr, width=25)

        self.ip_range_from_network_broadcast = LabelFrame(self.range, text='Assignable IP Range: Network '
                                                                           'Address, Broadcast Address')
        self.network = Label(self.ip_range_from_network_broadcast, text='Network Address:', width=25)
        self.broadcast = Label(self.ip_range_from_network_broadcast, text='Broadcast Address:', width=25)
        self.network_entry = Entry(self.ip_range_from_network_broadcast, width=25)
        self.broadcast_entry = Entry(self.ip_range_from_network_broadcast, width=25)

        self.learning_steps = LabelFrame(self.range, text='Learning Steps')

        self.calculate = Button(self.ip_range_from_cidr, text='Calculate',
                                command=lambda: self.get_ip_range_from_cidr())
        self.calculate2 = Button(self.ip_range_from_network_broadcast, text='Calculate',
                                 command=lambda: self.get_ip_range_from_network_broadcast())

        self.ip_range_from_cidr.grid(row=0)
        self.ip_range_from_network_broadcast.grid(row=1)
        self.learning_steps.grid(row=2, sticky='W')

        self.cidr_label.grid(row=0, column=0, sticky='W')
        self.cidr_entry.grid(row=0, column=1)
        self.calculate.grid(row=0, column=2)

        self.network.grid(row=0, column=0, sticky='W')
        self.broadcast.grid(row=0, column=1, sticky='W')
        self.network_entry.grid(row=1, column=0)
        self.broadcast_entry.grid(row=1, column=1)
        self.calculate2.grid(row=1, column=2)

        # self.broadcast.mainloop()

    def get_ip_range_from_cidr(self):
        if self.subnet.ip_range != '':
            self.clear_and_reset()
        else:
            self.subnet.cidr_address = self.cidr_entry.get()

            if self.subnet.verify_variables():
                self.subnet.calculate_ip_range_from_cidr()
                steps = self.subnet.ip_range_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                cidr_address = Label(self.learning_steps, text='CIDR Address: {}'.format(self.subnet.cidr_address))
                step2 = Label(self.learning_steps, text='Step 2:')
                front = Label(self.learning_steps, text='Front: {}'.format(steps[0]['Front']))
                step3 = Label(self.learning_steps, text='Step 3:')
                cidr = Label(self.learning_steps, text='CIDR: {}'.format(steps[1]['CIDR']))
                host = Label(self.learning_steps, text='Host Bits: 32 - {} = {}'.format(steps[1]['CIDR'],
                                                                                        (32 - int(steps[1]['CIDR']))))
                step4 = Label(self.learning_steps, text='Step 4:')
                net_binary = Label(self.learning_steps, text='Network Binary: {}'.format(steps[1]['Network Binary']))
                step5 = Label(self.learning_steps, text='Step 5:')
                back_binary = Label(self.learning_steps,
                                    text='Back Binary (Broadcast - 1): {}'.format(steps[2]['Back Binary']))
                step6 = Label(self.learning_steps, text='Step 6:')
                ip_range = Label(self.learning_steps, text='Assignable IP Range: {}'.format(self.subnet.ip_range))

                step1.grid(row=0, column=0, sticky='W')
                cidr_address.grid(row=0, column=1, columnspan=2, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                front.grid(row=1, column=1, columnspan=2, sticky='W')
                step3.grid(row=2, column=0, sticky='W')
                cidr.grid(row=2, column=1, sticky='W')
                host.grid(row=2, column=2, sticky='W')
                step4.grid(row=3, column=0, sticky='W')
                net_binary.grid(row=3, column=1, columnspan=2, sticky='W')
                step5.grid(row=4, column=0, sticky='W')
                back_binary.grid(row=4, column=1, columnspan=2, sticky='W')
                step6.grid(row=5, column=0, sticky='W')
                ip_range.grid(row=5, column=1, columnspan=2, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def get_ip_range_from_network_broadcast(self):
        if self.subnet.ip_range != '':
            self.clear_and_reset()
        else:
            self.subnet.network_address = self.network_entry.get()
            self.subnet.broadcast_address = self.broadcast_entry.get()

            if self.subnet.network_address != '' and self.subnet.broadcast_address != '' \
                    and self.subnet.verify_variables() \
                    and (ipaddress.IPv4Address(self.subnet.network_address) + 2) \
                            < ipaddress.IPv4Address(self.subnet.broadcast_address):
                self.subnet.calculate_ip_range_from_network_broadcast()
                steps = self.subnet.ip_range_steps

                step1 = Label(self.learning_steps, text='Step 1:')
                network = Label(self.learning_steps, text='Network Address: {}'.format(self.subnet.network_address))
                broadcast = Label(self.learning_steps,
                                  text='Broadcast Address: {}'.format(self.subnet.broadcast_address))
                step2 = Label(self.learning_steps, text='Step 2:')
                front = Label(self.learning_steps, text='Front: {}'.format(steps[0]['Front']))
                step3 = Label(self.learning_steps, text='Step 3:')
                back = Label(self.learning_steps, text='Back: {}'.format(steps[1]['Back']))
                step4 = Label(self.learning_steps, text='Step 4:')
                ip_range = Label(self.learning_steps, text='Assignable IP Range: {}'.format(self.subnet.ip_range))

                step1.grid(row=0, column=0, sticky='W')
                network.grid(row=0, column=1, sticky='W')
                broadcast.grid(row=0, column=2, sticky='W')
                step2.grid(row=1, column=0, sticky='W')
                front.grid(row=1, column=1, sticky='W')
                step3.grid(row=2, column=0, sticky='W')
                back.grid(row=2, column=1, sticky='W')
                step4.grid(row=3, column=0, sticky='W')
                ip_range.grid(row=3, column=1, columnspan=2, sticky='W')
            else:
                self.clear_and_reset()
                HelpGUI()

    def clear_and_reset(self):
        self.cidr_entry.delete(0, 'end')
        self.network_entry.delete(0, 'end')
        self.broadcast_entry.delete(0, 'end')
        self.subnet.reset_variables()
        for child in self.learning_steps.winfo_children():
            child.destroy()

    def generate_main(self):
        self.range.mainloop()
예제 #30
0
    if os.path.exists('history.txt'):
        os.remove('history.txt')

    sys_user = getpass.getuser()
    file_nme = 'C:/Users/' + str(sys_user) + '/.get_iplayer/download_history'
    if os.path.exists(file_nme):
        os.remove(file_nme)

    messagebox.showinfo(
        'Deleted!', 'Your download history has been deleted.'
        '\n\nYou happy now?')


radio_frame = LabelFrame(
    root, text='Select TV or Radio from above drop-down menu first')
radio_frame.grid(padx=10, pady=10)

# Entry box.
url_ent_box = Entry(radio_frame, bd=4, width=40)
url_ent_box.grid(sticky=W + E, padx=5, pady=5, row=0, column=1)
url_ent_box.delete(0, END)
url_ent_box.insert(0, 'Right click once to paste URL')
url_ent_box.focus()
url_ent_box.bind('<Button-3>', on_right_click)

# Download button.
dwnld_btn = Button(radio_frame,
                   bg='indianred',
                   text='Download',
                   command=dwnld_show)
dwnld_btn.grid(sticky=W + E, padx=5, pady=5, row=0, column=2)
예제 #31
0
class ffmpegGUI:
    def __init__(self):
        pass

    def run(self):
        self.root = Tk()
        self.root.title("ffmpegGUI")

        self.inputframe = LabelFrame(self.root)
        self.inputframeLabel = Label(self.inputframe)
        self.inputframe["labelwidget"] = self.inputframeLabel
        self.inputframeLabel["text"] = "Input"
        self.inputframe.grid(row=0, column=0, sticky=N + S)

        self.converterframe = LabelFrame(self.root)
        self.converterframeLabel = Label(self.converterframe)
        self.converterframe["labelwidget"] = self.converterframeLabel
        self.converterframeLabel["text"] = "Converter"
        self.converterframe.grid(row=0, column=1, sticky=N + S)

        self.outputframe = LabelFrame(self.root)
        self.outputframeLabel = Label(self.outputframe)
        self.outputframe["labelwidget"] = self.outputframeLabel
        self.outputframeLabel["text"] = "Output"
        self.outputframe.grid(row=0, column=2, sticky=N + S)

        self.build_inputframe()
        self.build_converterframe()
        self.build_outputframe()

        self.root.mainloop()

    def build_inputframe(self):
        self.input_sourcestree = Treeview(self.inputframe)
        self.input_addButton = Button(self.inputframe, text="Add...")
        self.input_editButton = Button(self.inputframe, text="Edit...")
        self.input_deleteButton = Button(self.inputframe, text="Delete")
        self.input_sourcestree.grid(row=0, column=0, columnspan=3)
        self.input_addButton.grid(row=1, column=0)
        self.input_editButton.grid(row=1, column=1)
        self.input_deleteButton.grid(row=1, column=2)

    def build_converterframe(self):
        self.converter_sourceframe = LabelFrame(self.converterframe)
        self.converter_sourceframeLabel = Label(self.converter_sourceframe)
        self.converter_sourceframeLabel["text"] = "ffmpeg.exe location"
        self.converter_sourceframe[
            "labelwidget"] = self.converter_sourceframeLabel
        self.coverter_sourceEntry = Entry(self.converter_sourceframe)
        self.converter_sourceChangeButton = Button(self.converter_sourceframe,
                                                   text="Change...")
        self.converter_sourceframe.grid(row=0, column=0)
        self.coverter_sourceEntry.grid(row=0, column=0)
        self.converter_sourceChangeButton.grid(row=1, column=0)

        self.converter_optionsframe = LabelFrame(self.converterframe)
        self.converter_optionsframe.grid(row=1, column=0)
        self.converter_optionsframeLabel = Label(self.converter_optionsframe)
        self.converter_optionsframeLabel["text"] = "commandline options"
        self.converter_optionsframe[
            "labelwidget"] = self.converter_optionsframeLabel
        self.converter_optionslist = Listbox(self.converter_optionsframe)
        self.converter_optionslist.grid(row=0, column=0)
        self.converter_optionslist.insert(0, "test")
        self.converter_optionslist_addButton = Button(
            self.converter_optionsframe, text="Add...")
        self.converter_optionslist_editButton = Button(
            self.converter_optionsframe, text="Edit...")
        self.converter_optionslist_deleteButton = Button(
            self.converter_optionsframe, text="Delete")
        self.converter_optionslist_addButton.grid(row=1, column=0)
        self.converter_optionslist_editButton.grid(row=2, column=0)
        self.converter_optionslist_deleteButton.grid(row=3, column=0)

    def build_outputframe(self):
        self.output_pathEntry = Entry(self.outputframe)
        self.output_pathButton = Button(self.outputframe, text="Browse...")
        self.output_namingFrame = LabelFrame(self.outputframe)
        self.output_namingLabel = Label(self.output_namingFrame,
                                        text="naming convention")
        self.output_namingFrame["labelwidget"] = self.output_namingLabel
        self.output_namingHelpLabel = Label(self.output_namingFrame)
        self.output_namingHelpLabel["text"] = "Placeholders:\n" \
                                              "%%path%%\n" \
                                              "%%filename%%\n" \
                                              "%%length%%\n"
        self.output_namingEntry = Entry(self.output_namingFrame)
        self.output_pathEntry.grid(row=0, column=0)
        self.output_pathButton.grid(row=0, column=1)
        self.output_namingFrame.grid(row=1, column=0, columnspan=2)
        self.output_namingHelpLabel.grid(row=0, column=0)
        self.output_namingEntry.grid(row=1, column=0)
예제 #32
0
    def init_page(self):
        """加载控件"""

        self.list = dbcontent.user_list()

        head_frame = LabelFrame(self, text="用户操作")
        head_frame.grid(row=0, column=0, columnspan=2, sticky="nswe")
        Label(head_frame, textvariable=self.selected_name).pack()

        btn_info = Button(head_frame, text="详情", command=self.info)
        btn_info.pack(side="left")
        btn_edit = Button(head_frame, text="编辑", command=self.edit)
        btn_edit.pack(side="left")
        btn_reset = Button(head_frame, text="重置密码", command=self.reset)
        btn_reset.pack(side="left")
        btn_delete = Button(head_frame, text="删除", command=self.delete)
        btn_delete.pack(side="left")

        # 表格
        self.tree_view = ttk.Treeview(self, show="headings")

        self.tree_view["columns"] = ("id", "name", "password", "op")
        # 列设置
        # self.tree_view.column("id", width=100) # 表示列,不显示
        # self.tree_view.column("name", width=100)
        # self.tree_view.column("password", width=100)
        # self.tree_view.column("op", width=100)
        # 显示表头
        self.tree_view.heading("id", text="ID")
        self.tree_view.heading("name", text="姓名")
        self.tree_view.heading("password", text="密码")
        self.tree_view.heading("op", text="操作")

        # 插入数据
        num = 1
        for item in self.list:
            self.tree_view.insert(
                "",
                num,
                text="",
                values=(item["id"], item["name"], item["password"], "详情"),
            )
        # 选中行
        self.tree_view.bind("<<TreeviewSelect>>", self.select)

        # 排序
        for col in self.tree_view["columns"]:  # 给所有标题加
            self.tree_view.heading(
                col,
                text=col,
                command=lambda _col=col: treeview_sort_column(
                    self.tree_view, _col, False),
            )

        vbar = ttk.Scrollbar(self,
                             orient="vertical",
                             command=self.tree_view.yview)
        self.tree_view.configure(yscrollcommand=vbar.set)
        self.tree_view.grid(row=1, column=0, sticky="nsew")
        vbar.grid(row=1, column=1, sticky="ns")
        Label(self, text="底部操作栏").grid(sticky="swe")
예제 #33
0
파일: main.py 프로젝트: Wingmore/CESD
    def __init__(self, root, in_Cap_Extract):
        # print(app.new.state())
        self.root = root
        # self.root.geometry("300x300+200+200")
        self.root.title('CESD Results')

        result_win = self.root
        result_win.grid_rowconfigure((0, 3), weight=0)
        result_win.grid_columnconfigure((0, 2), weight=1)

        misc_frame = LabelFrame(root, width=100, height=50, padx=10, pady=10)
        misc_frame.grid(row=1, column=2, padx=10, pady=10)

        out_frame = LabelFrame(root, width=100, height=50, padx=10, pady=10)
        out_frame.grid(row=1, column=1, padx=10)

        table_frame = LabelFrame(root,
                                 width=100,
                                 height=50,
                                 padx=10,
                                 pady=10,
                                 text="Capacitance Matrix")
        table_frame.grid(row=2, column=1, padx=10, pady=10, columnspan=2)

        label_names = [
            'ΔVtgs', 'ΔVg1', 'ΔVg2', 'DOT Charging Energy (meV)',
            'SET Charging Energy (meV)', 'DOT Lever Arm (%)',
            'SET Lever Arm (%)'
        ]
        o_variables = []

        # Results from image processing and stuff
        # source: https://stackoverflow.com/questions/18956945
        out = in_Cap_Extract.results
        o_variables.append(StringVar(self.root, value=out.DeltaVtgs))
        o_variables.append(StringVar(self.root, value=out.DeltaV1d))
        o_variables.append(StringVar(self.root, value=out.DeltaV2d))

        o_labels = []
        o_entrys = []
        for ii in range(3):
            o_labels.append(Label(out_frame, text=label_names[ii]))
            o_labels[-1].grid(padx=0, pady=0, row=ii, column=1, sticky='e')
            o_entrys.append(
                Entry(out_frame, textvariable=o_variables[ii], width=10))
            o_entrys[-1].grid(padx=0, pady=0, row=ii, column=2, sticky='w')

        m_variables = []
        for i in range(4):
            m_variables.append(StringVar(self.root, value=out.Energy[i]))

        self.m_labels = []
        self.m_entrys = []
        for ii in range(4):
            self.m_labels.append(Label(misc_frame, text=label_names[ii + +3]))
            self.m_labels[-1].grid(padx=0,
                                   pady=0,
                                   row=ii,
                                   column=1,
                                   sticky='e')
            self.m_entrys.append(
                Entry(misc_frame, textvariable=m_variables[ii], width=10))
            self.m_entrys[-1].grid(padx=0,
                                   pady=0,
                                   row=ii,
                                   column=2,
                                   sticky='w')
            print(ii, m_variables[ii])

        # Show Capacitance Matrix
        self.variables = []
        for i in range(25):
            self.variables.append([])

        #Fill out table entries
        for i in range(25):
            if (i + 5) // 5 == 1:
                self.variables[i] = StringVar(self.root, value=out.DOT[i % 5])
            if (i + 5) // 5 == 2:
                self.variables[i] = StringVar(self.root, value=out.SET[i % 5])
            if (i + 5) // 5 == 3:
                self.variables[i] = StringVar(self.root, value=out.G1[i % 5])
            if (i + 5) // 5 == 4:
                self.variables[i] = StringVar(self.root, value=out.G2[i % 5])
            if (i + 5) // 5 == 5:
                self.variables[i] = StringVar(self.root, value=out.TG[i % 5])

        self.labels = []
        self.entrys = []
        self.labels.append(Label(table_frame, text='DOT'))
        self.labels.append(Label(table_frame, text='SET'))
        self.labels.append(Label(table_frame, text='G1'))
        self.labels.append(Label(table_frame, text='G2'))
        self.labels.append(Label(table_frame, text='TopGate'))

        for i in range(5):
            self.labels[i].grid(padx=0, pady=0, row=0, column=i, stick="ew")

        for ii in range(25):
            self.entrys.append(
                Entry(table_frame, textvariable=self.variables[ii], width=10))
            self.entrys[-1].grid(padx=0,
                                 pady=0,
                                 row=(ii + 5) // 5 + 1,
                                 column=ii % 5)
class contrast_color_picker(_Dialog):
    def body(self, master):
        dialogframe = Frame(master, width=584, height=321)
        self.dialogframe = dialogframe
        dialogframe.pack()

        self.RadioGroup_1_StringVar = StringVar()

        self.make_Canvas_1(self.dialogframe)  #      Canvas:  at Main(2,2)
        self.make_Frame_1(self.dialogframe)  #       Frame:  at Main(2,1)
        self.make_Label_1(self.dialogframe)  #       Label:  at Main(2,3)
        self.make_Label_11(
            self.dialogframe)  #       Label: dark : at Main(3,4)
        self.make_Label_12(
            self.dialogframe)  #       Label: light : at Main(3,5)
        self.make_Label_6(self.dialogframe)  #       Label:  at Main(2,6)
        self.make_RadioGroup_1(
            self.dialogframe
        )  #  RadioGroup: Select Nominal Contrast Ratio : at Main(3,2)
        self.make_Scale_1(self.dialogframe)  #       Scale:  at Main(2,4)
        self.make_Scale_2(self.dialogframe)  #       Scale:  at Main(2,5)
        self.make_Button_1(
            self.Frame_1
        )  #      Button: Select Generic BG Color : at Frame_1(1,1)
        self.make_Button_2(
            self.Frame_1
        )  #      Button: Select Named BG Color : at Frame_1(2,1)
        self.make_Label_10(
            self.Frame_1
        )  #       Label: CR = Contrast Ratio : at Frame_1(10,1)
        self.make_Label_2(
            self.Frame_1)  #       Label: #ffffff : at Frame_1(4,1)
        self.make_Label_3(
            self.Frame_1)  #       Label: background color : at Frame_1(3,1)
        self.make_Label_4(
            self.Frame_1
        )  #       Label: contrasting foreground color : at Frame_1(6,1)
        self.make_Label_5(
            self.Frame_1)  #       Label: #000000 : at Frame_1(7,1)
        self.make_Label_7(self.Frame_1)  #       Label:  at Frame_1(9,1)
        self.make_Label_8(self.Frame_1)  #       Label:  at Frame_1(5,1)
        self.make_Label_9(
            self.Frame_1
        )  #       Label: click color chart to select : at Frame_1(8,1)
        self.make_Radiobutton_1(
            self.RadioGroup_1
        )  # Radiobutton: AA CR=4.5:1 normal text : at RadioGroup_1(1,1)
        self.make_Radiobutton_2(
            self.RadioGroup_1
        )  # Radiobutton: AA CR=3:1 large text : at RadioGroup_1(2,1)
        self.make_Radiobutton_3(
            self.RadioGroup_1
        )  # Radiobutton: AAA CR=7:1 for normal text : at RadioGroup_1(3,1)
        self.make_Radiobutton_4(
            self.RadioGroup_1
        )  # Radiobutton: AAA CR=4.5:1 for large text : at RadioGroup_1(4,1)

        self.dialogframe.columnconfigure(1, weight=1)

        self.RadioGroup_1_StringVar.set("2")
        self.RadioGroup_1_StringVar_traceName = self.RadioGroup_1_StringVar.trace_variable(
            "w", self.RadioGroup_1_StringVar_Callback)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.ref_color_str = '#808080'  # '#ffffff'       # default ref_color_str is white
        self.contrast_color_str = '#000000'  # default contrast_color_str is black

        self.Label_2.configure(text=self.ref_color_str,
                               fg=self.contrast_color_str,
                               bg=self.ref_color_str)

        self.ref_lum_p05 = self.get_lum_p05(self.ref_color_str)
        self.con_lum_p05 = self.get_lum_p05(self.contrast_color_str)
        self.CR = 21.0
        self.CR_request = 4.5

        self.crL = [4.5, 3.0, 7.0, 4.5]
        self.set_targ_lum_from_radiogroup()

        self.draw_canvas()
        self.ignore_slider = False

    def get_lum_p05(self, cstr):
        """Return luminance + 0.05 (used in contrast ratio calc.)"""
        (r, g, b) = hex_to_rgbfloat(cstr)
        lum_p05 = w3_luminance(r, g, b) + 0.05
        return lum_p05

    def set_slider_targ_lum(self):

        self.ignore_slider = True

        min_cr_val = 1.0

        # ---------- set Scale_1 based on best contrast possible
        #if self.ref_lum_p05 > 0.229: # best contrast is for low luminosity
        max_cr_val = self.ref_lum_p05 / 0.05
        #else:
        #    max_cr_val = max(1.05/self.ref_lum_p05, self.CR_request)

        self.Scale_1.configure(tickinterval=0.1,
                               from_=min_cr_val,
                               to=max_cr_val,
                               resolution=0.1,
                               digits=3)

        self.Scale_1_StringVar.set(self.CR_request)

        # ---------- set Scale_2 based on lesser contrast possible
        #if self.ref_lum_p05 > 0.229: # IGNORE best contrast is for low luminosity
        max_cr_val = 1.05 / self.ref_lum_p05
        #else:
        #max_cr_val = self.ref_lum_p05 / 0.05

        self.Scale_2.configure(tickinterval=0.1,
                               from_=min_cr_val,
                               to=max_cr_val,
                               resolution=0.1,
                               digits=3)

        self.Scale_2_StringVar.set(self.CR_request)

        self.ignore_slider = False

    def set_targ_lum_from_radiogroup(self):

        i = int(self.RadioGroup_1_StringVar.get()) - 1
        self.CR_request = self.crL[i]

        # calc required target luminance based on Radio Group Selection
        if self.ref_lum_p05 > 0.229:  # best contrast is for low luminosity
            self.targ_lum = max(0.0,
                                (self.ref_lum_p05 / self.CR_request) - 0.05)
        else:  # best contrast is for high luminosity
            self.targ_lum = min(1.0,
                                (self.CR_request * self.ref_lum_p05) - 0.05)

        self.set_slider_targ_lum()

    def draw_canvas(self):
        # clear canvas
        self.Canvas_1.delete("all")

        # paint canvas
        for i in range(N_CANVAS):
            for j in range(N_CANVAS):
                I = IMIN + i * DI
                Q = QMIN + j * DQ
                (r, g, b) = wiq_to_rgb(self.targ_lum, I, Q)
                cstr = rgbfloat_to_hex((r, g, b))

                w = i * DX_CANVAS
                h = j * DX_CANVAS
                self.Canvas_1.create_rectangle(
                    (w, h, w + DX_CANVAS, h + DX_CANVAS),
                    outline=cstr,
                    fill=cstr)

        # make sure that contrast label is set.
        self.set_contrast_color_label()

    def set_contrast_color_label(self):

        if self.ref_lum_p05 > self.con_lum_p05:
            self.CR = self.ref_lum_p05 / self.con_lum_p05
        else:
            self.CR = self.con_lum_p05 / self.ref_lum_p05

        msg = 'fg=%s, CR=%.1f' % (self.contrast_color_str, self.CR)
        self.Label_5.configure(text=msg,
                               bg=self.ref_color_str,
                               fg=self.contrast_color_str,
                               width=len(msg) + 2)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Canvas_1"
    def make_Canvas_1(self, frame):
        """      Canvas:  at Main(2,2)"""
        self.Canvas_1 = Canvas(frame, height="160", width="160")
        self.Canvas_1.grid(row=2, column=2, sticky="n")

        # >>>>>>insert any user code below this comment for section "make_Canvas_1"

        self.Canvas_1.config(bg='#ffffcc',
                             height=CANVAS_SIZE,
                             width=CANVAS_SIZE)
        self.Canvas_1.bind("<ButtonRelease-1>", self.Canvas_1_Click)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Frame_1"
    def make_Frame_1(self, frame):
        """       Frame:  at Main(2,1)"""
        self.Frame_1 = Frame(frame,
                             width="60",
                             relief="flat",
                             height="50",
                             borderwidth="6")
        self.Frame_1.grid(row=2, column=1, rowspan="2")

        # >>>>>>insert any user code below this comment for section "make_Frame_1"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_1"
    def make_Label_1(self, frame):
        """       Label:  at Main(2,3)"""
        self.Label_1 = Label(frame, text="", width="2")
        self.Label_1.grid(row=2, column=3)

        # >>>>>>insert any user code below this comment for section "make_Label_1"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_11"
    def make_Label_11(self, frame):
        """       Label: dark : at Main(3,4)"""
        self.Label_11 = Label(frame, text="dark", width="5")
        self.Label_11.grid(row=3, column=4, sticky="ne")

        # >>>>>>insert any user code below this comment for section "make_Label_11"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_12"
    def make_Label_12(self, frame):
        """       Label: light : at Main(3,5)"""
        self.Label_12 = Label(frame, text="light", width="5")
        self.Label_12.grid(row=3, column=5, sticky="ne")

        # >>>>>>insert any user code below this comment for section "make_Label_12"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_6"
    def make_Label_6(self, frame):
        """       Label:  at Main(2,6)"""
        self.Label_6 = Label(frame, text="", width="2")
        self.Label_6.grid(row=2, column=6)

        # >>>>>>insert any user code below this comment for section "make_Label_6"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_RadioGroup_1"
    def make_RadioGroup_1(self, frame):
        """  RadioGroup: Select Nominal Contrast Ratio : at Main(3,2)"""
        self.RadioGroup_1 = LabelFrame(frame,
                                       text="Select Nominal Contrast Ratio",
                                       width="60",
                                       height="50")
        self.RadioGroup_1.grid(row=3, column=2, sticky="new", columnspan="2")

        # >>>>>>insert any user code below this comment for section "make_RadioGroup_1"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Scale_1"
    def make_Scale_1(self, frame):
        """       Scale:  at Main(2,4)"""
        self.Scale_1 = Scale(frame,
                             width="16",
                             to="100",
                             length="160",
                             borderwidth="1",
                             label="")
        self.Scale_1.grid(row=2, column=4, sticky="n")
        self.Scale_1_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Scale_1"

        self.Scale_1.configure(variable=self.Scale_1_StringVar)
        self.Scale_1_StringVar_traceName = self.Scale_1_StringVar.trace_variable(
            "w", self.Scale_1_StringVar_Callback)
        self.Scale_1.configure(length=CANVAS_SIZE)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Scale_2"
    def make_Scale_2(self, frame):
        """       Scale:  at Main(2,5)"""
        self.Scale_2 = Scale(frame,
                             to="100",
                             width="16",
                             length="160",
                             borderwidth="1",
                             label="")
        self.Scale_2.grid(row=2, column=5, sticky="n")
        self.Scale_2_StringVar = StringVar()

        # >>>>>>insert any user code below this comment for section "make_Scale_2"

        self.Scale_2.configure(variable=self.Scale_2_StringVar)
        self.Scale_2_StringVar_traceName = self.Scale_2_StringVar.trace_variable(
            "w", self.Scale_2_StringVar_Callback)
        self.Scale_2.configure(length=CANVAS_SIZE)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Button_1"
    def make_Button_1(self, frame):
        """      Button: Select Generic BG Color : at Frame_1(1,1)"""
        self.Button_1 = Button(frame,
                               text="Select Generic BG Color",
                               width="30")
        self.Button_1.grid(row=1, column=1, sticky="ew")

        # >>>>>>insert any user code below this comment for section "make_Button_1"

        self.Button_1.bind("<ButtonRelease-1>", self.Button_1_Click)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Button_2"
    def make_Button_2(self, frame):
        """      Button: Select Named BG Color : at Frame_1(2,1)"""
        self.Button_2 = Button(frame, text="Select Named BG Color", width="30")
        self.Button_2.grid(row=2, column=1, sticky="ew")

        # >>>>>>insert any user code below this comment for section "make_Button_2"

        self.Button_2.bind("<ButtonRelease-1>", self.Button_2_Click)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_10"
    def make_Label_10(self, frame):
        """       Label: CR = Contrast Ratio : at Frame_1(10,1)"""
        self.Label_10 = Label(frame, text="CR = Contrast Ratio", width="30")
        self.Label_10.grid(row=10, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_10"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_2"
    def make_Label_2(self, frame):
        """       Label: #ffffff : at Frame_1(4,1)"""
        self.Label_2 = Label(frame,
                             foreground="#000000",
                             text="#ffffff",
                             width="15",
                             background="#ffffff",
                             font="Times\ New\ Roman 16 bold roman")
        self.Label_2.grid(row=4, column=1, sticky="ew")

        # >>>>>>insert any user code below this comment for section "make_Label_2"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_3"
    def make_Label_3(self, frame):
        """       Label: background color : at Frame_1(3,1)"""
        self.Label_3 = Label(frame, text="background color", width="15")
        self.Label_3.grid(row=3, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_3"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_4"
    def make_Label_4(self, frame):
        """       Label: contrasting foreground color : at Frame_1(6,1)"""
        self.Label_4 = Label(frame,
                             text="contrasting foreground color",
                             width="25")
        self.Label_4.grid(row=6, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_4"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_5"
    def make_Label_5(self, frame):
        """       Label: #000000 : at Frame_1(7,1)"""
        self.Label_5 = Label(frame,
                             foreground="#000000",
                             text="#000000",
                             width="15",
                             background="#ffffff",
                             font="Times\ New\ Roman 16 bold roman")
        self.Label_5.grid(row=7, column=1, sticky="ew")

        # >>>>>>insert any user code below this comment for section "make_Label_5"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_7"
    def make_Label_7(self, frame):
        """       Label:  at Frame_1(9,1)"""
        self.Label_7 = Label(frame, text="", width="15")
        self.Label_7.grid(row=9, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_7"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_8"
    def make_Label_8(self, frame):
        """       Label:  at Frame_1(5,1)"""
        self.Label_8 = Label(frame, text="", width="15")
        self.Label_8.grid(row=5, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_8"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Label_9"
    def make_Label_9(self, frame):
        """       Label: click color chart to select : at Frame_1(8,1)"""
        self.Label_9 = Label(frame,
                             text="click color chart to select",
                             width="30",
                             font="Times\ New\ Roman 12 bold roman")
        self.Label_9.grid(row=8, column=1)

        # >>>>>>insert any user code below this comment for section "make_Label_9"

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_1"
    def make_Radiobutton_1(self, frame):
        """ Radiobutton: AA CR=4.5:1 normal text : at RadioGroup_1(1,1)"""
        self.Radiobutton_1 = Radiobutton(frame,
                                         text="AA CR=4.5:1 normal text",
                                         value="1",
                                         width="20",
                                         anchor="w",
                                         justify="left")
        self.Radiobutton_1.grid(row=1, column=1, sticky="w")

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_1"

        self.Radiobutton_1.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_2"
    def make_Radiobutton_2(self, frame):
        """ Radiobutton: AA CR=3:1 large text : at RadioGroup_1(2,1)"""
        self.Radiobutton_2 = Radiobutton(frame,
                                         text="AA CR=3:1 large text",
                                         value="2",
                                         width="16",
                                         anchor="w",
                                         justify="left")
        self.Radiobutton_2.grid(row=2, column=1, sticky="w")

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_2"

        self.Radiobutton_2.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_3"
    def make_Radiobutton_3(self, frame):
        """ Radiobutton: AAA CR=7:1 for normal text : at RadioGroup_1(3,1)"""
        self.Radiobutton_3 = Radiobutton(frame,
                                         text="AAA CR=7:1 for normal text",
                                         value="3",
                                         width="20",
                                         anchor="w",
                                         justify="left")
        self.Radiobutton_3.grid(row=3, column=1, sticky="w")

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_3"

        self.Radiobutton_3.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "make_Radiobutton_4"
    def make_Radiobutton_4(self, frame):
        """ Radiobutton: AAA CR=4.5:1 for large text : at RadioGroup_1(4,1)"""
        self.Radiobutton_4 = Radiobutton(frame,
                                         text="AAA CR=4.5:1 for large text",
                                         value="4",
                                         width="20",
                                         anchor="w",
                                         justify="left")
        self.Radiobutton_4.grid(row=4, column=1, sticky="w")

        # >>>>>>insert any user code below this comment for section "make_Radiobutton_4"

        self.Radiobutton_4.configure(variable=self.RadioGroup_1_StringVar)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Canvas_1_Click"
    def Canvas_1_Click(self, event):  #bind method for component ID=Canvas_1
        """      Canvas:  at Main(2,2)"""
        pass
        # >>>>>>insert any user code below this comment for section "Canvas_1_Click"
        # replace, delete, or comment-out the following
        #print( "executed method Canvas_1_Click" )

        #print( "clicked in canvas at x,y =",event.x,event.y )

        #w = int(self.Canvas_1.cget("width"))
        #h = int(self.Canvas_1.cget("height"))
        #self.Canvas_1.create_rectangle((2, 2, w+1, h+1), outline="blue")
        #self.Canvas_1.create_line(0, 0, w+2, h+2, fill="red")
        x = int(event.x)
        y = int(event.y)
        #print( "event x,y=",x,y )
        item = self.Canvas_1.find_closest(event.x, event.y)

        # fill color of rectangle on canvas
        self.contrast_color_str = self.Canvas_1.itemcget(item, "fill")
        self.con_lum_p05 = self.get_lum_p05(self.contrast_color_str)

        self.set_contrast_color_label()
        #self.set_slider_targ_lum()

        #self.Canvas_1.create_text(x,y, text="NE", fill="green", anchor=NE)
        #self.Canvas_1.create_text(x,y, text="SW", fill="magenta", anchor=SW)

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Button_1_Click"
    def Button_1_Click(self, event):  #bind method for component ID=Button_1
        """      Button: Select Generic BG Color : at Frame_1(1,1)"""
        pass
        # >>>>>>insert any user code below this comment for section "Button_1_Click"
        # replace, delete, or comment-out the following
        #print( "executed method Button_1_Click" )

        ctup, cstr = tkinter.colorchooser.askcolor(title='Selected Color')
        if cstr:
            #print( cstr )
            lum_p05 = self.get_lum_p05(cstr)

            if lum_p05 > 0.229:
                fg = '#000000'
            else:
                fg = '#ffffff'

            msg = cstr
            self.Label_2.configure(text=msg,
                                   fg=fg,
                                   bg=cstr,
                                   width=len(msg) + 2)

            self.ref_color_str = cstr
            self.ref_lum_p05 = self.get_lum_p05(self.ref_color_str)

            self.set_targ_lum_from_radiogroup()
            self.draw_canvas()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Button_2_Click"
    def Button_2_Click(self, event):  #bind method for component ID=Button_2
        """      Button: Select Named BG Color : at Frame_1(2,1)"""
        pass
        # >>>>>>insert any user code below this comment for section "Button_2_Click"
        # replace, delete, or comment-out the following
        #print( "executed method Button_2_Click" )

        dialog = named_color_picker(self.parent, title="Get Named Color")
        if dialog.result is not None:
            (_, lum_p05, _, _, _, _, cstr, name) = dialog.result["named_color"]

            if lum_p05 > 0.229:
                fg = '#000000'
            else:
                fg = '#ffffff'

            msg = name + ' ' + cstr
            self.Label_2.configure(text=msg,
                                   fg=fg,
                                   bg=cstr,
                                   width=len(msg) + 2)

            self.ref_color_str = cstr
            self.ref_lum_p05 = self.get_lum_p05(self.ref_color_str)

            self.set_targ_lum_from_radiogroup()
            self.draw_canvas()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Scale_1_StringVar_traceName"
    def Scale_1_StringVar_Callback(self, varName, index, mode):
        """       Scale:  at Main(2,4)"""
        pass

        # >>>>>>insert any user code below this comment for section "Scale_1_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Scale_1_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Scale_1_StringVar.get() )

        if self.ignore_slider:
            return

        CR = float(self.Scale_1_StringVar.get())

        #if self.ref_lum_p05 > 0.229: # best contrast is for low luminosity
        self.targ_lum = max(0.0, (self.ref_lum_p05 / CR) - 0.05)
        #else:                   # best contrast is for high luminosity
        #    self.targ_lum = min(1.0, (CR * self.ref_lum_p05)-0.05 )

        self.draw_canvas()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "Scale_2_StringVar_traceName"
    def Scale_2_StringVar_Callback(self, varName, index, mode):
        """       Scale:  at Main(2,5)"""
        pass

        # >>>>>>insert any user code below this comment for section "Scale_2_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "Scale_2_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.Scale_2_StringVar.get() )

        if self.ignore_slider:
            return

        CR = float(self.Scale_2_StringVar.get())

        #if self.ref_lum_p05 > 0.229: # IGNORE best contrast is for low luminosity
        #    self.targ_lum = max(0.0, (self.ref_lum_p05 / CR)-0.05 )
        #else:                   # IGNORE best contrast is for high luminosity
        self.targ_lum = min(1.0, (CR * self.ref_lum_p05) - 0.05)

        self.draw_canvas()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "RadioGroup_1_StringVar_traceName"
    def RadioGroup_1_StringVar_Callback(self, varName, index, mode):
        """  RadioGroup: Select Nominal Contrast Ratio : at Main(3,2)"""
        pass

        # >>>>>>insert any user code below this comment for section "RadioGroup_1_StringVar_traceName"
        # replace, delete, or comment-out the following
        #print( "RadioGroup_1_StringVar_Callback varName, index, mode",varName, index, mode )
        #print( "    new StringVar value =",self.RadioGroup_1_StringVar.get() )

        self.set_targ_lum_from_radiogroup()
        self.draw_canvas()

    # TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "dialog_validate"
    def validate(self):
        self.result = {}  # return a dictionary of results

        self.result["Scale_1"] = self.Scale_1_StringVar.get()
        self.result["Scale_2"] = self.Scale_2_StringVar.get()
        self.result["RadioGroup_1"] = self.RadioGroup_1_StringVar.get()

        # >>>>>>insert any user code below this comment for section "dialog_validate"
        # set values in "self.result" dictionary for return
        # for example...
        # self.result["age"] = self.Entry_2_StringVar.get()

        self.result = {}  # reinitialize return a dictionary of results

        self.result["bg_color_str"] = self.ref_color_str
        self.result["fg_color_str"] = self.contrast_color_str

        self.result["contrast_ratio"] = self.CR

        return 1


# TkGridGUI generated code. DO NOT EDIT THE FOLLOWING. section "end"

    def apply(self):
        pass
예제 #35
0
t1 = ttk.Frame(tc)
t2 = ttk.Frame(tc)
tc.add(t1, text='Results', state="normal")
tc.pack(expand="yes", fill="both")
tc.add(t2, text='Other',
       state="hidden")  # insert a second tab for demo purposes

t1.grid_rowconfigure(
    2, weight=1)  # weight attr is similar to flex:1 in css flexbox
t1.grid_columnconfigure(0, weight=1)

section1 = LabelFrame(t1, text="Team Data")  # tkinter fieldsets
section2 = LabelFrame(t1, text="")
section3 = LabelFrame(t1, text="Team List", bd=2)

section1.grid(row=0, column=0, padx=20, pady=5, sticky="new")
section2.grid(row=1, column=0, padx=20, pady=5, sticky="new")
section3.grid(row=2, column=0, columnspan=4, padx=20, pady=5, sticky="nsew")
""" SECTION 1 - TEAM DATA """

section1.grid_rowconfigure(0, weight=1)
section1.grid_columnconfigure([1, 2], weight=1)

team_label = Label(section1, text='Member', font=('bold', 11))
team_label.grid(row=0, column=0, padx=10, pady=10)
team_text = StringVar()
# below set have assumed for ex. a pc username named fdrandom
# would be the user of F.D. in db Team column and on the tk menu
team_text.set(f"{userPC[0].upper()}.{userPC[1].upper()}.")
# team_text.set to a default value -> team_text.set(TeamPPL[0])
team_dropdown = OptionMenu(section1, team_text, *TeamPPL)  # dropdown menu
예제 #36
0
    def __init__(self, window):
        self.wind = window
        self.wind.title('Sistema de gestion de trabajos')
        self.rc = RepositorioClientes()
        self.lista_clientes = self.rc.get_all_particulares()
        self.rt = RepositorioTrabajos()

        #Frame
        frame = LabelFrame(self.wind, text='Menu principal')
        frame.grid(row=0, column=0, columnspan=8, pady=20)

        # Botonera
        ttk.Button(frame,
                   text="Agregar cliente particular",
                   command=self.add_clientspart_window).grid(row=1,
                                                             column=4,
                                                             columnspan=2,
                                                             sticky=W + E)
        ttk.Button(frame,
                   text="Agregar cliente corporativo",
                   command=self.add_clientscorp_window).grid(row=2,
                                                             column=4,
                                                             columnspan=2,
                                                             sticky=W + E)
        ttk.Button(frame,
                   text="Agregar un trabajo",
                   command=self.add_works_window).grid(row=3,
                                                       column=4,
                                                       columnspan=2,
                                                       sticky=W + E)

        # Mensajes de salida
        self.message = Label(text='', fg='red')
        self.message.grid(row=8, column=0, columnspan=2, sticky=W + E)

        # Tabla
        self.tree = ttk.Treeview(height=5, columns=("#1", "#2", "#3", '#4'))
        self.tree.grid(row=9, column=0, columnspan=6)

        self.tree.heading('#0', text='Nombre', anchor=CENTER)
        self.tree.heading('#1', text='Apellido', anchor=CENTER)
        self.tree.heading('#2', text='Teléfono', anchor=CENTER)
        self.tree.heading('#3', text='Mail', anchor=CENTER)
        self.tree.heading('#4', text='ID', anchor=CENTER)

        # Tabla clientes corporativos
        self.tree2 = ttk.Treeview(height=5,
                                  columns=("#1", "#2", "#3", "#4", '#5'))
        self.tree2.grid(row=11, column=0, columnspan=6)

        self.tree2.heading('#0', text='Nombre de la Empresa', anchor=CENTER)
        self.tree2.heading('#1', text='Nombre de Contacto', anchor=CENTER)
        self.tree2.heading('#2', text='Teléfono', anchor=CENTER)
        self.tree2.heading('#3', text='Teléfono de contacto', anchor=CENTER)
        self.tree2.heading('#4', text='Mail', anchor=CENTER)
        self.tree2.heading('#5', text='ID', anchor=CENTER)

        # Tabla trabajos
        self.tree3 = ttk.Treeview(height=5,
                                  columns=("#1", "#2", "#3", "#4", '#5', '#6'))
        self.tree3.grid(row=13, column=0, columnspan=6)

        self.tree3.heading('#0', text='ID de trabajo', anchor=CENTER)
        self.tree3.heading('#1', text='Nombre de cliente', anchor=CENTER)
        self.tree3.heading('#2', text='Fecha de Ingreso', anchor=CENTER)
        self.tree3.heading('#3',
                           text='Fecha de Entrega Propuesta',
                           anchor=CENTER)
        self.tree3.heading('#4', text='Fecha de Entrega Real', anchor=CENTER)
        self.tree3.heading('#5', text='Descripción', anchor=CENTER)
        self.tree3.heading('#6', text='Entregado', anchor=CENTER)

        # Botonera 2
        ttk.Button(text="Editar cliente particular",
                   command=self.edit_clients_part_window).grid(row=10,
                                                               column=1,
                                                               columnspan=2)
        ttk.Button(text="Eliminar cliente particular",
                   command=self.delete_clients_part).grid(row=10,
                                                          column=3,
                                                          columnspan=2)

        ttk.Button(text="Editar cliente corporativo",
                   command=self.edit_clients_corp_window).grid(row=12,
                                                               column=0,
                                                               columnspan=3)
        ttk.Button(text="Eliminar cliente corporativo",
                   command=self.delete_clients_corp).grid(row=12,
                                                          column=3,
                                                          columnspan=3)

        ttk.Button(text="Finalizar trabajo",
                   command=self.trabajo_finalizado).grid(row=14,
                                                         column=0,
                                                         columnspan=2)
        ttk.Button(text="Entregar el trabajo",
                   command=self.trabajo_entregado).grid(row=14,
                                                        column=1,
                                                        columnspan=2)
        ttk.Button(text="Modificar datos del trabajo",
                   command=self.edit_trabajos_window).grid(row=14,
                                                           column=2,
                                                           columnspan=2)
        ttk.Button(text="Cancelar trabajo",
                   command=self.eliminar_trabajo_confirmacion).grid(
                       row=14, column=3, columnspan=2)
        ttk.Button(text="Informe de trabajos pendientes",
                   command=self.informe).grid(row=14, column=4, columnspan=2)

        self.get_clients()
        self.get_works()
class OptimizerMainWindow:
    """
    classdocs
    """

    # TODO: change that name
    def reactToClick(self, event):
        a = AddRestrictionDialog(self)

    def __init__(self, optimizer):

        # always have a reference to model/controller
        self.optimizer = optimizer

        # setup main GUI and make stretchable
        self.guiRoot = Tk()
        self.guiRoot.title("OPTIMIZR")
        self.guiRoot.columnconfigure(1, weight=1)
        self.guiRoot.rowconfigure(0, weight=1)

        # left (settings) and right (sequences) part
        self.frameLeft = Frame(self.guiRoot)
        self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S)
        self.frameLeft.columnconfigure(0, weight=1)
        self.frameRight = Frame(self.guiRoot)
        self.frameRight.grid(row=0, column=1, sticky=W + E + N + S)
        self.frameRight.columnconfigure(0, weight=1)
        self.frameRight.rowconfigure(0, weight=1)
        self.frameRight.rowconfigure(1, weight=1)

        self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10)
        self.frameSpeciesControll.columnconfigure(1, weight=1)
        self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10)
        self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10)
        self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10)
        self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10)
        self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10)

        # Species Controll
        Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0)
        Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0)

        self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly")
        self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew")
        self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly")
        self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we")
        self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List")
        self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e")

        self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
        self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)

        # Optimization Controll
        Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0)
        self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly")
        self.comboOptimizationStrategy.grid(row=0, column=1)
        self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies
        self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)

        # Restriction Enzymes
        self.listRestriction = Listbox(self.frameRestrictionControll)
        self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E)
        self.frameRestrictionControll.columnconfigure(0, weight=1)
        self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ")
        self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ")
        self.buttonRestricionAdd.grid(row=1, column=1, padx=5)
        self.buttonRestricionDel.grid(row=1, column=2, padx=5)

        # Source Sequence Frame
        self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10)
        self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10)
        self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10)
        self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10)

        self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ")
        self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10)
        self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5)
        self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens")
        self.frameSourceSequence.columnconfigure(0, weight=1)
        self.frameSourceSequence.rowconfigure(1, weight=1)
        self.textSourceSeq.frame.columnconfigure(1, weight=1)
        self.textSourceSeq.frame.rowconfigure(0, weight=1)

        self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ")
        self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize)

        self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ")
        self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion)

        self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ")
        self.textResultSequence = ScrolledText(self.frameResultSequence, height=10)
        self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w")
        self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w")
        self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens")
        self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e")
        self.frameResultSequence.columnconfigure(2, weight=1)
        self.frameResultSequence.rowconfigure(1, weight=1)
        self.textResultSequence.frame.columnconfigure(1, weight=1)
        self.textResultSequence.frame.rowconfigure(0, weight=1)

        self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified)
        self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified)

        # generate color tags for textboxes
        for i in range(101):

            # green for normal codons
            (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0)
            colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255))

            self.textSourceSeq.tag_config("normal" + str(i), background=colorHex)
            self.textResultSequence.tag_config("normal" + str(i), background=colorHex)

            # red for codons with restriction sites
            (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0)
            colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255))

            self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex)
            self.textResultSequence.tag_config("restrict" + str(i), background=colorHex)

        # Set (minimum + max) Window size
        self.guiRoot.update()
        self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height())

        self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick)
        self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete)
        self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton)

        self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence)
        self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence)

        # TEST
        #         self.listRestriction.insert("end", "EcoRI")
        #         self.listRestriction.insert("end", "BamHI")
        #

        # dummy event to manually trigger update
        self.guiRoot.bind("<<Update>>", self.actionUpdate)

        self.actionUpdate(None)

        self.guiRoot.mainloop()

    def actionRestrictionEnzymeDelete(self, event):
        try:
            selectedEnzyme = self.listRestriction.selection_get()
            self.optimizer.restrictionEnzymeList.remove(selectedEnzyme)
            self.guiRoot.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionUpdate(self, event):
        #         print("update called")

        # clear list of restriction enzymes
        self.listRestriction.delete(0, "end")
        for r in self.optimizer.restrictionEnzymeList:
            self.listRestriction.insert("end", r)

        self.comboSourceSpecies.delete(0, "end")
        self.comboTargetSpecies.delete(0, "end")

        speciesValues = list()
        for (taxid, name) in self.optimizer.speciesList:
            speciesValues.append(taxid + ": " + name)

        self.comboSourceSpecies["values"] = speciesValues
        self.comboTargetSpecies["values"] = speciesValues

        if self.comboSourceSpecies.get() not in speciesValues:
            self.comboSourceSpecies.set("")
        if self.comboTargetSpecies.get() not in speciesValues:
            self.comboTargetSpecies.set("")

        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)

        self.optimizer.saveConfig("config.ini")

    def actionEditSpeciesButton(self, event):
        speciesListDialog = SpeciesListDialog(self)

    def actionOptimizerSettingsChanged(self, event=None):
        #         print("Something happened")
        strategy = self.comboOptimizationStrategy.get()
        sourceString = self.comboSourceSpecies.get()
        targetString = self.comboTargetSpecies.get()

        if not (strategy and sourceString and targetString):
            return

        sourceTaxid = sourceString.split(":")[0]
        targetTaxid = targetString.split(":")[0]

        self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy)

        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)

    #         self.optimizer.testPrint()

    def actionOptimize(self, event=None):
        self.optimizer.runOptimization()
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)

    def actionRemoveRestricion(self, event=None):
        self.optimizer.runRestricionRemoval()
        self.textSourceSeq.edit_modified(True)
        self.textResultSequence.edit_modified(True)

    def actionSequenceModified(self, event=None):
        # necessary if, otherwise -> infinite loop
        if self.textSourceSeq.edit_modified():

            seq = self.textSourceSeq.get("1.0", "end").strip()
            seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"])
            self.optimizer.setSourceSeq(seq)

            oldInsert = self.textSourceSeq.index("insert")
            self.textSourceSeq.delete("1.0", "end")

            sourceCodons = self.optimizer.getCodonsForPrint(True)
            if not sourceCodons:
                self.textSourceSeq.insert("end", self.optimizer.sourceSequence)
            else:
                for (co, sc, r) in sourceCodons:
                    if sc:
                        if not r:
                            self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100)))
                            # print("normal"+str(int(sc*100)))
                        else:
                            self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100)))
                    else:
                        # remainder without color
                        self.textSourceSeq.insert("end", co)

            self.textSourceSeq.mark_set("insert", oldInsert)

            # reset the modified status at the very end
            self.textSourceSeq.edit_modified(False)

        if self.textResultSequence.edit_modified():

            seq = self.textResultSequence.get("1.0", "end").strip()
            #             self.optimizer.setOptimizedSeq(seq)

            oldInsert = self.textResultSequence.index("insert")
            self.textResultSequence.delete("1.0", "end")

            targetCodons = self.optimizer.getCodonsForPrint(False)
            if not targetCodons:
                self.textSourceSeq.insert("end", self.optimizer.optimizedSequence)
            else:
                for (co, sc, r) in targetCodons:
                    if sc:
                        if not r:
                            self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100)))
                            # print("normal"+str(int(sc*100)))
                        else:
                            self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100)))
                    else:
                        # remainder without color
                        self.textResultSequence.insert("end", co)

            self.textSourceSeq.mark_set("insert", oldInsert)

            self.textResultSequence.edit_modified(False)

    def actionLoadSequence(self, event=None):
        filename = tkinter.filedialog.askopenfilename()
        if filename:
            seq = sequenceIO.readFile(filename)
            self.textSourceSeq.delete("1.0", "end")
            self.textSourceSeq.insert("end", seq)
            self.textSourceSeq.edit_modified(True)

    def actionSaveSequence(self, event=None):
        filename = tkinter.filedialog.asksaveasfilename()
        if filename:
            #             print("file is " + filename)
            with open(filename, mode="w") as fd:
                fd.write(self.optimizer.optimizedSequence)