Beispiel #1
2
    def __bookmarks(self, master):
        panel = Frame(master)
        panel.grid_rowconfigure(0, weight=1)

        bookmarks = Frame(panel)
        bookmarks.grid_columnconfigure(0, weight=1)
        bookmarks.grid_rowconfigure(0, weight=1)

        li = Listbox(bookmarks, width=40)
        li.grid(column=0, row=0, sticky=(N, E, S, W))
        self.bookmarks_list = li

        sb = Scrollbar(bookmarks, orient=VERTICAL, command=li.yview)
        sb.grid(column=1, row=0, sticky=(N, S))

        li.config(yscrollcommand=sb.set)
        def _lbox_selected(*args):
            selected_idx = int(li.curselection()[0])
            self.render_start.set(self.bookmarks_values[selected_idx])
            self.canvas.xview_moveto(0)
            if not self.render_auto.get():
                self.update()
        li.bind('<Double-Button-1>', _lbox_selected)
        bookmarks.grid(column=0, row=0, sticky=(N, E, S, W))

        buttons = Frame(panel)
        Button(buttons, image=self.img_start, command=self.start_event).pack(side="left")
        Button(buttons, image=self.img_prev, command=self.prev_event).pack(side="left")
        Button(buttons, image=self.img_end, command=self.end_event).pack(side="right")
        Button(buttons, image=self.img_next, command=self.next_event).pack(side="right")
        buttons.grid(column=0, row=1, sticky=(E, W))

        return panel
 def setPixelList(self):
     if "pixelListBox" in self.widgetDict.keys():
         pixelListBox = self.widgetDict["pixelListBox"]
         pixelListBox.delete(0, "end")
         self.widgetDict["kernelListbox"].config(text="Pixels: %s" % len(
             self.RepLine.getKernel(self.activeCob,
                                    self.activeKernel).keys()))
     else:
         pixelListbox = Listbox(self)
         self.widgetDict["pixelListbox"] = pixelListbox
         scrollbar = Scrollbar(pixelListbox, orient="vertical")
         pixelListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=pixelListbox.yview)
         self.widgetDict["pixelsLabel"].config(text="Pixels: %s" % len(
             self.RepLine.getKernel(self.activeCob,
                                    self.activeKernel).keys()))
         pixelListbox.grid(row=3, column=2, rowspan=3, sticky="nsew")
         pixelListbox.columnconfigure(0, weight=1)
         pixelListbox.bind("<<ListboxSelect>>", self.updateActivePixel)
         scrollbar.grid(column=2, sticky="e")
     cobNumber = self.activeCob[:self.activeCob.index("_")]
     kernelNumber = self.activeKernel[self.activeKernel.index(" ") + 1:]
     kernel = self.RepLine.getKernel(int(cobNumber), int(kernelNumber))
     for pixelNumber in xrange(len(kernel.keys())):
         pixelListbox.insert(pixelNumber, "Pixel: %s" % pixelNumber)
Beispiel #3
0
    def startUI(self):

        self.parent.title("Testing")

        self.file_list = listdir(getcwd())

        fileBox = Listbox(self.parent, selectmode=SINGLE)
        fileBox.pack()
        fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S)

        textBox = Text(self.parent)
        textBox.grid(column=4,
                     row=0,
                     columnspan=4,
                     rowspan=10,
                     sticky=N + S + E)

        ipBox = Entry(self.parent)
        ipBox.grid(column=0, row=0)

        btn = Button(text="Open ->",
                     command=lambda: self.readFile(fileBox, textBox))
        btn.grid(column=3, row=2)

        btnFire = Button(text="Fire away!",
                         command=lambda: self.fireTorpedoes(ipBox, textBox))
        btnFire.grid(column=3, row=3)

        scrlBar = Scrollbar(self.parent, command=textBox.yview)
        scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S)
        textBox.config(yscrollcommand=scrlBar.set)

        for i in self.file_list:
            fileBox.insert(END, i)
Beispiel #4
0
    def startUI(self):

        self.files = os.listdir(os.getcwd())

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)

        menubar.add_cascade(label="File", menu=fileMenu)

        listbox = Listbox(self.parent, selectmode=SINGLE)
        listbox.pack(fill=BOTH, expand=1)
        # listbox.insert(END, 'bebs')
        for i in self.files:
            listbox.insert(END, i)

        listbox.grid(column=0, columnspan=4, row=0, rowspan=10, sticky=N+S+E+W)


        txt = Text(self.parent)
        txt.grid(column=6, columnspan=8, row=0, rowspan=10, sticky=N+S+E+W)
        # txt.pack(fill=BOTH, expand=1)

        oBtn = Button(text="Open->", command=lambda: self.readContents(listbox, txt))

        oBtn.grid(column=5, row=3)
Beispiel #5
0
    def initUI(self):
      
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)


        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)
        
        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W, pady=4, padx=5)
        
        area = Listbox(self)
        area.grid(row=1, column=0, columnspan=2, rowspan=4, 
            padx=5, sticky=E+W+S+N)
        
        abtn = Button(self, text="Activate")
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close")
        cbtn.grid(row=2, column=3, pady=4)
        
        hbtn = Button(self, text="Help")
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
class Window(object):
    def __init__(self, master):

        self.master = master
        self.master.wm_title('PEP8 checker')
        self.master.resizable(False, True)

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)

        home_dir = expanduser("~")
        self.directory = StringVar(value=home_dir)

        directory_frame = Frame(self.frame)
        directory_frame.grid()
        self.frame.grid_rowconfigure(2, weight=1)

        self.entry_directory = Entry(directory_frame, textvariable=self.directory)
        self.entry_directory.pack(anchor=W, side=LEFT)

        self.select_directory = Button(directory_frame, text="Select directory to scan", command=self.select_directory)
        self.select_directory.pack(anchor=E, side=RIGHT)

        self.run_button = Button(self.frame, text='Run PEP8!', command=self.run_pep)
        self.run_button.grid(sticky=W + E)

        self.errors_list = Listbox(self.frame)
        self.errors_list.grid(sticky=W + E)

        self.status_label = Label(self.frame)

    def select_directory(self):
        directory = askdirectory(initialdir=self.directory.get())
        if directory:
            self.directory.set(directory)

    def run_pep(self):
        self.errors_list.delete(0, END)
        process = Popen('$(which pep8) {}'.format(self.directory.get()), shell=True, stderr=PIPE, stdout=PIPE)
        output = process.communicate()[0]
        selected_dir = ''.join((self.directory.get(), '/'))
        if output:
            self.errors_list.configure(background='red')
            for i, error in enumerate(output.split('\n')):
                self.errors_list.insert(i, error.replace(selected_dir, ''))
        else:
            self.errors_list.configure(background='green')
            self.errors_list.insert(0, 'Directory is OK!')
Beispiel #7
0
    class RecapCalculs:
        '''
        Interface graphique recapitulant les caracteristique du sismogramme
        presentant les options de filtrage et de calculs du noyau de sensibilite
        '''
        def __init__(self,root):
            self.canvas = Canvas(root, borderwidth=1, background="#ffffff")
            self.frame = Frame(self.canvas, background="#ffffff")
            self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview)
            self.canvas.configure(yscrollcommand=self.vsb.set)
            self.vsb.pack(side="right", fill="y")
            self.canvas.pack(side="left", fill="both", expand=True)
            self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame")

            self.frame.bind("<Configure>", self.OnFrameConfigure)

            self.data()
        def data(self):
        
            self.message = Label(self.frame, text="Recapitulatif du sismogramme").grid(row=0)
         
            global X
            X=read(textPath.get())
          
            self.recap = Listbox(self.frame, height = 15, width = 50)
           
            self.recap.insert(1, "network: {}\n".format(X[0].stats.network))
            self.recap.insert(2, "station: {}\n".format(X[0].stats.station))
            self.recap.insert(3, "location: {}\n".format(X[0].stats.location))
            self.recap.insert(4, "channel: {}\n".format(X[0].stats.channel))
            self.recap.insert(5, "start time: {}\n".format(X[0].stats.starttime))
            self.recap.insert(6, "end time: {}\n".format(X[0].stats.endtime))
            self.recap.insert(7, "sampling rate: {}\n".format(X[0].stats.sampling_rate))
            self.recap.insert(8, "delta: {}\n".format(X[0].stats.delta))
            self.recap.insert(9, "number points: {}\n".format(X[0].stats.npts))
            self.recap.insert(10, "calibration: {}\n".format(X[0].stats.calib))
            self.recap.insert(11, "event latitude: {}\n".format(X[0].stats.sac.evla))
            self.recap.insert(12, "event longitude: {}\n".format(X[0].stats.sac.evlo))
            self.recap.insert(13, "event depth: {}\n".format(X[0].stats.sac.evdp))
            self.recap.insert(14, "station latitude: {}\n".format(X[0].stats.sac.stla))
            self.recap.insert(15, "station longitude: {}\n".format(X[0].stats.sac.stlo))
            self.recap.grid(row=0)
            
            #afficheGraphique()
        
        def OnFrameConfigure(self, event):
            '''Reset the scroll region to encompass the inner frame'''
            self.canvas.configure(scrollregion=self.canvas.bbox("all"))
Beispiel #8
0
    def init(self):
        self.parent.title('FuzzyOctoDubstep')

        self.style = Style()
        self.style.theme_use('default')
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W, pady=4, padx=5)

        conv_scrollbar = Scrollbar(self)
        conv_scrollbar.grid(row=1, column=2)

        conv = Listbox(self,
                       width=80,
                       height=30,
                       yscrollcommand=conv_scrollbar.set)
        conv.grid(row=1,
                  column=0,
                  columnspan=2,
                  rowspan=4,
                  padx=5,
                  sticky=E + W + S + N)
        conv.insert(END, 'Hello')

        conv_scrollbar.config(command=conv.yview)

        abtn = Button(self, text="Activate")
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close")
        cbtn.grid(row=2, column=3, pady=4)

        hbtn = Button(self, text="Help")
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
class GUIListbox:
    def __init__(self, parent, items=None, **kwargs):
        self.listbox = Listbox(parent, **kwargs)

        if items:
            self.setItems(items)

    def setItems(self, items):
        self.listbox.delete(0, END)
        for item in items:
            self.listbox.insert(END, item)

    def getSelected(self):
        return self.listbox.get(ACTIVE)

    def bindDoubleClick(self, func):
        self.listbox.bind("<Double-Button-1>", func)

    def grid(self, **kwargs):
        self.listbox.grid(kwargs)

    def pack(self, **kwargs):
        self.listbox.pack(kwargs)
 def setKernelList(self):
     self.kernelList = []
     for i in xrange(len(self.RepLine.cobs[self.activeCob])):
         self.kernelList.append("Kernel: " + str(i + 1))
     if "kernelListbox" in self.widgetDict.keys():
         kernelListbox = self.widgetDict["kernelListbox"]
         kernelListbox.delete(0, "end")
         self.widgetDict["kernelsLabel"].config(text="Kernels: %s" %
                                                len(self.kernelList))
     else:
         kernelListbox = Listbox(self)
         self.widgetDict["kernelListbox"] = kernelListbox
         scrollbar = Scrollbar(kernelListbox, orient="vertical")
         kernelListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=kernelListbox.yview)
         self.widgetDict["kernelsLabel"].config(text="Kernels: %s" %
                                                len(self.kernelList))
         kernelListbox.grid(row=3, column=1, rowspan=3, sticky="nsew")
         kernelListbox.columnconfigure(0, weight=1)
         kernelListbox.bind("<<ListboxSelect>>", self.updateActiveKernel)
         scrollbar.grid(column=1, sticky="e")
     for kernel in self.kernelList:
         kernelListbox.insert(self.kernelList.index(kernel), kernel)
Beispiel #11
0
    def init(self):
        self.parent.title('FuzzyOctoDubstep')

        self.style = Style()
        self.style.theme_use('default')
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W, pady=4, padx=5)

        conv_scrollbar = Scrollbar(self)
        conv_scrollbar.grid(row=1, column=2)


        conv = Listbox(self, width=80, height=30, yscrollcommand=conv_scrollbar.set)
        conv.grid(row=1, column=0, columnspan=2, rowspan=4,
            padx=5, sticky=E+W+S+N)
        conv.insert(END, 'Hello')

        conv_scrollbar.config(command=conv.yview)

        abtn = Button(self, text="Activate")
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close")
        cbtn.grid(row=2, column=3, pady=4)

        hbtn = Button(self, text="Help")
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
 def setCobList(self):
     self.cobList = []
     for cob in xrange(len(self.RepLine.cobs.keys())):
         self.cobList.append(
             str(cob + 1) + "_" + self.RepLine.accessionName)
     if "cobListbox" in self.widgetDict.keys():
         cobListbox = self.widgetDict["cobListbox"]
         cobListbox.delete(0, "end")
         self.widgetDict["cobsLabel"].config(text="Cobs: %s" %
                                             len(self.cobList))
     else:
         cobListbox = Listbox(self)
         self.widgetDict["cobListbox"] = cobListbox
         scrollbar = Scrollbar(cobListbox, orient="vertical")
         cobListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=cobListbox.yview)
         self.widgetDict["cobsLabel"].config(text="Cobs: %s" %
                                             len(self.cobList))
         cobListbox.grid(row=3, column=0, rowspan=3, sticky="nsew")
         cobListbox.columnconfigure(0, weight=1)
         cobListbox.bind("<<ListboxSelect>>", self.updateActiveCob)
         scrollbar.grid(column=0, sticky="e")
     for cob in self.cobList:
         cobListbox.insert(self.cobList.index(cob), cob)
Beispiel #13
0
    def startUI(self):

        self.files = os.listdir(os.getcwd())

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)

        menubar.add_cascade(label="File", menu=fileMenu)

        listbox = Listbox(self.parent, selectmode=SINGLE)
        listbox.pack(fill=BOTH, expand=1)
        # listbox.insert(END, 'bebs')
        for i in self.files:
            listbox.insert(END, i)

        listbox.grid(column=0,
                     columnspan=4,
                     row=0,
                     rowspan=10,
                     sticky=N + S + E + W)

        txt = Text(self.parent)
        txt.grid(column=6,
                 columnspan=8,
                 row=0,
                 rowspan=10,
                 sticky=N + S + E + W)
        # txt.pack(fill=BOTH, expand=1)

        oBtn = Button(text="Open->",
                      command=lambda: self.readContents(listbox, txt))

        oBtn.grid(column=5, row=3)
Beispiel #14
0
class Troop:
    @classmethod
    def init_troop(cls, name, nation):
        strength = random.randint(1, 3)
        health = random.randint(1, 3)
        ranged = random.choice([False, True]) #Starting troops are always melee random.choice([False, True])

        speed = random.randint(2, 4)

        discipline = random.randint(1, 2)

        rank_size = random.randint(4, 15)
        ranks = random.randint(4, 6)

        elite = random.randint(2, 6)

        if ranged:
            weapons = [random.choice(nation.basic_ranged_weapon_list), random.choice(nation.sidearm_list)]
        else:
            weapons = [random.choice(nation.basic_weapon_list), random.choice(nation.basic_weapon_list)]

        #weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]

        armor = random.choice(nation.basic_armor_list)

        mount = nation.mount_none

        if random.randint(0, 100) < elite + 5:
            mount = random.choice(nation.basic_mount_list)


        tier = 1

        # print "Unknown nation has created a new unit: " + str(name) + ", armed with: " + str(weapons[0].name) +", " + str(weapons[1].name) + ", "+str(armor.name)+", "+str(mount.name)+" elite: "+str(elite)

        return cls(name, strength, health, 0, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, tier, [], mount, troop_nation=nation)

    def __init__(self, name, strength, health, number, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, tier, upgrades, mount,
                 stats_history=None, arms_history=None, troop_nation=None):
        if arms_history is None:
            arms_history = []
        if stats_history is None:
            stats_history = []
        self.name = name
        self.strength = strength
        self.health = health
        self.number = number

        self.speed = speed

        self.originally_ranged = ranged #This one won't change when the unit swiches to melee mode.
        self.ranged = ranged

        self.discipline = discipline

        self.rank_size = rank_size
        self.ranks = ranks

        self.weapons = weapons
        self.armor = armor
        self.mount = mount

        self.upgrades = upgrades

        self.elite = elite

        self.tier = tier

        self.nation = troop_nation

        if not arms_history:
            self.arms_history = [(self.weapons, self.armor)]
        else:
            self.arms_history = arms_history

        if not stats_history:
            self.stats_history = [utility.base_soldier_stats()]
        else:
            self.stats_history = stats_history

        self.quality = 0

        if self.nation is not None:
            self.nation.troop_tree.append(self)

        self.experience = 1

    #Creates another troop to add to the troop tree
    @classmethod
    def new_troop(cls, self, nation):
        name = nation.language.make_word(nation.language.name_length, True)

        ranged = random.choice([False, True])

        strength = self.strength + random.randint(1, 10 if not ranged else 5)
        health = self.health + random.randint(1, 4 if not ranged else 2)
        discipline = self.discipline + random.randint(0, 1)

        speed = self.speed + random.randint(1, 2)

        rank_size = random.randint(3, 15)
        ranks = random.randint(3, 5)

        if ranged:
            weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]
        else:
            weapons = [random.choice(nation.weapon_list), random.choice(nation.sidearm_list)]

        armor = random.choice(nation.armor_list)

        mount = nation.mount_none

        elite = random.randint(2, 6)

        if random.randint(0, 100) < (elite * 2) + 5:
            mount = random.choice(nation.mount_list)

        # print str(nation.name) + " created a new unit: " + str(name) + ", armed with: " + str(weapons[0].name) +", " + str(weapons[1].name) + ", "+str(armor.name)+", "+str(mount.name)
        #e.append(events.EventTroopCreated('TroopCreated', {'nation_a': nation.name, 'army_a': name, 'equip_a':weapons, 'armor_a':armor}, s_parent.get_current_date()))

        return cls(name, strength, health, 0, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, self.tier + 1, [], mount, troop_nation=nation)

    def get_info(self):
        res = {}
        res['name'] = self.name
        res['strength'] = self.strength
        res['health'] = self.health
        res['number'] = self.number
        res['speed'] = self.speed
        res['ranged'] = self.ranged
        res['discipline'] = self.discipline
        res['rank_size'] = self.rank_size
        res['ranks'] = self.ranks
        res['weapons'] = map(lambda eqp: eqp.get_info(), self.weapons)
        res['armor'] = self.armor.get_info()
        res['elite'] = self.elite
        res['tier'] = self.tier
        res['mount'] = self.mount

        res['upgrades'] = []
        for upgrade in self.upgrades:
            res['upgrades'].append(upgrade.get_info())

        res['arms_history'] = []
        for weapons, armor in self.arms_history:
            res['arms_history'].append((map(lambda eqp: eqp.get_info(), weapons), armor.get_info()))

        res['stats_history'] = self.stats_history

        return res

    # TODO: Make these actually do something
    def train(self, amount):
        return 0
        #self.elite += random.randint(0, amount)
        #print self.elite

    def upgrade_gear(self):
        return 0
        # if self.quality > 6:
        #     return

        # self.quality += 1

        # #print "upgrading " + str(self.weapons[0].attack)

        # self.weapons[0].upgrade(1)
        # self.weapons[0].upgrade_skill(1)

        # #Sprint "upgrading to" + str(self.weapons[0].attack)

        # self.weapons[1].upgrade(1)
        # self.weapons[1].upgrade_skill(1)

        # self.armor.upgrade(1)
        # self.armor.upgrade_skill(1)

    def save(self, path):
        with open(path + 'army_structure.txt', 'w') as f:
            f.write(str(self.get_info()))

    def handle_battle_end(self, stats):
        self.stats_history[-1] = utility.zip_dict_with(lambda a,b: a + b, self.stats_history[-1], stats)

    def do_rearm(self, nation):
        if self.tier == 1:
            if self.ranged:
                weapons = [random.choice(nation.basic_ranged_weapon_list), random.choice(nation.sidearm_list)]
            else:
                weapons = [random.choice(nation.basic_weapon_list), random.choice(nation.basic_weapon_list)]

            armor = random.choice(nation.basic_armor_list)

            mount = nation.mount_none

            if random.randint(0, 100) < self.elite + 5:
                mount = random.choice(nation.basic_mount_list)
        else:
            if self.ranged:
                weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]
            else:
                weapons = [random.choice(nation.weapon_list), random.choice(nation.sidearm_list)]

            armor = random.choice(nation.armor_list)

            mount = nation.mount_none

            if random.randint(0, 100) < (self.elite * 2) + 5:
                mount = random.choice(nation.mount_list)

        self.weapons = weapons
        self.armor = armor
        self.mount = mount

        self.arms_history.append((self.weapons, self.armor, self.mount))
        self.stats_history.append(utility.base_soldier_stats())

        return self

    def rearm(self, name, new_weapons, new_armor, new_mount):
        if self.name == name:
            self.weapons = new_weapons
            self.armor = new_armor
            self.mount = new_mount
        else:
            for upgrade in self.upgrades:
                upgrade.rearm(name, new_weapons, new_armor, new_mount)

    def show_information_gui(self):
        self.gui_window = Tk()
        self.gui_window.title(self.name)
        self.gui_window.geometry("400x625+0+0")
        self.gui_window.config(background='white')

        self.ranged_label = gui.Label(self.gui_window, text='Is ranged: {}'.format(self.ranged))
        self.ranged_label.grid(row=0, sticky=W)

        self.mount_label = gui.Label(self.gui_window, text='Mount: {}'.format(self.mount.name))
        self.mount_label.grid(row=1, sticky=W)

        self.strength_label = gui.Label(self.gui_window, text='Strength: {}'.format(self.strength))
        self.strength_label.grid(row=2, sticky=W)

        self.health_label = gui.Label(self.gui_window, text='Health: {}'.format(self.health))
        self.health_label.grid(row=3, sticky=W)

        self.discipline_label = gui.Label(self.gui_window, text='Discipline: {}'.format(self.discipline))
        self.discipline_label.grid(row=4, sticky=W)


        self.discipline_label = gui.Label(self.gui_window, text='Cost: {}'.format(self.get_soldier_cost()))
        self.discipline_label.grid(row=5, sticky=W)

        self.arrangement = gui.Label(self.gui_window, text='Arrangement: {}x{}'.format(self.rank_size, self.ranks))
        self.arrangement.grid(row=6, sticky=W)

        self.arrangement_canvas = Canvas(self.gui_window, width = (self.rank_size + 1) * (TROOP_RADIUS + 1), height= (self.ranks + 1) * (TROOP_RADIUS + 1))
        self.arrangement_canvas.config(background='white')
        self.arrangement_canvas.grid(row=7, sticky=W)

        for x in xrange(1, self.rank_size + 1):
            for y in xrange(1, self.ranks + 1):
                base_x, base_y = x * (TROOP_RADIUS + 1), y * (TROOP_RADIUS + 1)
                self.arrangement_canvas.create_oval(base_x, base_y, base_x + TROOP_RADIUS, base_y + TROOP_RADIUS)

        self.upgrade_label = gui.Label(self.gui_window, text='Upgrades:')
        self.upgrade_label.grid(row=8, sticky=W)

        self.upgrade_buttons = []
        for (i, upgrade) in enumerate(self.upgrades):
            new_upgrade_button = gui.Button(self.gui_window, text=upgrade.name, command=upgrade.show_information_gui)
            new_upgrade_button.grid(row=9, column=i, sticky=W)

            self.upgrade_buttons.append(new_upgrade_button)

        self.history_choice = StringVar()
        self.history_choice.set(self.stringify_history(0))

        self.stats_label = gui.Label(self.gui_window, text='Stats:')
        self.stats_label.grid(row=10, column=0, sticky=W)

        self.stats_choice = OptionMenu(self.gui_window, self.history_choice, *map(self.stringify_history, range(len(self.arms_history))))
        self.stats_choice.config(background='white')
        self.stats_choice['menu'].config(background='white')
        self.stats_choice.grid(row=10, column=1, sticky=W)

        self.stats_select = gui.Button(self.gui_window, text='Select', command=self.select_history)
        self.stats_select.grid(row=10, column=2, sticky=W)

        self.stats_display = Listbox(self.gui_window)
        self.stats_display.grid(row=11, column=0, columnspan=3, sticky=W+E)

        self.select_history()

    def get_soldier_cost(self):
        amount = 0
        for weapon in self.weapons:
            amount += weapon.cost

        amount += self.armor.cost
        amount += self.mount.cost

        return amount

    def stringify_history(self, i):
        weapon_str = ', '.join(map(lambda i: i.name, self.arms_history[i][0]))
        armor_str = self.arms_history[i][1].name
        mount_str = self.mount.name
        return '{}: ({}, {}), {}'.format(i, weapon_str, armor_str, mount_str)

    def select_history(self):
        history_index = int(self.history_choice.get().split(':')[0])

        self.stats_display.delete(0, END)
        for stat in self.stats_history[history_index]:
            self.stats_display.insert(END, '{}: {}'.format(utility.displayify_text(stat), self.stats_history[history_index][stat]))

    def add_number(self, number, nation):
        self.number += number
        #e.append(events.EventArmyRaised('ArmyRaised', {'nation_a': nation.name, 'army_a': self.name, 'raised_a':number}, s_parent.get_current_date()))

        if self.number > self.elite** math.sqrt(self.tier): #If we have enough troops, we will create another, better, rank of troops
            if len(self.upgrades) < 3:
                self.upgrades.append(Troop.new_troop(self, nation))

                self.upgrades[-1].upgrades = [] #Because it wants to put itself as an upgrade, for some reason. TODO

        if self.number < 0:
            self.number = 0

        #Upgrade troops if possible.
        if self.number > (self.elite * self.tier) and len(self.upgrades) > 0:
            upgrading = random.randint(1, self.number // self.elite)
            self.number -= upgrading

            per_upgrade = upgrading // len(self.upgrades)
            for upgrade in self.upgrades:
                total_cost = nation.get_soldier_cost(upgrade)

                if nation.money > total_cost:
                    upgrade.add_number(per_upgrade, nation)
                    #print str(nation.name) + " raised an army of " + str(number) + " " + str(self.name)
                else:
                    self.number += per_upgrade #Add these people back, because they weren't actually upgraded.

        nation.update_tree(self)

        return self

    def reset(self):
        return self.zero().reset_stats()

    def reset_stats(self):
        self.stats_history = [utility.base_soldier_stats()]

        return self

    def zero(self):
        return self.copy().remove_number('', self.size())

    def add_army(self, other):
        self.add_to(other.name, other.number)

        for i in other.upgrades:
            self.add_army(i)

    def add_to(self, type, number):
        if self.name == type:
            self.number += number

            return self
        else:
            for upgrade in self.upgrades:
                if upgrade.name == type:
                    upgrade.number += number

                    return self

            for upgrade in self.upgrades:
                val = upgrade.add_to(type, number)

                if val is not None:
                    return self

            return None

    #Returns a list of the unit + it's upgrades
    def make_upgrade_list(self):
        return sorted([self] + reduce(lambda a, b: a + b, [i.make_upgrade_list() for i in self.upgrades], []), key=lambda a: a.strength * a.health)

    def copy(self):
        return Troop(self.name, self.strength, self.health, 0, self.ranged, self.speed, self.discipline, self.rank_size, self.ranks, [i.copy() for i in self.weapons], self.armor.copy(), self.elite, self.tier, map(lambda i: i.copy(), self.upgrades), self.mount, stats_history=map(dict, self.stats_history), arms_history=list(self.arms_history))

    def is_empty(self):
        return all(map(lambda i: i.is_empty(), self.upgrades)) and self.number == 0

    def trim_empty(self):
        i = 0
        while i < len(self.upgrades):
            if self.upgrades[i].is_empty():
                self.upgrades.pop(i)
            else:
                self.upgrades[i] = self.upgrades[i].trim_empty()

                i += 1

        return self

    def take_number(self, number):
        upgrade_list = self.make_upgrade_list()

        result = self.copy()

        for upgrade in upgrade_list:
            upgraded_amount = 0

            if upgrade.number > number:
                upgrade.number -= number
                upgraded_amount = number

                number = 0
            else:
                upgraded_amount = upgrade.number
                number -= upgrade.number

                upgrade.number = 0

            result.add_to(upgrade.name, upgraded_amount)

            if number == 0:
                break

        return result.trim_empty()

    def remove_number(self, type, number):
        if type == '':
            upgrade_list = self.make_upgrade_list()

            for upgrade in upgrade_list:
                if upgrade.number > number:
                    upgrade.number -= number

                    number = 0

                    return self
                else:
                    number -= upgrade.number

                    upgrade.number = 0

            return self
        else:
            if type == self.name:
                self.number -= number

                return self.number

            for i in self.upgrades:
                if i.name == type:
                    i.number -= number

                    return i.number

            #If not found in any of them, let's check all the children
            for i in self.upgrades:
                val = i.remove_number(type, number)

                if val >= 0:
                    return val

            return -1

    def size(self):
        return self.number + sum(map(lambda t: t.size(), self.upgrades))

    def merge_all(self, other):
        if self.name == other.name:
            self.number += other.number

            for index, upgrade in enumerate(other.upgrades):
                if not upgrade in self.upgrades:
                    self.upgrades.append(upgrade.copy())

                    self.upgrades[-1] = self.upgrades[-1].merge_all(upgrade)
                else:
                    self_upgrade = self.upgrades.index(upgrade)

                    self.upgrades[self_upgrade] = self.upgrades[self_upgrade].merge_all(upgrade)

            return self

    def merge_structure(self, other):
        result = self.zero()

        if result.name == other.name:
            for index, upgrade in enumerate(other.upgrades):
                if not upgrade in result.upgrades:
                    result.upgrades.append(upgrade.zero())

                    result.upgrades[-1] = result.upgrades[-1].merge_structure(upgrade)
                else:
                    self_upgrade = self.upgrades.index(upgrade)

                    result.upgrades[self_upgrade] = result.upgrades[self_upgrade].merge_structure(upgrade)

        return result

    def __eq__(self, other):
        try:
            return self.name == other.name
        except:
            return False

    def __repr__(self):
        return "{0}({1}, {2}): {3} {4}".format(self.name, self.strength, self.health, self.number, self.upgrades)
Beispiel #15
0
class EngineGui():
    def __init__(self, communicationProtocal):
        self.communicationProtocal = communicationProtocal

    def StartGui(self):
        self.tkRoot = Tk(baseName="")
        self.tkRoot.geometry("350x300+0+0")
        self.tkRoot.title("Engine SAPI GUI")
        self.GUIVisible = True

        frame = Frame(self.tkRoot)
        frame.style = Style()
        frame.style.theme_use("alt")
        frame.pack(fill=BOTH, expand=1)

        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(7, pad=7)
        frame.rowconfigure(13, weight=1)
        frame.rowconfigure(13, pad=7)
        
        Label(frame, text="Start:").grid(row = 0, column=0)
        self.labelStart = Label(frame, text="0")
        self.labelStart.grid(row = 1, column=0)

        Label(frame, text="Length:").grid(row = 0, column=1)
        self.labelLength = Label(frame, text="0")
        self.labelLength.grid(row = 1, column=1)

        Label(frame, text="Total:").grid(row = 0, column=2)
        self.labelTotal = Label(frame, text="0")
        self.labelTotal.grid(row = 1, column=2)
        
        self.labelSentenceLeft = Label(frame, text="...")
        self.labelSentenceLeft.grid(row = 2, column=0, sticky=E)
        self.labelSentenceSpoken = Label(frame, text="...", foreground="red")
        self.labelSentenceSpoken.grid(row = 2, column=1)
        self.labelSentenceRight = Label(frame, text="...")
        self.labelSentenceRight.grid(row = 2, column=2, sticky=W, columnspan=2)   

        scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.labelQueueToSpeak = Label(frame, text="Queue to speak:").grid(row = 3, column=0, pady=4, padx=5, sticky=W)
        self.listboxQueueToSpeak = Listbox(frame, width=50, height=3, yscrollcommand=scrollbar.set)
        
        scrollbar.config(command=self.listboxQueueToSpeak.yview)
        self.listboxQueueToSpeak.grid( sticky=N+S+E+W, row = 4, column = 0, columnspan = 2 ,rowspan = 3, padx=3)
        scrollbar.grid(sticky=N+S+W, row = 4, column = 2, rowspan = 3)

        self.buttonPauze = Button(frame, text="Pauze", command=self.communicationProtocal.handlePauze)
        self.buttonPauze.grid(row = 4, column=3)

        self.buttonStop = Button(frame, text="Stop", command=self.communicationProtocal.restartProcess)
        self.buttonStop.grid(row = 5, column=3)

        self.buttonResume = Button(frame, text="Resume", command=self.communicationProtocal.handleResume)
        self.buttonResume.grid(row = 6, column=3)

        Label(frame, text="Text to say:").grid(row = 7, column=0, padx=3, sticky=W)

        self.stringVarTextToSay = StringVar()
        self.entryTextToSay = Entry(frame, textvariable=self.stringVarTextToSay, width=500)
        self.entryTextToSay.grid(row=8, column=0, columnspan=3, padx=3, sticky=W)
        self.stringVarTextToSay.set("Hello SAPI Speak Engine")
        self.entryTextToSay.bind('<Return>', self.CallBackReturnSay)

        self.buttonSay = Button(frame, text="Say", command=self.CallBackButtonSay)
        self.buttonSay.grid(row = 8, column=3)

        Label(frame, text="Recover action:").grid(row = 9, column=0, padx=3, sticky=W)
        self.recoverActionLabelText = "None"
        self.labelRecoverAction = Label(frame, text=self.recoverActionLabelText, foreground="blue")
        self.labelRecoverAction.grid(row = 10, column=0)   

        Label(frame, text="Voice speed:").grid(row = 9, column=1, sticky=W)
        self.buttonSpeedDown = Button(frame, text="Speed down", command=self.communicationProtocal.handleSpeedDown)
        self.buttonSpeedDown.grid(row = 10, column=1, padx=3, sticky=E)

        self.speedValue = 0
        self.intVarSpeed = IntVar()
        vcmd = (self.tkRoot.register(self.OnValidateEntrySpeakSpeed), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entrySpeakSpeed = Entry(frame, textvariable=self.intVarSpeed, validate="key", validatecommand=vcmd, width=5)
        self.entrySpeakSpeed.grid(row=10,column=2)
        self.entrySpeakSpeed.bind('<Return>', self.CallBackSetSpeed)

        self.buttonSpeedUp = Button(frame, text="Speed up", command=self.communicationProtocal.handleSpeedUp)
        self.buttonSpeedUp.grid(row = 10, column=3)

        Label(frame, text="voice:").grid(row = 11, column=0, padx=3, sticky=W)
        self.buttonPrevVoice = Button(frame, text="Prev voice", command=self.communicationProtocal.handlePrevVoice)
        self.buttonPrevVoice.grid(row = 12, column=0, padx=3, sticky=W)

        self.buttonNextVoice = Button(frame, text="Next voice", command=self.communicationProtocal.handleNextVoice)
        self.buttonNextVoice.grid(row = 12, column=3)

        self.currentVoice = StringVar(self.tkRoot)
        self.currentVoice.set(self.communicationProtocal.CurrentVoiceName)

        engine = pyttsx.init()
        voices = engine.getProperty("voices")
        voiceNames = list()
        for x in xrange(0, len(voices)):
            voiceNames.append(voices[x].name)
        self.optionMenuVoices = OptionMenu(frame, self.currentVoice, *tuple(voiceNames), command=self.CallBackOptionMenuVoices)
        self.optionMenuVoices.config(width=500)
        self.optionMenuVoices.grid(sticky=W, row = 12, column = 1)
     
        #hide if close button is clicked
        self.tkRoot.protocol("WM_DELETE_WINDOW", self.HideGui)
        self.tkRoot.after(1000/32, self.Update)
        self.tkRoot.mainloop()  

    def Update(self):
        wordLocation = self.communicationProtocal.OnWordStartLocation
        wordLength = self.communicationProtocal.OnWordLength
        wordTotal = self.communicationProtocal.OnWordTotal

        if wordLocation:
            self.labelStart.configure(text=wordLocation)
        else:
            self.labelStart.configure(text="0")
        self.labelLength.configure(text=wordLength)
        if wordLength != 0 and wordTotal == 0:
            self.labelTotal.configure(text="Introduce")    
        else:
            self.labelTotal.configure(text=wordTotal)

        if len(self.communicationProtocal.SpeakQueue) != 0:
            if (wordLocation < 25):
                self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[0:wordLocation])
            else:
                self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation-25:wordLocation])
            self.labelSentenceSpoken.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation:wordLocation+wordLength])
            if (wordTotal - wordLocation - wordLength < 25):
                self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordTotal])
            else:
                self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordLocation+wordLength+25])
        else:
            self.labelSentenceLeft.configure(text="...")
            self.labelSentenceSpoken.configure(text="...")
            self.labelSentenceRight.configure(text="...")

        if (self.communicationProtocal.SpeakQueue != None and self.listboxQueueToSpeak.size() != len(self.communicationProtocal.SpeakQueue)):
            self.listboxQueueToSpeak.delete(0,self.listboxQueueToSpeak.size())
            for x in xrange(0,len(self.communicationProtocal.SpeakQueue)):
                self.listboxQueueToSpeak.insert(x, str(x)+": "+self.communicationProtocal.SpeakQueue[x])

        if (self.currentVoice.get() != self.communicationProtocal.CurrentVoiceName):
            self.currentVoice.set(self.communicationProtocal.CurrentVoiceName)

        if self.speedValue != self.communicationProtocal.CurrentRate:
            self.intVarSpeed.set(self.communicationProtocal.CurrentRate) 
            self.speedValue = self.communicationProtocal.CurrentRate

        if self.recoverActionLabelText != self.communicationProtocal.recoveryTask:
            self.recoverActionLabelText = self.communicationProtocal.recoveryTask
            self.labelRecoverAction.configure(text=self.recoverActionLabelText)

        if self.GUIVisible != self.communicationProtocal.GUIVisible:
            # self.GUIVisible ? self.HideGui : self.ShowGui
            self.HideGui() if self.GUIVisible else self.ShowGui()
            
        self.tkRoot.after(1000/32,self.Update)

    def OnValidateEntrySpeakSpeed(self, d, i, P, s, S, v, V, W):
        try :
            int(S)
            return True
        except ValueError:
            return False

    def CallBackSetSpeed(self):
        self.communicationProtocal.handleSetSpeed(self.intVarSpeed.get())

    def CallBackReturnSay(self, event):
        self.CallBackButtonSay()

    def CallBackButtonSay(self):
        self.communicationProtocal.handleSay(self.stringVarTextToSay.get())
        
    def CallBackOptionMenuVoices(self, selectedItem):
        self.communicationProtocal.handleSetVoice(selectedItem)

    def Close(self):
        self.tkRoot.quit()
        
    def HideGui(self):
        self.GUIVisible = False
        self.communicationProtocal.GUIVisible = False
        self.tkRoot.withdraw()
        
    def ShowGui(self):
        self.GUIVisible = True
        self.communicationProtocal.GUIVisible = True
        self.tkRoot.deiconify()
Beispiel #16
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.
            
        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = range(columns)
            include_labels = False
        else:
            include_labels = True
        
        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i
            
            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)
            
        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Beispiel #17
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUIGlobals()

    def initUIGlobals(self):

        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

        f1 = Frame(self)
        f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W)

        f11 = LabelFrame(f1, text="Algorithms to Run")
        f11.grid(row=0, column=0)
        row = 0

        self.check_algs_value_list = []
        self.check_algs_map = {}
        for alg in algorithms:
            if alg == 'clean':
                continue
            check_alg_value = IntVar()
            check_alg = Checkbutton(f11,
                                    text=alg,
                                    variable=check_alg_value,
                                    justify=LEFT,
                                    width=25)
            check_alg.grid(row=row, column=0, sticky=W + E)
            self.check_algs_value_list.append(check_alg_value)
            self.check_algs_map[alg] = check_alg_value
            row += 1

        f111 = Frame(f11)
        f111.grid(row=row, column=0)

        button_checkall = Button(f111, text="All", command=self.checkall)
        button_checkall.grid(row=0, column=0, sticky=W + E)
        button_uncheckall = Button(f111, text="None", command=self.uncheckall)
        button_uncheckall.grid(row=0, column=1, sticky=W + E)

        row = 0

        f12 = Frame(f1)
        f12.grid(row=1, column=0, pady=20, sticky=S + W + E)

        f121 = LabelFrame(f12, text='Location of uPMU')
        f121.grid(row=0, column=0)

        self.radio_loc_string = StringVar()
        locations.append('Other Location')
        for loc in locations:
            radio_loc = Radiobutton(f121,
                                    text=loc,
                                    variable=self.radio_loc_string,
                                    value=loc,
                                    command=self.set_loc,
                                    justify=LEFT,
                                    width=25)
            radio_loc.grid(row=row, column=0, sticky=W + E)
            row += 1

        self.entry_otherloc = Entry(f121)

        f2 = Frame(self)
        f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W)

        f21 = LabelFrame(f2, text='Name of uPMU (raw)')
        f21.grid(row=0)
        row = 0

        f211 = Frame(f21)
        f211.grid(row=row)
        row += 1

        self.entry_namesearch = Entry(f211)
        self.entry_namesearch.grid(row=0, column=0, sticky=E + W)

        button_namesearch = Button(f211,
                                   text="Search",
                                   command=self.namesearch)
        button_namesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_namelist = Listbox(f21)
        self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
        self.lstbx_namelist.grid(row=row, sticky=W + E)
        row += 1

        f212 = Frame(f21)
        f212.grid(row=row)
        row += 1

        label_nameselected = Label(f212, text="Selected:")
        label_nameselected.grid(row=0, column=0)

        self.entry_nameselected = Entry(f212, state=DISABLED)
        self.entry_nameselected.grid(row=0, column=1, sticky=W + E)

        f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
        f22.grid(row=1, sticky=W + E, pady=10)
        self.entry_name = Entry(f22, width=30)
        self.entry_name.grid(row=0, column=0, sticky=E + W)

        f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
        f23.grid(row=2, pady=10)
        row = 0

        f231 = Frame(f23)
        f231.grid(row=row)
        row += 1

        self.entry_refnamesearch = Entry(f231)
        self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W)

        button_refnamesearch = Button(f231,
                                      text="Search",
                                      command=self.refnamesearch)
        button_refnamesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_refnamelist = Listbox(f23)
        self.lstbx_refnamelist.bind("<Double-Button-1>",
                                    self.refnamelist_select)
        self.lstbx_refnamelist.grid(row=row, sticky=W + E)
        row += 1

        f232 = Frame(f23)
        f232.grid(row=row)
        row += 1

        label_refnameselected = Label(f232, text="Selected:")
        label_refnameselected.grid(row=0, column=0)

        self.entry_refnameselected = Entry(f232, state=DISABLED)
        self.entry_refnameselected.grid(row=0, column=1, sticky=W + E)

        button_gen = Button(self,
                            text="Generate Files",
                            command=self.generate_files)
        button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E)

        self.pack()

    def generate_files(self):
        algs = []
        for alg in self.check_algs_map:
            if self.check_algs_map[alg].get() == 1:
                algs.append(alg)

        if self.radio_loc_string.get() == "Other Location":
            location = self.entry_otherloc.get()
        else:
            location = self.radio_loc_string.get()

        name_raw = self.entry_nameselected.get()
        name = self.entry_name.get()
        ref_name = self.entry_refnameselected.get()

        uuid_map = self.get_uuid_map(name_raw)
        reference_uuid_map = self.get_ref_uuid_map(ref_name)

        IniGenAutomation(location, name_raw, name, uuid_map, ref_name,
                         reference_uuid_map, algs)

    def namesearch(self):
        searchterm = self.entry_namesearch.get()
        if searchterm.contains("/"):
            loc = searchterm.split('/')
            searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1])
        else:
            searchphrase = '/upmu/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_namelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_namelist.insert(END, result)

    def refnamesearch(self):
        searchterm = self.entry_refnamesearch.get()
        searchphrase = '/Clean/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_refnamelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_refnamelist.insert(END, result)

    def search(self, searchterm, searchphrase):
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(
                searchphrase))
        results = connection.store_result()
        queried_data = {}
        result = results.fetch_row()
        while result != tuple():
            queried_data[result[0][0]] = result[0][1]
            result = results.fetch_row()
        search_results = set()
        for path in queried_data:
            dirs = path.split('/')
            if searchterm in dirs[2]:
                search_results.add(dirs[2])
        return search_results

    def set_loc(self):
        if self.radio_loc_string.get() == "Other Location":
            self.entry_otherloc.grid(sticky=W + E)
        else:
            self.entry_otherloc.grid_forget()

    def checkall(self):
        for check in self.check_algs_value_list:
            check.set(1)

    def uncheckall(self):
        for check in self.check_algs_value_list:
            check.set(0)

    def namelist_select(self, event):
        selected_index = self.lstbx_namelist.curselection()
        selected = self.lstbx_namelist.get(selected_index)
        self.entry_nameselected.configure(state=NORMAL)
        self.entry_nameselected.delete(0, END)
        self.entry_nameselected.insert(0, selected)
        self.entry_nameselected.configure(state=DISABLED)

    def refnamelist_select(self, event):
        selected_index = self.lstbx_refnamelist.curselection()
        selected = self.lstbx_refnamelist.get(selected_index)
        self.entry_refnameselected.configure(state=NORMAL)
        self.entry_refnameselected.delete(0, END)
        self.entry_refnameselected.insert(0, selected)
        self.entry_refnameselected.configure(state=DISABLED)

    def get_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-1]] = result[0][1]
            result = results.fetch_row()
        return uuid_map

    def get_ref_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-2]] = result[0][1]
            result = results.fetch_row()
        return uuid_map
Beispiel #18
0
class GUI(Frame):
    # In intialize the object, taking in the parent as in input parameter
    def __init__(self, parent):
        Frame.__init__(self, parent)
        # Initialize the api
        self.api = API()
        # Set the ip and port to communicate with the master server
        self.SERVER_IP = config.masterip
        self.SERVER_PORT = config.port
        # Set the initial server status to 0, will change to 1 if server is active
        # self.serverStatus = 0
        # Declare a list which will hold the files that have been flagged for deletion
        self.toDelete = []

        self.parent = parent
        # Initialize the GUI
        self.initUI()

    # Function to initialize UI
    def initUI(self):
        # Set the name of the UI window
        self.parent.title("Bennington File System Client")
        # Set the style using the default theme
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        # Set the "Open File" options
        self.file_opt = options = {}
        # Allow for any file to be choosable
        options["defaultextension"] = ""
        options["filetypes"] = ""
        # Set the directory window will open up to initially
        options["initialdir"] = "C:\\"
        options["parent"] = self

        # Create a label object which holds the text labeling the listbox
        lbl = Label(self, text="Bennington File System Files List", foreground="black")
        # Place the text in the top left
        lbl.grid(column=0, row=0, pady=4, padx=5)

        # Create the listbox, which will contain a list of all the files on the system
        self.area = Listbox(self, height=20)
        # Place the lisbox in the UI frame
        self.area.grid(row=1, column=0, columnspan=1, rowspan=10, padx=5, sticky=N + W + E + S)

        # Ask the master server which files it has, then populate the listbox with the response
        self.getFiles()

        # Create a button labeled 'Upload', and bind the uploadFile() function to it
        uploadbtn = Button(self, text="Upload", command=self.uploadFile)
        # Place the button in the UI frame
        uploadbtn.grid(row=1, column=3)

        # Create a button labeled 'Download', and bind the downloadFile() function to it
        dwnbtn = Button(self, text="Download", command=self.downloadFile)
        # Place the button in the UI frame
        dwnbtn.grid(row=2, column=3)

        # Create a button labeled 'Delete', and bind the deleteFile() function to it
        delbtn = Button(self, text="Delete", command=self.deleteFile)
        # Place the button in the UI frame
        delbtn.grid(row=3, column=3)

        # Create a button labeled 'Undelete', and bind the undeleteFile() function to it
        undelbtn = Button(self, text="Undelete", command=self.undeleteFile)
        # Place the button in the UI frame
        undelbtn.grid(row=4, column=3)

        # Create a button labeled 'Refresh List', and bind the getFiles() function to it
        refbtn = Button(self, text="Refresh List", command=self.getFiles)
        # Place the button in the UI frame
        refbtn.grid(row=5, column=3)

        # Create a button labeled 'Quit', and bind the exitProgram() function to it
        quitButton = Button(self, text="Quit", command=self.exitProgram)
        # Place the button in the UI frame
        quitButton.grid(sticky=W, padx=5, pady=4)

    # Downloads the active selection in the listbox
    def downloadFile(self):
        # Get the filename from the active listbox item
        fileName = self.currentSelectionFileName()
        # Call the API read function to get all the data associated with that file
        self.api.read(fileName, 0, -1, fileName)

    # Get the file name of the active selection in the listbox
    def currentSelectionFileName(self):
        # Get the index of the active selection
        index = self.currentSelectionIndex()
        # From the listbox object, pass in the index to get the filename
        fileName = self.area.get(index)
        return fileName

    # Get the index of the active selection in the listbox
    def currentSelectionIndex(self):
        # Get the index of the active selection
        index = self.area.curselection()[0]
        return index

    # Mark the active selection in the listbox for deletion
    def deleteFile(self):
        # Get the index of the current active selection
        index = self.currentSelectionIndex()
        # Get the filename of the current active selection
        filename = self.area.get(index)
        # Call the API function to mark file for deletion
        self.api.delete(filename)
        # Change the background color of the selection to denote it has been marked for deletion
        self.area.itemconfig(index, {"bg": "salmon"})
        # Append the filename to the toDelete list
        self.toDelete.append(filename)

    # Unmarks the active selection in the listbox for deletion
    def undeleteFile(self):
        # Get the index of the current active selection
        index = self.currentSelectionIndex()
        # Get the filename of the current active selection
        filename = self.area.get(index)
        # See if the file has been marked for deletion
        if filename in self.toDelete:
            # Call the API function to unmark file for deletion
            self.api.undelete(filename)
            # Change the background color of the selection to denote it is no longer marked for deletion
            self.area.itemconfig(index, {"bg": "white"})
            # Remove the filename from the toDelete list
            self.toDelete.remove(filename)

    # Upload a file from local machine to the distributed file system
    def uploadFile(self):
        # Get the file name and file path of the file the user wants to upload
        fileinfo = self.openFile()
        # Create a file with the filename provided
        self.api.create(fileinfo[0])
        # Append the file data from the file at the given file path
        self.api.append(fileinfo[0], fileinfo[1], 1)
        # Once that is complete, refresh the file list in the listbox
        self.getFiles()

    # Prompt the user to select a file
    def openFile(self):
        # Prompt the user to select a file, and store the returned file path
        filepath = tkFileDialog.askopenfilename(**self.file_opt)
        # Parse the filepath, and store the last element of the split as the file name
        filename = filepath.split("/")[-1]
        # Return a list containing the file name and file path
        return [filename, filepath]

    # Get the list of existing files from the master server
    def getFiles(self):
        try:
            # Get the file data using the API's fileList() function
            # At this stage, the data has lots of extra things in it, so it needs to be cleaned up
            data = self.api.fileList()
            # Split the string at every * character
            data = re.split("\*", data)
            # Declare an empty array which will hold the file names found from the parsing
            fileNames = []
            for item in data:
                # Split the element at every ^ character
                tempitem = re.split("\^", item)
                for thing in tempitem:
                    # If the element has a | in it, but is not just a |, then it is the filename
                    if "|" in thing and not thing == "|":
                        # Append the filename (with the | stripped out) to the fileNames list
                        fileNames.append(thing.strip("|"))

            # If the file is marked for deletion and still in the fileNames list
            # keep the file in the toDelete list
            temp = []
            for item in self.toDelete:
                if item in fileNames:
                    temp.append(item)

            # Update the toDelete list
            self.toDelete = temp

            # Remove all entries in the listbox
            self.area.delete(0, END)

            # Populate the listbox with the file names returned from the master
            for item in fileNames:
                self.area.insert(END, item)
                self.checkIfMarked(item)

        except Exception as e:
            raise e

    # Check to see if the provided file name exists in the toDelete list
    def checkIfMarked(self, fileName):
        # If the file name is in the toDelete list
        if fileName in self.toDelete:
            # Change the background color of the element to denote that it has been marked for deletion
            self.area.itemconfig(END, {"bg": "salmon"})

    # An exit function that quits the UI (any additional clean up pre-close should go in here)
    def exitProgram(self):
        self.quit()
class hillGUI(Frame):
    """The base class for the hill_calc GUI"""
    
    # This is the constructor for the GUI
    def __init__(self,master=None):
        # We begin by calling the base class's constructor first
        Frame.__init__(self,master)
    
        # We now have an empty window!
        
        # This command sets up a grid structure in the window
        self.grid()
        
        # This loop generates rows and columns in the grid
        for i in range(10):
            self.rowconfigure(i,minsize=10)
        for i in range(3):
            self.columnconfigure(i,minsize=10)
        
        # These are methods which appear below the constructor
        #self.defineUnits() # this sets up the units I'll be using in the converter
        self.createWidgets() # this places the elements (or widgets) in the grid
        
        # This command "binds" the user's click to a method (varChoice)
        # This method will determine which variable the user wants (Distance, Mass, Time)
        self.inputlist.bind("<Button-1>",self.__varChoice)
    
        # This is a similar command for the selection of unit
        self.unitlist.bind("<Button-1>",self.__unitChoice)
    
        # Finally, this bind reads in whatever value is in the text box when the user hits return
        # and carries out the unit conversion
        
        for i in range(len(self.inputfield)):
            self.inputfield[i].bind("<Return>",self.__calcConversion)
               
    def createUnitDict(self,mydict,mykeys,myvalues):
        '''This method takes a set of units and values, and creates a dictionary to store them in'''
        for i in range(len(myvalues)):
            mydict[mykeys[i]] = myvalues[i]
            
    def createWidgets(self):
        '''This method creates all widgets and adds them to the GUI'''
        
        # Create Widgets in order of appearance
        # This is not necessary, but makes code easier to read
        
        # Start with text telling user what to do
        self.varlabel = Text(self,height=1, width=20)
        self.varlabel.insert(END,"Which Variable?")
        
        # Place widget on the Frame according to a grid
        self.varlabel.grid(row=0,column=0,sticky=W)
        
        # Second text label asking user which units are being used
        self.unitlabel = Text(self,height=2,width=20)
        self.unitlabel.insert(END,"Planet Mass Units?\n (a=AU, Ms=Msol)")
        self.unitlabel.grid(row=0,column=1,sticky=W)
        
        # Third text label asking user for numerical value
        
        self.numlabel = Text(self,height=1, width=20)
        self.numlabel.insert(END,"Enter Variable Values")
        self.numlabel.grid(row=0,column=2,sticky=W)
        
        # This creates a list of options for the user to select
        self.inputlist = Listbox(self, height=4, selectmode=SINGLE)
      
        # Tuple of choices we're going to put in this list
        self.paramlist = ('Semi Major Axis', 'Planet Mass', 'Star Mass','Hill Radius')
        
        # Add each item separately
        for item in self.paramlist:
            self.inputlist.insert(END,item)
            
        # Add it to the grid    
        self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W)
        
        # Add a unit list (several combinations of units allowed)
        
        self.unitlist = Listbox(self, height=4,selectmode=SINGLE)
        self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W)
        
        self.massunits = ('Earth Masses','Neptune Masses', 'Jupiter Masses', 'Solar Masses') 
        self.massvalues = ( 3.00343905235e-06, 5.1500311727e-5, 0.000954588419846,1.0)
    
        self.massdict = {}
        self.createUnitDict(self.massdict, self.massunits,self.massvalues)
    
        for item in self.massunits:
            self.unitlist.insert(END,item)
    
        # Number Entry Boxes (and Text Labels)
        
        self.inputfield = []
        self.inputlabels = []
    
        irow = 0
        for i in range(len(self.paramlist)):
            
            irow = irow+1
            self.inputlabels.append(Text(self,height=1,width=20))
            self.inputlabels[i].insert(END,self.paramlist[i])
            self.inputlabels[i].grid(row=irow,column=2,sticky='N')
            irow = irow+1
            self.inputfield.append(Entry(self))
            self.inputfield[i].insert(END, "1.0")
            self.inputfield[i].grid(row =irow, column=2,sticky='N')
        
        # Text Output Box
        self.outputtext = Text(self, height=1, width=40)
        self.outputtext.grid(row=7,column=0,columnspan=2,sticky=W)
        self.outputtext.insert(END, "WAITING: ")
        # Create the Quit Button
        self.quitButton=Button(self,text='Quit',command=self.quit)
        self.quitButton.grid(row =8, column=0, sticky=W)
             

    # Event handler functions begin here    
    # This handler defines the choice of units available to the user, 
    # depending on selected variable
    
    def __varChoice(self, event):
        '''Handles the selection of variable: updates the list of units'''
        # Firstly, delete anything already in the units column
#        self.unitlist.delete(first=0,last=len(self.myvalues))
        num = 0
        
        # Identify which option was clicked on
        try:
            num = self.inputlist.curselection()[0]       
            self.varchoice = int(num)
            
        except:
            self.varchoice = 0
            return
        
        # Get the string associated with this choice
        selection= self.inputlist.get(self.varchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.inputlist.itemconfig(self.varchoice, selectbackground='red')

    def __unitChoice(self,event):
        '''Handles the selection of units'''
        num = 0
        # Find which number is selected
        try:
            num = self.unitlist.curselection()[0]       
            self.unitchoice = int(num)
            
        except:
            self.unitchoice = 0
            return
        
        # Get the string (i.e. which unit is selected)
        selection= self.unitlist.get(self.unitchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.unitlist.itemconfig(self.unitchoice, selectbackground='red')
        
        # If statement defines units being used
        
        self.massconvert = self.massdict[selection]
        
        
        # Remove all text in the output box, and tell user to define units
        self.outputtext.delete("1.0",index2=END)
        self.outputtext.insert(END, "Now Enter Values")
        
    # Handler takes current state of GUI, and calculates results
    def __calcConversion(self,event):
        '''This method takes the current state of all GUI variables, calculates one of four equations'''
        print 'Calculating'
        # Which variable has been selected for calculation?
        # This decides what equation to use
        
        a = self.inputfield[0].get()
        a=float(a)
        
        mp = self.inputfield[1].get()
        mp=float(mp)*self.massconvert
        
        ms = self.inputfield[2].get()
        ms = float(ms)
        
        rh = self.inputfield[3].get()
        rh = float(rh)
        
        if self.varchoice==0:
            a = rh*(3*ms/mp)*0.3333
            value = a
        elif self.varchoice==1:
            mp = 3*ms*rh**3/a**3
            value = mp
        elif self.varchoice==2:
            ms = mp*a**3/(3*rh**3)
            value = ms
        elif self.varchoice==3:
            rh = a *(mp/(3*ms))**0.3333
            value = rh
            
        
        # Remove all text in the output box and insert new stuff
        self.outputtext.delete("1.0",index2=END)
        self.outputtext.insert(END,str(self.paramlist[self.varchoice])+":    "+str(value))
Beispiel #20
0
class GUI:
	def __init__(self, master):
		self.master = master
		self.conf = Config()
		self.student_list = None
		self.save_filetype = StringVar()
		self.save_filetype.set('.txt')
		self.selected_section = StringVar()
		self.selected_section.set('ENGR 102 01')
		self.week = StringVar()
		self.week.set('42')
		self.student_listbox_contents = []
		self.attended_students = []

		# Set title
		master.title(self.conf.TITLE)

		# Header Label
		self.header_label_text = StringVar()
		self.header_label_text.set(self.conf.PROG_NAME)
		self.header_label = Label(master, textvariable=self.header_label_text, font=('Arial', 25))

		# File Import Label
		self.file_label_text = StringVar()
		self.file_label_text.set("Select student list Excel file:")
		self.file_label = Label(master, textvariable=self.file_label_text, font=('Arial', 15, 'bold'))

		# File Import Button
		self.file_button = Button(master, text="Import List", command=self.select_list)


		self.header_label.grid(row=0, column=1, columnspan=4, sticky=W+E)
		self.file_label.grid(row=1, column=0, columnspan=2, sticky=W)
		self.file_button.grid(row=1, column=2, columnspan=1, sticky=W+E)
		#self.reset_button.grid(row=3, column=1)
		self.render_student_listbox()
		self.render_attended_students_listbox()
		self.render_section_combobox()
		self.render_add_remove()
		self.render_export_section()

	def render_student_listbox(self):
		self.student_listbox_contents = []
		# Students Label
		self.student_label = Label(self.master, text="Select a Student:", font=('Arial', 15, 'bold'))

		# Students Listbox
		self.students_listbox = Listbox(self.master,
										selectmode=MULTIPLE,
										height=10)
		selected_section = self.selected_section.get()
		if self.student_list != None:
			for i,s in enumerate(self.student_list.students):
				if s.section == selected_section:
					self.students_listbox.insert(i, str(s))
					self.student_listbox_contents.append(s)
		self.student_label.grid(row=2, column=0, columnspan=1, sticky=W)
		self.students_listbox.grid(row=3, rowspan=13, column=0, columnspan=2, sticky=W+E)

	def render_attended_students_listbox(self):
		# Attended Students Label
		self.attended_students_label = Label(self.master, text="Attended Students:", font=('Arial', 15, 'bold'))
		
		# Attended Students Listbox
		self.attended_students_listbox = Listbox(self.master,
												 selectmode=MULTIPLE,
												 height=10,
												 width=20)
		for i,s in enumerate(self.attended_students):
			self.attended_students_listbox.insert(i, str(s))
		self.attended_students_label.grid(row=2, column=3, sticky=W)
		self.attended_students_listbox.grid(row=3, rowspan=13, column=3, columnspan=7, sticky=W+E)
			

	def render_section_combobox(self):
		sections = self.student_list.sections if self.student_list != None else []
		self.section_label = Label(self.master, text="Section:", font=('Arial', 15, 'bold'))
		self.section_combobox = ttk.Combobox(self.master,
											 textvariable=self.selected_section,
											 values=sections)
		self.section_combobox.bind("<<ComboboxSelected>>", self.sectionchange)
		self.section_label.grid(row=2, column=2)
		self.section_combobox.grid(row=3, column=2, sticky=W+E+N+S)

	def render_add_remove(self):
		self.add_button = Button(self.master, text="Add ->", command=self.add_students)
		self.remove_button = Button(self.master, text="<- Remove", command=self.remove_students)

		self.add_button.grid(row=4, column=2, sticky=W+E+N+S)
		self.remove_button.grid(row=5, column=2, sticky=W+E+N+S)

	def render_export_section(self):
		self.filetype_label = Label(self.master, text="Please select file type:", font=('Arial', 13, 'bold'))
		self.filetype_combobox = ttk.Combobox(self.master,
											  height=3,
											  textvariable=self.save_filetype,
											  values=['.xls', '.csv', '.txt'])
		self.filetype_combobox.bind("<<ComboboxSelected>>", self.save_filetype_change)
		self.week_label = Label(self.master, text="Please enter week:", font=('Arial', 13, 'bold'))
		self.week_entry = Entry(self.master, textvariable=self.week)
		self.export_button = Button(self.master, text="Export as File", command=self.export_list)

		self.filetype_label.grid(row=18, column=0, sticky=W)
		self.filetype_combobox.grid(row=18, column=1, sticky=E)
		self.week_label.grid(row=18, column=2)
		self.week_entry.grid(row=18, column=3, sticky=W+E)
		self.export_button.grid(row=18, column=4, sticky=W+E)


	def start(self):
		self.master.mainloop()

	def add_students(self):
		ixs = self.students_listbox.curselection()
		for i in ixs:
			self.attended_students.append(self.student_listbox_contents[i])
		self.attended_students = list(set(self.attended_students))
		self.render_attended_students_listbox()
		self.students_listbox.selection_clear(0, END)

	def remove_students(self):
		ixs = list(self.attended_students_listbox.curselection())
		ixs.reverse()
		for i in ixs:
			del self.attended_students[i]
		self.render_attended_students_listbox()

	def export_list(self):
		save_filename = "{}{}{}".format(self.selected_section.get(), self.week.get(), self.save_filetype.get())
		if self.save_filetype.get() == '.txt':
			try:
				with open(save_filename, 'w') as fd:
					for i,s in enumerate(self.attended_students):
						fd.write("{}\t{}\t{}\n".format(s.id, s.name, s.dept))
				fd.close()
			except:
				print("Unable to open file.")
		elif self.save_filetype.get() == '.xls':
			book = xlwt.Workbook()
			sheet = book.add_sheet('Sheet 1')
			sheet.write(0, 0, 'Id')
			sheet.write(0, 1, 'Name')
			sheet.write(0, 2, 'Dept.')
			for i,s in enumerate(self.attended_students):
				sheet.write(i+1, 0, s.id)
				sheet.write(i+1, 1, s.name_unicode)
				sheet.write(i+1, 2, s.dept)
			book.save(save_filename)
		else:
			raise BaseException('Filetype is not supported.')

	def select_list(self):
		self.list_file = tkFileDialog.askopenfilename(initialdir="~",
													  title="Import List",
													  filetypes = (("Excel Files","*.xls*"),("all files","*.*")))
		if self.list_file:
			self.student_list = Studentlist(self.list_file)
			self.render_student_listbox()
			self.render_attended_students_listbox()
			self.render_section_combobox()
			self.render_add_remove()
			self.render_export_section()

	def sectionchange(self, event):
		self.selected_section.set(self.section_combobox.get())
		self.attended_students = []
		self.render_student_listbox()
		self.render_attended_students_listbox()

	def save_filetype_change(self, event):
		self.save_filetype.set(self.filetype_combobox.get())
class WikinewsExplorer:
	def __init__(self, master):
		
		
		self.currentFileName = ""
		self.entDir = "/dev/shm/wikinews/entities/"
		self.llDir= "/dev/shm/wikinews/lang_links/"
		self.boolFileLoad = False
		self.entFiles = []
		self.llFiles = []
		self.wikinewsBaseURL = "http://en.wikinews.org/?curid="

		frame = Frame(master)
		frame.pack()
		
		frame.columnconfigure(1, weight=1)
		frame.columnconfigure(3, pad=7)
		frame.rowconfigure(3, weight=1)
		frame.rowconfigure(5, pad=7)
		
		self.lbEntFile = Label(frame, text="entities dir: ")
		self.lbEntFile.grid(row=0, column=0)
		
		self.lbLLFile = Label(frame, text="lang links dir: ")
		self.lbLLFile.grid(row=1, column=0)
		
		self.txtEntFile =Text(frame, height=1, width=40)
		self.txtEntFile.insert(INSERT, self.entDir)
		self.txtEntFile.grid(row=0, column=1)
		
		self.txtLLFile =Text(frame, height=1, width=40)
		self.txtLLFile.insert(INSERT, self.llDir)
		self.txtLLFile.grid(row=1, column=1)
		
		self.butLoad= Button(frame, text ="Load", command = self.readInputFiles)
		self.butLoad.grid(row=0, column=2, rowspan=2)
		
		
		
		self.scrollbar = Scrollbar(frame)
		self.lstArticles = Listbox(frame, yscrollcommand = self.scrollbar.set, width=50, height=20)
		self.lstArticles.grid( row=2, column=0, columnspan=2, sticky=W)
		self.lstArticles.bind("<<ListboxSelect>>", self.onArticleSelect)
		
		self.scrollbar.grid(row=2, column=3, sticky=W)
		self.scrollbar.config( command = self.lstArticles.yview )
		
		self.butOpenBrowser = Button(frame, text="View article in browser", command=self.openInFirefox)
		self.butOpenBrowser.grid(row=3, column=0)
	
	
	
		self.lblSearchTitle = Label(frame, text="search article ID: ")
		self.lblSearchTitle.grid(row=4, column=0, sticky=E)
		
		self.txtSearchTitle = Text(frame, height=1, width=30)
		self.txtSearchTitle.grid(row=4, column=1)
		
		
		self.butSearchTitle = Button(frame, text="Go", command=self.searchTitle)
		self.butSearchTitle.grid(row=4, column=2, sticky=W)
		
		self.scrollbar2 = Scrollbar(frame)		
		self.lstContent = Listbox(frame, yscrollcommand=self.scrollbar2.set, width=100, height=20)
		self.lstContent.grid(row=0, column=3, rowspan=5)
		self.lstContent.bind("<<ListboxSelect>>", self.onEntitySelect)
		self.scrollbar2.grid(row=0, column=3, sticky=W)
		self.scrollbar2.config( command = self.lstContent.yview )
		
		
		self.scrollbar3 = Scrollbar(frame)		
		self.lstWikiLinks = Listbox(frame, yscrollcommand=self.scrollbar3.set, width=70, height=13)
		self.lstWikiLinks.grid(row=5, column=3, sticky=W)
		self.scrollbar3.grid(row=5, column=3, sticky=W)
		self.scrollbar3.config( command = self.lstWikiLinks.yview )
	
	
	
	def onEntitySelect(self, event):
		""" fetch entity info directly from wikipedia """
		# enpty content box
		self.lstWikiLinks.delete(0, END)
		widg = event.widget
		index = int(widg.curselection()[0])
		entityString = widg.get(index)
		print 'selected entity %d: "%s"' % (index, entityString)	
		
		entityName = extractEntityName(entityString)
		self.lstWikiLinks.insert(END, "en.wikipedia.org/wiki/" + entityName) 
		self.lstWikiLinks.insert(END, "======= links to the following wiki entities: ========================") 
		
		url = "http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=" + entityName +"&prop=links"
		print "HTTP request: ", url
		xmlResponseTree = None
		try:
			response = urllib2.urlopen(url).read()
			xmlResponseTree = ET.fromstring(response)
		except:
			print " \n ERROR: ", str(sys.exc_info()[0])
								
		
		if xmlResponseTree != None:
			for link in xmlResponseTree.iter("pl"):
# 				item = "en.wikipedia.org/wiki/" + 
				self.lstWikiLinks.insert(END, link.attrib.get("title"))
		else:
			print " xml response tree empty "
		
	def onArticleSelect(self, event):
		
		# enpty content boxes
		self.lstContent.delete(0, END)
		self.lstWikiLinks.delete(0,END)
		
		widg = event.widget
		index = int(widg.curselection()[0])
		fileName = widg.get(index)
		self.currentFileName = fileName
		print 'selected item %d: "%s"' % (index, fileName)	
		
		# load the entity and lang-link files and display in the content box
		entFile = self.entDir + fileName
		llFile = self.llDir + fileName
		ents = open(entFile)
		lls = open(llFile)

		self.lstContent.insert(END, "===== contained Entities =================================")
		
		for ent in ents:
			self.lstContent.insert(END, ent.strip())

		self.lstContent.insert(END, " ")			
		self.lstContent.insert(END, "===== contained Language Links ===========================")
		
		for ll in lls:
			self.lstContent.insert(END, ll.strip())
			
		ents.close()
		lls.close()
		
	def openInFirefox(self):
		wikinewsBase = self.wikinewsBaseURL
		
		articleID = self.lstArticles.get(ACTIVE).split("-")[0]
		
		"""
		commandLinux = "firefox " + wikinewsBase + articleID + " &"	
		commandMacOS = "open -a firefox -g " + wikinewsBase + articleID
		commandWindows = 'firefox.exe \"' +  wikinewsBase + articleID +  '\"'
	
	
		if os.uname()[0] == "Linux":
			print "Linux: starting firefox"
			os.system(commandLinux)
		elif os.uname()[0] == "Mac":
			print "Mac: starting firefox"
			os.system(commandMacOS)
		elif os.name == "Windows":
			print "Windows: starting firefox"
			os.system(commandWindows)
		else:
			tkMessageBox.showinfo("Wikinews Explorer", "Strange OS detected: " + os.uname()[0] + "\n can't start Firefox")
		"""
		if not webbrowser.open_new(wikinewsBase + articleID):
			tkMessageBox.showinfo("Wikinews Explorer", "start browser")
			
		return
	
	def searchTitle(self):
		print "search: files loaded?", self.boolFileLoad
		targetString = self.txtSearchTitle.get(1.0, END).strip()
		if self.boolFileLoad:
			i = 0
			for fileName in self.entFiles:
				if targetString.lower() in fileName.lower():
					# focus first result and exit
					
					self.lstArticles.selection_set(i, i)
					self.lstArticles.see(i)
				
					
					print "--- found: ", i, " ", fileName
					break
				i += 1
				
		else:
			tkMessageBox.showinfo("Wikinews Explorer", "Input files not loaded")
	
	
	def readInputFiles(self):
		self.entDir = self.txtEntFile.get(1.0, END).strip()
		self.llDir = self.txtLLFile.get(1.0, END).strip()

		if not os.path.exists(self.entDir):
			tkMessageBox.showinfo( "Wikinews Explorer", self.entDir + "\ndoes not exist")
			self.boolFileLoad = False
			return
		if not os.path.exists(self.llDir):
			self.boolFileLoad = False
			tkMessageBox.showinfo( "Wikinews Explorer", self.llDir + "\ndoes not exist")
			return	
		
		# no return until here, it's fine
		self.entFiles = os.listdir(self.entDir)
		self.llFiles = os.listdir(self.llDir)
		
		if len(self.entFiles) != len(self.llFiles):
			tkMessageBox.showinfo("Wikinews Explorer", "something's wrong: \n  article number mismatch: " + len(self.entFiles) + " != " + len(self.llFiles))
			self.boolFileLoad = False
			return
		else:
			print "files count ok: ", str(len(self.entFiles)), " == ", str(len(self.llFiles))
			for fileName in self.entFiles:
				self.lstArticles.insert(END, fileName)
			self.boolFileLoad = True # file loading ok
		
		print "files loaded?", self.boolFileLoad
Beispiel #22
0
main.geometry("+50+150")
frame1 = ttk.Frame(main, padding=(3, 3, 12, 12))
frame1.grid(column=0, row=0, sticky=('N', 'S', 'E', 'W'))

values = StringVar()
values.set("Voltage Calcium CalciumER")

lbl = Label(frame1, text="Options")
lbl.grid(column=0, row=0)

lstbox = Listbox(frame1,
                 listvariable=values,
                 selectmode='multiple',
                 width=20,
                 height=3)
lstbox.grid(column=1, row=0, columnspan=2)

lbl2 = Label(frame1, text="How Many Branchtype")
lbl2.grid(column=0, row=1)

txtbox = Entry(frame1)
txtbox.grid(column=1, row=1)


def initalwrite():
    global reslist
    reslist = list()
    selection = lstbox.curselection()
    for i in selection:
        ent = lstbox.get(i)
        reslist.append(ent)
Beispiel #23
0
class ui:
    def __init__(self, r):
        self.__root = r         # root of program
        self.__load_icon = ImageTk.PhotoImage(file=constants.PATH + r'/ico/load.png')

        self.__master_file = ""         # file to merge into
        self.__convert_list = []        # holds list of files to be converted
        self.__sub_list = []            # holds list of files to compare against master

        self.__convert_opts = None      # Top level for additional convert options
        self.__nth_number = None        # Entry box for holding nth number for convert option
        self.__lbl_file = None          # Label which holds name of master file in top left corner
        self.__convert_lbox = None      # Listbox for holding list of files to convert
        self.__sub_lbox = None          # Listbox for holding list of files to compare against master file

        self.__match_rule = IntVar()        # the rule on how to merge files into master
        self.__column_rule = IntVar()       # which column to use for comparing
        self.__column_rule.set(1)           # initial value is the first column
        self.__column_match_rule = IntVar() # which column to compare for a match
        self.__column_match_rule.set(1)     # initial value is the first column

        # public window dimensions
        self.width = self.__root.winfo_screenwidth()
        self.height = self.__root.winfo_screenheight()

        # upper left side of screen
        self.__master_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID,
                                    height=constants.HEIGHT/4)
        self.__master_frame.grid_propagate(False)
        self.__master_frame.grid(row=0, column=0, padx=5, pady=5)

        # lower left side of screen
        self.__convert_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID,
                                     height=constants.HEIGHT - constants.HEIGHT/4 - 20)
        self.__convert_frame.pack_propagate(False)
        self.__convert_frame.grid(row=1, column=0, padx=5, pady=5)

        # right side of screen
        self.__sub_frame = Frame(self.__root, width=constants.WIDTH - constants.WIDTH/3 - 20, borderwidth=1, relief=SOLID,
                                 height=constants.HEIGHT - 10)
        self.__sub_frame.grid_propagate(False)
        self.__sub_frame.grid(row=0, column=1, padx=5, pady=5, columnspan=2, rowspan=2)

    def setup_gui(self):
        """
        Top level function which is called from main(). Sets window title and dimensions, then calls three sub
        routines which created and setup the rest of the GUI
        """
        self.__root.title('db_swapper')
        x = (self.width - constants.WIDTH) / 2
        y = (self.height - constants.HEIGHT) / 2

        self.__root.geometry('%dx%d+%d+%d' % (constants.WIDTH, constants.HEIGHT, x, y))

        self.create_master_frame()
        self.create_convert_frame()
        self.create_sub_frame()

    def create_master_frame(self):
        """
        Initialize the GUI for the upper left
        """
        load_btn = Button(self.__master_frame, image=self.__load_icon, width=20, height=20,
                          command=self.import_master_file)
        load_btn.grid(row=1, column=1, padx=5, pady=5)

        Label(self.__master_frame, text="Master List").\
            grid(row=1, column=2, padx=5, pady=5)

        self.__lbl_file = Label(self.__master_frame, bg="white", relief=SUNKEN, width=26)
        self.__lbl_file.grid(row=2, column=1, padx=5, pady=5, columnspan=3)

        # adding these weights allows the GUI to align itself within the frame
        self.__master_frame.grid_rowconfigure(0, weight=1)
        self.__master_frame.grid_columnconfigure(3, weight=1)
        self.__master_frame.grid_rowconfigure(3, weight=1)
        self.__master_frame.grid_columnconfigure(0, weight=1)

    def create_convert_frame(self):
        """
        Initialize the GUI for the lower left side of the program
        """
        Label(self.__convert_frame, text="Files to split").\
            pack(side=TOP)

        self.__convert_lbox = Listbox(self.__convert_frame, width=29, height=12, selectmode=EXTENDED)
        self.__convert_lbox.pack(side=TOP)

        convert = Button(self.__convert_frame, text="Convert", command=self.choose_convert)
        remove = Button(self.__convert_frame, text="Remove Item",
                        command=lambda: self.remove_item(self.__convert_lbox, self.__convert_list))
        load = Button(self.__convert_frame, image=self.__load_icon, width=27, height=20,
                      command=lambda: self.import_and_append_file(self.__convert_lbox, self.__convert_list))

        convert.pack(side=LEFT, padx=(10,5), pady=5)
        remove.pack(side=LEFT, padx=(0,5))
        load.pack(side=LEFT)

    def create_sub_frame(self):
        """
        Initialize the GUI for the right side of the program
        """
        self.__sub_lbox = Listbox(self.__sub_frame, width = 30, height = 23, selectmode=EXTENDED)
        self.__sub_lbox.grid(row=0, column=0, rowspan=20, padx=5, pady=5)

        Label(self.__sub_frame, justify=LEFT,
                    text = "To use db_swapper first load a\nmaster list, the database you wish\nto"
                           " merge files into. Then add\nany sub files to compare against\nand hit"
                           " 'merge'. Use convert to\nsplit a large file into smaller files\n"
                           "using the popup options").\
            grid(row=1, column=1, rowspan=20, columnspan=4, sticky=N+W)

        Label(self.__sub_frame, text="Merge into master if a matched\nsub item is:", justify=LEFT).\
            grid(row=11, column=1, sticky=W, rowspan=3, columnspan=4)

        Radiobutton(self.__sub_frame, text="Less", variable=self.__match_rule, value=constants.LESS).\
            grid(row=14, column=1, sticky=W)
        Radiobutton(self.__sub_frame, text="Greater", variable=self.__match_rule, value=constants.GREATER).\
            grid(row=14, column=2, sticky=W)
        Radiobutton(self.__sub_frame, text="Equal", variable=self.__match_rule, value=constants.EQUAL).\
            grid(row=14, column=3, sticky=W)

        Label(self.__sub_frame, text="Column to match with:", justify=LEFT).\
            grid(row=15, column=1, sticky=W, columnspan=4)

        OptionMenu(self.__sub_frame, self.__column_match_rule,1,2,3,4,5,6,7,8,9,10).\
            grid(row=15, column=3, sticky=E)

        Label(self.__sub_frame, text="Column to compare to:", justify=LEFT).\
            grid(row=16, column=1, sticky=W, columnspan=4)

        OptionMenu(self.__sub_frame, self.__column_rule,1,2,3,4,5,6,7,8,9,10).\
            grid(row=16,column=3,sticky=E)

        # Merge button
        Button(self.__sub_frame, text="Merge", width=24, command=self.merge_files).\
            grid(row=19, column=1, padx=(0,5), columnspan=4, sticky=W)

        # Load button for merge frame
        Button(self.__sub_frame, image=self.__load_icon, width=73, height=35,
                      command=lambda: self.import_and_append_file(self.__sub_lbox, self.__sub_list)).\
            grid(row=18, column=1, padx=(0,0), sticky=W, columnspan=2)

        # Remove button for merge frame
        Button(self.__sub_frame, text="Remove Item", width=10, height=2,
                        command=lambda: self.remove_item(self.__sub_lbox, self.__sub_list)).\
            grid(row=18, column=2, padx=(40,0), sticky=W, columnspan=2)

    def choose_convert(self):
        """
        Creates a window that prompts the user for what type of file conversion to use. The user may
        either elect to split a file based upon it's matching first column, or split a file based
        on every Nth item, which is entered in this window.
        """
        self.__convert_opts = Toplevel()
        self.__convert_opts.title("Conversion method")

        # hard coded dimensions
        x = (self.width - 250) / 2
        y = (self.height - 100) / 2
        self.__convert_opts.geometry('%dx%d+%d+%d' % (250, 100, x, y))

        Label(self.__convert_opts, text="Which method to split by?").grid(row=0, column=0, columnspan=4)

        Button(self.__convert_opts, text="First Column", command=self.convert_files).\
            grid(row=1, column=0, sticky=W, padx=5, pady=5)
        Button(self.__convert_opts, text="By every Nth Entry", command=self.convert_files_nth).\
            grid(row=2, column=0, sticky=W, padx=5)
        self.__nth_number = Entry(self.__convert_opts)
        self.__nth_number.grid(row=2,column=1)


    def import_master_file(self):
        """
        Method called with the user chooses to import a master file, opens a dialog for the user to browse and
        select a file, then displays the file chosen within a label and sets the internal variable __master_file
        """
        file_types = [('Semicolon Separated Text Files', ('*.csv', '*.txt')), ('All Files', '*')]
        dlg = tkFileDialog.Open(filetypes=file_types)
        fl = dlg.show()
        if fl != '':
            self.__master_file = fl
            segments = self.__master_file.rpartition('/')
            self.__lbl_file.config(text=segments[2])

    def import_and_append_file(self, lbox, lbox_list):
        """
        Method to prompt a user for a selection of files, and append those files to a list box and internal list.
        Takes a Listbox and list object, and inserts the selected filenames into the Listbox and the full path
        filenames into the list
        """
        file_types = [('Semicolon Separated Files', ('*.csv', '*.txt')), ('All Files', '*')]
        files = list(tkFileDialog.askopenfilenames(filetypes=file_types))
        if files is not None:
            for file in files:
                lbox.insert(END, file.rpartition('/')[2])
                lbox_list.append(file)

    def remove_item(self, lbox, lbox_list):
        """
        Removes any items currently selected in a listbox passed. Also ensures to remove that item from the internal
        list passed.
        """
        indexes = list(lbox.curselection())

        # Remove in reversed order so the indices do not change as we delete
        for idx in reversed(indexes):
            lbox.delete(idx)
            del lbox_list[idx]

    def convert_files(self):
        """
        Splits a large csv file into smaller csv files based upon their first column
        """
        logger.info('Converting file(s) based upon first column')
        self.__convert_opts.destroy()

        if not self.__convert_list:
            logger.error('No files to convert')
            return

        # loop through each file in the Listbox
        for item in self.__convert_list:
            with open(item, 'rb') as file:
                # open the file and create a reader
                master_reader = csv.reader(file, delimiter=constants.DELIMITER)
                curr = None     # keeps track of current running subject
                segment = []    # rows are appended to this list as long as the subject remains the same
                for row in master_reader:
                    # if curr is empty, start a new subject
                    if curr is None: curr = row[0]
                    if curr != row[0]:
                        # sometimes the csv file contains a header sep, if so then ignore it
                        if 'sep=' in curr:
                            curr = None
                            segment=[]
                            continue
                        # create a csv file with the name of the subject
                        with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out:
                            # write out the delimiter helper, then write the segment list
                            write_out.write('sep='+constants.DELIMITER + '\n')
                            writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                            for seg in segment:
                                writer.writerow(seg)
                        segment = []
                        curr = row[0]       # if row doesn't match previous curr, it becomes the new curr
                        segment.append(row) # append this row to the start of the new curr
                    else:
                        segment.append(row)
                # if segments has data for a subject at the end of the loop, write the data to the subject
                if list is not None:
                    with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out:
                        write_out.write('sep='+constants.DELIMITER + '\n')
                        writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                        for seg in segment:
                            writer.writerow(seg)

        logger.info('FINISHED, split files can be found in installation directory')

    def convert_files_nth(self):

        if not self.__convert_list:
            logger.error('No files to convert')
            return

        # if the text in the entry box cannot be converted, display error
        try:
            num = int(self.__nth_number.get())
        except:
            logger.error('Invalid number of entries given: \'%s\'' % self.__nth_number.get())
            self.__convert_opts.destroy()
            return

        self.__convert_opts.destroy()
        logger.info('Converting file(s) based upon every nth item')
        for item in self.__convert_list:
            with open(item, 'rb') as file:
                master_reader = csv.reader(file, delimiter=constants.DELIMITER)
                count = 0
                parts = 0
                segment = []
                for row in master_reader:
                    if('sep=' in '\t'.join(row)):
                        continue
                    count += 1
                    segment.append(row)
                    if(count == num):
                        with open(constants.PATH + '/%spart%d' %
                                ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out:
                            write_out.write('sep='+constants.DELIMITER + '\n')
                            writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                            for seg in segment:
                                writer.writerow(seg)
                        segment = []
                        parts += 1
                        count = 0
            if count != 0:
                with open(constants.PATH + '/%spart%d' % ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out:
                    write_out.write('sep='+constants.DELIMITER + '\n')
                    writer = csv.writer(write_out, delimiter=constants.DELIMITER)
                    for seg in segment:
                        writer.writerow(seg)

        logger.info('FINISHED, split files can be found in installation directory')




    def merge_files(self):
        """
        Merges small files into a master file based upon a matching criteria. all files in __sub_list are compared
        to __master_file.
        """
        compare_col = self.__column_rule.get() - 1
        match_col = self.__column_match_rule.get() - 1
        rule = self.__match_rule.get()

        if rule == 0:
            logger.error('Rule not selected, select LESS, GREATER, or EQUAL')
            return

        if self.__master_file == "":
            logger.error('No master file selected')
            return

        if self.__sub_list is None:
            logger.error('No sub files selected')
            return

        s = ""
        if rule == constants.LESS: s = "LESS than"
        elif rule == constants.GREATER: s = "GREATER than"
        elif rule == constants.EQUAL: s = "EQUAL to"
        logger.info('beginning merge, using column #%d for finding matching rows' % match_col)
        logger.info('Checking column #%d to decide whether to overwrite rows' % compare_col)
        logger.info('overwriting will occur if child row is %s parent row' % s)

        # move master file into a list for comparing and overwriting
        master_list = []
        with open(self.__master_file, 'rb') as m_file:
            master_reader = csv.reader(m_file, delimiter=constants.DELIMITER)
            for row in master_reader:
                master_list.append(row)

        # run each sub file through the master list to swap
        changed = False
        for sub_file in self.__sub_list:
            sub_list = []
            with open(sub_file, 'rb') as file:
                sub_reader = csv.reader(file, delimiter=constants.DELIMITER)
                for sr in sub_reader:
                    sub_list.append(sr)

            row_num = 1
            non_decimal = re.compile(r'[^\d.]+')
            for row in master_list:
                for sub_row in sub_list:
                    if str(sub_row[match_col]).lower() == str(row[match_col]).lower() and \
                        (not 'sep=' in str(sub_row[match_col])):
                        ms_val = int(float(non_decimal.sub('',row[compare_col])))
                        sb_val = int(float(non_decimal.sub('',sub_row[compare_col])))
                        if rule == constants.LESS and sb_val < ms_val or \
                           rule == constants.GREATER and sb_val > ms_val or \
                           rule == constants.EQUAL and sb_val == ms_val:
                            changed = True
                            logger.info('row #%d: SWAPPING %s in master list for %s in %s' %
                                        (row_num, ','.join(row), ','.join(sub_row), sub_file.rpartition('/')[2]))
                            master_list[(row_num-1)] = sub_row
                row_num+= 1

        # write back master list into master file with new changes
        if changed:
            with open((self.__master_file.rpartition('/')[2])[:-4] + '_swapped.csv', 'wb') as m_file:
                master_writer = csv.writer(m_file, delimiter=constants.DELIMITER)
                for row in master_list:
                    master_writer.writerow(row)

        logger.info('FINISHED, swapped file located in installation directory')
Beispiel #24
0
class TkApp:
    def __init__(self, master, mech):
        self.mech = mech
        frame = Frame(master)
        frame.grid()
        rct_label = Label(frame, text='Select Reactants')
        rct_label.grid(column=1, row=1)
        and_or = Label(frame, text='AND/OR')
        and_or.grid(column=3, row=1)
        prod_label = Label(frame, text='Select Products')
        prod_label.grid(column=4, row=1)
        what_to_do = Label(frame, text='Execute')
        what_to_do.grid(column=6, row=1)
        reactants_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.reactants = Listbox(frame,
                                 selectmode=EXTENDED,
                                 exportselection=0,
                                 yscrollcommand=reactants_scrollbar.set)
        self.reactants.grid(column=1, row=2)
        reactants_scrollbar.config(command=self.reactants.yview)
        reactants_scrollbar.grid(column=2, row=2, sticky=N + S)

        self.logical_and = IntVar()
        self.logical_and.set(1)
        c = Checkbutton(frame, text="AND", variable=self.logical_and)
        c.grid(column=3, row=2)

        products_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.products = Listbox(frame, selectmode=EXTENDED, exportselection=0)
        self.products.grid(column=4, row=2)
        products_scrollbar.config(command=self.products.yview)
        products_scrollbar.grid(column=5, row=2, sticky=N + S)

        self.method_list = Listbox(frame,
                                   selectmode=EXTENDED,
                                   exportselection=0)
        self.method_list.grid(column=6, row=2)
        #self.methods = [k for k in dir(self.mech) if k[:1] != '_' and isinstance(getattr(self.mech, k), MethodType)]
        self.methods = [
            'plot_rxns', 'find_rxns', 'print_rxns', 'print_irrs',
            'print_net_rxn', 'plot_proc'
        ]
        method_labels = [
            'Plot Reactions', 'Show Rxn Ids', 'Print Rxns', 'Print IRRs',
            'Print Net Rxn', 'Process Plot'
        ]
        for method in method_labels:
            self.method_list.insert(END, method)

        species_keys = self.mech.species_dict.keys()
        species_keys.sort()
        self.species_objects = [
            self.mech.species_dict[spc] for spc in species_keys
        ]

        for spc in species_keys:
            self.reactants.insert(END, spc)
            self.products.insert(END, spc)
        self.execute_button = Button(frame, text="go", command=self.execute)
        self.execute_button.grid(column=6, row=4)

    def _get_species(self, list):
        items = list.curselection()
        try:
            items = map(int, items)
        except:
            pass
        items = map(lambda i, d=self.species_objects: d[i], items)
        return items

    def get_reactants(self):
        return self._get_species(self.reactants)

    def get_products(self):
        return self._get_species(self.products)

    def get_methods(self):
        items = self.method_list.curselection()
        try:
            items = map(int, items)
        except:
            pass
        items = map(lambda i, d=self.methods: d[i], items)
        return items

    def execute(self):
        os.system('clear')
        reactants = self.get_reactants()
        products = self.get_products()
        logical_and = bool(self.logical_and.get())
        methods = self.get_methods()
        kwds = dict(reactants=reactants,
                    products=products,
                    logical_and=logical_and)
        for method in methods:
            if method == 'plot_proc':
                thiskwds = {}
                thiskwds['species'] = (reactants + products)[0]
            else:
                thiskwds = kwds.copy()
            getattr(self.mech, method)(**thiskwds)
Beispiel #25
0
class ConditionalsEditor:
    def __init__(self, my_window, conditionals, close_callback):
        #Tk.__init__(self)
        self.my_window = my_window
        self.my_window.title("Condition Editor")
        self.close_callback = close_callback
        self.conditionals = conditionals

        shared_pad_x = 3
        shared_pad_y = 3

        main_frame = Frame(self.my_window)
        main_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        image_path = "images"
        image_files = [
            f for f in os.listdir(image_path) if
            os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png")
        ]
        self.icons = {}
        for image_file in image_files:
            self.icons[os.path.splitext(
                os.path.basename(image_file))[0]] = PhotoImage(
                    file=os.path.join(image_path, image_file))

        up_down_button_frame = Frame(main_frame)

        self.up_button = Button(up_down_button_frame,
                                state="disabled",
                                text="Move up",
                                image=self.icons["gtk-go-up"],
                                command=self.up_pressed)
        self.up_button.grid(column=0, row=0, sticky=(E))

        self.down_button = Button(up_down_button_frame,
                                  state="disabled",
                                  text="Move down",
                                  image=self.icons["gtk-go-down"],
                                  command=self.down_pressed)
        self.down_button.grid(column=0, row=1, sticky=(E))

        up_down_button_frame.grid(column=0, row=0, sticky=(E))

        condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1)
        condition_list.grid(column=1,
                            row=0,
                            sticky=(N, S, E, W),
                            padx=shared_pad_x,
                            pady=shared_pad_y,
                            columnspan=1)
        self.condition_list_scrollbar = Scrollbar(condition_list)

        self.state_listbox = Listbox(condition_list,
                                     relief=FLAT,
                                     exportselection=False,
                                     borderwidth=0,
                                     highlightthickness=0,
                                     yscrollcommand=self.state_listbox_scroll,
                                     activestyle="none")
        self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S))
        self.state_listbox.bind("<<ListboxSelect>>",
                                self.state_listbox_selected)

        self.condition_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.condition_listbox_scroll,
            activestyle="none")
        self.condition_listbox.grid(column=1,
                                    row=0,
                                    sticky=(N, S, E, W),
                                    padx=0)
        self.condition_listbox.bind("<<ListboxSelect>>",
                                    self.condition_listbox_selected)

        self.execution_target_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.execution_target_listbox_scroll,
            activestyle="none")
        self.execution_target_listbox.grid(column=2,
                                           row=0,
                                           padx=0,
                                           sticky=(N, S))
        self.execution_target_listbox.bind(
            "<<ListboxSelect>>", self.execution_target_listbox_selected)

        self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S))
        self.condition_list_scrollbar.config(
            command=self.condition_list_scrollbar_callback)
        condition_list.grid_rowconfigure(0, weight=1)

        for conditional in self.conditionals:
            self.state_listbox.insert(END, conditional[0])
            self.condition_listbox.insert(END, conditional[1])
            self.execution_target_listbox.insert(END, conditional[2])
        #for i in range(5):
        #    self.state_listbox.insert(END, "Foo %d"%i)
        #    self.condition_listbox.insert(END, "Bar %d"%i)
        #    self.execution_target_listbox.insert(END, "Baz %d"%i)

        if_label = Label(main_frame, text="If:", padx=10)
        if_label.grid(column=0, row=1, sticky=(N, E))
        self.if_text_variable = StringVar()
        if_entry = Entry(main_frame, textvariable=self.if_text_variable)
        if_entry.grid(
            column=1,
            row=1,
            sticky=(E, W),
            padx=shared_pad_x,
            pady=shared_pad_y,
        )

        then_label = Label(main_frame, text="Then:", padx=10)
        then_label.grid(column=0, row=2, sticky=(N, E))
        self.then_entry = Text(main_frame)
        self.then_entry.grid(
            column=1,
            row=2,
            sticky=(N, S, E, W),
            padx=shared_pad_x,
            rowspan=2,
        )

        option_frame = Frame(main_frame)
        execution_target_label = Label(option_frame, text="Execution target:")
        execution_target_label.grid(column=0,
                                    row=0,
                                    sticky=(N, W),
                                    pady=(10, shared_pad_y))
        self.execution_target = StringVar()
        self.execution_target.set("Debugger")
        debugger_radiobutton = Radiobutton(option_frame,
                                           text="Debugger",
                                           variable=self.execution_target,
                                           value="Debugger")
        debugger_radiobutton.grid(column=0, row=1, sticky=(N, W))
        python_radiobutton = Radiobutton(option_frame,
                                         text="Python",
                                         variable=self.execution_target,
                                         value="Python")
        python_radiobutton.grid(column=0, row=2, sticky=(N, W))
        state_label = Label(option_frame, text="State")
        state_label.grid(column=0,
                         row=3,
                         sticky=(N, W),
                         pady=(10, shared_pad_y))

        self.active_checkbutton = StringVar()
        self.active_checkbutton.set("Enabled")
        active_checkbutton = Checkbutton(option_frame,
                                         text="Enabled",
                                         variable=self.active_checkbutton,
                                         onvalue="Enabled",
                                         offvalue="Disabled")
        active_checkbutton.grid(column=0, row=4, sticky=(N, W))
        option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5)

        button_frame = Frame(main_frame)
        self.add_button = Button(button_frame,
                                 state="disabled",
                                 text="Add",
                                 image=self.icons["gtk-add"],
                                 compound=LEFT)
        self.add_button.grid(column=0, row=0, sticky=(E))
        self.update_button = Button(button_frame,
                                    state="disabled",
                                    text="Update",
                                    image=self.icons["gtk-edit"],
                                    compound=LEFT)
        self.update_button.grid(column=1, row=0, sticky=(E))
        self.delete_button = Button(button_frame,
                                    state="disabled",
                                    text="Delete",
                                    image=self.icons["gtk-remove"],
                                    compound=LEFT)
        self.delete_button.grid(column=2, row=0, sticky=(E))
        button_frame.grid(column=0,
                          row=4,
                          columnspan=2,
                          sticky=(E),
                          padx=shared_pad_x,
                          pady=shared_pad_y)

        close_frame = Frame(main_frame)
        close_button = Button(close_frame,
                              text="Close",
                              image=self.icons["gtk-close"],
                              compound=LEFT,
                              command=self.on_closing)
        close_button.grid(column=0, row=0, sticky=(S, E))
        close_frame.grid(column=0,
                         row=5,
                         columnspan=2,
                         sticky=(S, E),
                         padx=shared_pad_x,
                         pady=(15, shared_pad_y))

        self.my_window.grid_columnconfigure(0, weight=1)
        self.my_window.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_rowconfigure(2, weight=0)
        main_frame.grid_rowconfigure(3, weight=1)
        main_frame.grid_rowconfigure(4, weight=1)
        main_frame.grid_rowconfigure(5, weight=1)
        condition_list.grid_columnconfigure(1, weight=1)
        button_frame.grid_rowconfigure(0, weight=1)

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

    def on_closing(self):
        if self.close_callback is not None:
            self.close_callback()
        self.my_window.destroy()

    def up_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index - 1, state_current)
        self.condition_listbox.insert(index - 1, condition_current)
        self.execution_target_listbox.insert(index - 1,
                                             execution_target_current)

        self.conditionals.insert(index - 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index - 1)
        self.condition_listbox.selection_set(index - 1)
        self.execution_target_listbox.selection_set(index - 1)
        self.state_listbox.see(index - 1)

        if index - 1 == 0:
            self.up_button.config(state="disabled")
        self.down_button.config(state="normal")

    def down_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index + 1, state_current)
        self.condition_listbox.insert(index + 1, condition_current)
        self.execution_target_listbox.insert(index + 1,
                                             execution_target_current)

        self.conditionals.insert(index + 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index + 1)
        self.condition_listbox.selection_set(index + 1)
        self.execution_target_listbox.selection_set(index + 1)
        self.state_listbox.see(index + 1)

        if index + 1 == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        self.up_button.config(state="normal")

    def condition_list_scrollbar_callback(self, *args):
        self.state_listbox.yview(*args)
        self.condition_listbox.yview(*args)
        self.execution_target_listbox.yview(*args)

    def state_listbox_scroll(self, *args):
        self.condition_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])
        self.condition_list_scrollbar.set(*args)

    def condition_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])

    def execution_target_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.condition_listbox.yview_moveto(args[0])

    def any_listbox_selected(self):
        self.up_button.config(state="normal")
        self.down_button.config(state="normal")
        if self.state_listbox.curselection(
        )[0] == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        if self.state_listbox.curselection()[0] == 0:
            self.up_button.config(state="disabled")
        self.delete_button.config(state="normal")
        self.then_entry.delete("1.0", END)
        self.then_entry.insert(
            END, self.conditionals[self.state_listbox.curselection()[0]][3])
        self.if_text_variable.set(
            self.conditionals[self.state_listbox.curselection()[0]][1])

        self.execution_target.set(
            self.conditionals[self.state_listbox.curselection()[0]][2])

        self.active_checkbutton.set(
            self.conditionals[self.state_listbox.curselection()[0]][0])

    def state_listbox_selected(self, event):
        index = self.state_listbox.curselection()[0]
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def condition_listbox_selected(self, event):
        index = self.condition_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def execution_target_listbox_selected(self, event):
        index = self.execution_target_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        self.any_listbox_selected()
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
Beispiel #27
0
class App:
    ########################################################################
    ####################################Interface for PlaNet:
    def __init__(self, master):
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        analyzemenu = Menu(menu)
        PostAnalysis = Menu(menu)
        Settings = Menu(menu)
        About = Menu(menu)

        menu.add_cascade(label="Start", menu=filemenu)
        filemenu.add_command(label="Select genes for analysis",
                             command=self.SearchGene)
        menu.add_cascade(label="Analyze", menu=analyzemenu)
        analyzemenu.add_command(label="Display probeset specific report",
                                command=self.nvnReport)
        analyzemenu.add_command(
            label="NetworkComparer Step I: Find similar co-expression networks",
            command=self.netComparer)
        analyzemenu.add_command(
            label="NetworkComparer Step II: Extract ancestral network",
            command=self.ancestranNetPipe)
        menu.add_cascade(label="Change organism/database",
                         command=self.UseDatabaseFile)
        menu.add_cascade(label="Help", menu=About)
        About.add_command(label="About GeneCAT", command=self.About)

        self.messenger = Text(root, font=("Courier", 10), wrap=NONE)
        self.printer("Stand alone version of PlaNet\n")
        button = Button(root, text="Clear", fg="red", command=self.clear)
        self.LabVar = StringVar()
        DBLabel = Label(root, relief=SUNKEN, textvariable=self.LabVar)

        ybar = Scrollbar(root)
        xbar = Scrollbar(root, orient=HORIZONTAL)
        DBLabel.pack(side=BOTTOM, anchor=NW)
        button.pack(side=BOTTOM, anchor=E)
        ybar.pack(side=RIGHT, fill=Y)
        xbar.pack(side=BOTTOM, fill=X)
        self.messenger.pack(expand=1, fill=BOTH)
        self.messenger.config(yscrollcommand=ybar.set)
        self.messenger.config(xscrollcommand=xbar.set)
        ybar.config(command=self.messenger.yview)
        xbar.config(command=self.messenger.xview)

        config = open('dbconf.txt', 'r').readlines()
        self.queries = []
        try:
            self.currentDB = codecs.open('%s' % (config[0].rstrip()),
                                         mode='r',
                                         encoding='ASCII',
                                         errors='ignore').readlines()
            self.printer(
                "Currently using database: %s consisting of %d probesets and %d chips.\n"
                % (config[0].rstrip(), len(self.currentDB),
                   (len(self.currentDB[0].split()) - 3)))
            self.LabVar.set(
                "Using database: %s, Columns=%d, rows=%d." %
                (config[0].rstrip(), len(
                    self.currentDB[0].split()), len(self.currentDB)))
            nominator = []
            denominator = []
            self.annoDict = {}
            for i in range(len(self.currentDB)):
                temp = []
                splitta = self.currentDB[i].rstrip().split("\t")
                self.annoDict[i] = splitta[
                    0] + "\t" + splitta[1] + "\t" + splitta[2].replace(
                        "*", " ") + "\t" + splitta[3] + "\t"
                for j in range(5, len(splitta)):
                    temp.append(float(splitta[j]))
                expVector = numpy.array(temp)
                nomi = expVector - (numpy.sum(expVector) / len(expVector))
                denomi = numpy.sqrt(numpy.sum(nomi**2))
                nominator.append(nomi)
                denominator.append(denomi)
            self.nominator = numpy.array(nominator)
            self.denominator = numpy.array(denominator)
        except IOError:
            self.printer("Could not open current database.\n")

########################################################################
####################################Start menu items:

    def SearchGene(self):  #interface for "Select genes for analysis"
        SearchFrame = Toplevel()
        SearchFrame.title(
            "Data entry. Enter gene identifier, probesets or keywords.\n")
        scrollBar = Scrollbar(SearchFrame)
        self.inputFrame = Text(SearchFrame,
                               font="courier",
                               width=30,
                               wrap=WORD)
        self.inputFrame.pack(side=LEFT, fill=BOTH)
        scrollBar.pack(side=LEFT, fill=Y)
        self.inputFrame.config(yscrollcommand=scrollBar.set)
        scrollBar.config(command=self.inputFrame.yview)
        goButton = Button(SearchFrame,
                          text="Find",
                          fg="red",
                          command=self.SearchGenePipe)
        goButton.pack(side=BOTTOM)
####################################Searches the current database with user specified keywords

    def SearchGenePipe(self):
        if self.inputFrame.get(1.0, END) != "\n":
            queries = self.inputFrame.get(1.0, END).lower().split()
            foundGenes = []
            for i in queries:
                infos = ""
                for j in self.currentDB:
                    if i in j.lower():
                        splitta = j.split("\t")
                        foundGenes.append(j)
                        infos += splitta[0] + "\t" + splitta[
                            1] + "\t" + splitta[2].replace("*", " ") + "\n"
                self.printer("Probesets found for term: " + i + "\n" + infos +
                             "\n")
            if len(infos) == "":
                self.printer("No hits found.\n")
            else:
                self.queries = foundGenes

########################################################################
####################################Data mining menu items

####################"Display probeset specific report"

    def nvnReport(self):  #interface for "Display probeset specific report"
        top = Toplevel()
        top.title("Co-expression analysis")
        self.genelist = []
        for string in self.queries:
            self.genelist.append(string.split())
        self.listbox = Listbox(top, width=40, height=30, exportselection=0)
        for gene in self.genelist:
            self.listbox.insert(END, gene[0] + '   ' + gene[1])

        DescriptionLabel = LabelFrame(top, text="Info")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list to the left.\nThis tool will generate result.html file containing a page similar to\ngene specific pages in PlaNet."
        )
        DescriptionLabel.grid(row=0, column=2)

        ParametersLabel = LabelFrame(top, text="Parameters")
        Steps = Label(ParametersLabel, text="Number of steps")
        ParametersLabel.grid(row=1, column=2)
        Hrr = Label(ParametersLabel, text="HRR cut-off.")

        self.paraSteps = Entry(ParametersLabel)
        self.paraSteps.grid(row=1)
        self.paraSteps.insert(END, 2)
        self.paraHrr = Entry(ParametersLabel)
        self.paraHrr.grid(row=3)
        self.paraHrr.insert(END, 30)
        Description.grid()
        Steps.grid(row=0)
        Hrr.grid(row=2)
        scrollbar = Scrollbar(top)
        scrollbar.grid(row=0, column=1, rowspan=5, sticky=S + N)
        self.listbox.grid(row=0, column=0, rowspan=5)
        scrollbar.config(command=self.listbox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.nvnReportPipe)
        button.grid(row=6, column=0)

    def nvnReportPipe(
            self):  #Executes functions that generate result.html file
        try:
            steps = int(self.paraSteps.get())
            hrr = int(self.paraHrr.get())
        except:
            self.printer(
                "You need to enter integer values for HRR and step parameters.\n"
            )
        if self.listbox.curselection() != ():
            query = self.genelist[int(self.listbox.curselection()[0])][0]

            #### Plot expression profile function
            try:
                plotDatabase = codecs.open(
                    open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".plt",
                    mode='r',
                    encoding='ASCII',
                    errors='ignore').readlines()
                ticka = [""] + plotDatabase[0].replace(
                    ",", "\n").lstrip().rstrip().split("\t")
                for i in plotDatabase:
                    if query in i:
                        query = i
                data = query.split()[1:]
                temp = []
                for i in range(len(data)):
                    temp.append([
                        map(float, data[i].replace("-",
                                                   "\t").rstrip().split()),
                        average(
                            map(float, data[i].replace("-",
                                                       "\t").rstrip().split()))
                    ])
                fig = plt.figure(figsize=(12, 7))
                ax = fig.add_subplot(111)
                plt.subplots_adjust(left=0.1, right=0.97, top=0.93, bottom=0.3)
                ax.set_ylabel("Signal value")
                ax.set_title(query.split()[0])
                ax.grid(True)
                plt.xticks(range(len(ticka) + 1),
                           ticka,
                           rotation=90,
                           fontsize="small",
                           horizontalalignment="center")
                ax.plot([0], [0])
                crossX = []
                crossY = []
                for i in range(len(temp)):
                    ax.plot([i + 1] * len(temp[i][0]), temp[i][0], "g.")
                    crossX.append([i + 1])
                    crossY.append(temp[i][1])
                ax.plot(crossX, crossY, "-ro")
                ax.plot([i + 2], [0])
                canvas = FigureCanvasAgg(fig)
                canvas.print_figure("profile.png")
                plt.clf()
            except:
                self.printer(
                    "Failed to generate an expression profile of your gene of interes.\nThe expression matrix used for plotting of expression profiles must be present and named "
                    + open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".plt!")
            ###Call network creator
            try:
                networkViewer.makeNetwork(query.split()[0], steps, hrr)
            except:
                self.printer(
                    "Failed to generate an co-expression network of your gene of interes.\nThe HRR network file used must be present named "
                    + open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".hrr!")
            ### Calculate PCC of a gene to all genes in database
            try:
                query = self.queries[int(
                    self.listbox.curselection()[0])].split("\t")
                expVector = map(float, query[5:])
                expVector = numpy.array(expVector)
                nomi = expVector - (numpy.sum(expVector) / len(expVector))
                denomi = numpy.sqrt(numpy.sum(nomi**2))
                rValues = numpy.dot(self.nominator, nomi) / numpy.dot(
                    self.denominator, denomi)
                displayList = []
                for i in range(len(rValues)):
                    displayList.append([rValues[i], self.annoDict[i]])
                displayList.sort(reverse=True)
            except:
                displayList = []
                self.printer(
                    "Failed to calculate Pearson correlation co-efficient list.\n"
                )

            ###Create html document with results
            header = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">\n<html>\n<head>\n<!-- blarg -->\n</head>\n<body>\n'
            try:
                header += '<big><b>Summary page for: %s</b></big>\n<br><b>Expression profile:</b>\n<IMG SRC="profile.png"><br>\n' % (
                    displayList[0][1].split()[0] + "\t" +
                    displayList[0][1].split()[1])
            except:
                pass
            header += '<b>HRR based co-expression network:</b>\nGreen, organge and red edges represent HRR values of %s, %s and %s, respectively.</b><br>\n' % (
                int(hrr) / 3, (int(hrr) / 3) * 2, hrr)
            header += '<embed src="network.svg" width="1200" height="1200" type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/" />\n<br>'
            #header += '<iframe src="network.svg" width="1500" height="1500">\n</iframe>\n'
            header += "<br><b>MapMan ontology analysis of the above network:</b>\n"
            try:
                header += open("mapRes.mapman", "r").read()
            except:
                pass
            header += "\n<br><b>Pearson correlation based co-expression analysis:</b>\n<pre>"

            v = open("result.html", "w")
            v.close()
            v = open("result.html", "a")
            v.write(header)
            for i in range(len(self.annoDict)):
                v.write(
                    str(displayList[i][0])[:6] + "\t" + displayList[i][1] +
                    "\n")
            v.write("</pre>")
            v.close()
            self.printer(
                "Probeset specific result calculated and available in result.html file.\n"
            )

####################"NetworkComparer step I:"

    def netComparer(self):  #Interface
        top = Toplevel()
        top.title("NetworkComparer")

        self.genelistNC = []
        for string in self.queries:
            if "No hit" not in string:
                self.genelistNC.append(string.split("\t"))
        DescriptionLabel = LabelFrame(
            top, text="Select the gene of interest and specify parameters.")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer."
        )
        DescriptionLabel.grid(row=0, column=0)
        Description.grid(row=0)
        ParametersLabel = LabelFrame(DescriptionLabel, text="Parameters")
        Steps = Label(ParametersLabel, text="Number of steps")
        ParametersLabel.grid(row=1, column=2)
        Hrr = Label(ParametersLabel, text="HRR cut-off.")
        Steps.grid(row=0)
        Hrr.grid(row=2)
        self.paraSteps = Entry(ParametersLabel)
        self.paraSteps.grid(row=1)
        self.paraSteps.insert(END, 2)
        self.paraHrr = Entry(ParametersLabel)
        self.paraHrr.grid(row=3)
        self.paraHrr.insert(END, 30)
        self.listbox = Listbox(DescriptionLabel,
                               width=40,
                               height=30,
                               exportselection=0)
        probeName = []
        for gene in self.genelistNC:
            self.listbox.insert(END,
                                gene[0] + '   ' + gene[1] + '   ' + gene[3])
        self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarG = Scrollbar(DescriptionLabel)
        scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarG.config(command=self.listbox.yview)

        NetworkLabel = LabelFrame(
            top, text="Select the networks/species you want to compare.")
        Network = Label(
            NetworkLabel,
            text=
            "Available networks are displayed in the list below. Check/uncheck networks of interest."
        )
        NetworkLabel.grid(row=0, column=1)
        Network.grid(row=0)
        self.networkBox = Listbox(NetworkLabel,
                                  width=40,
                                  height=30,
                                  selectmode=MULTIPLE,
                                  exportselection=0)
        self.networkList = []
        for i in os.listdir("."):
            if ".hrr" in i:
                self.networkBox.insert(END, i)
                self.networkList.append(i)
        self.networkBox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarN = Scrollbar(NetworkLabel)
        scrollbarN.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarN.config(command=self.networkBox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.netComparerPipe)
        button.grid(row=1, column=0, columnspan=5, sticky=E + W)

    def netComparerPipe(
        self
    ):  #Passess selected query and networks to networkComparer.start function
        error = 0
        try:
            steps = int(self.paraSteps.get())
        except:
            error += 1
            self.printer(
                "You must enter an integer value bigger than 1 for this parameter.\n"
            )
        try:
            hrr = int(self.paraHrr.get())
        except:
            error += 1
            self.printer(
                "You must enter an integer value bigger than 1 for this parameter.\n"
            )
        netList = []
        for i in self.networkBox.curselection():
            netList.append(self.networkList[int(i)])
        if netList == []:
            error += 1
            self.printer(
                "You must at least select one network for this analysis.\n")
        if error == 0:
            #try:
            networkComparer.start(
                steps, hrr, netList,
                self.genelistNC[int(self.listbox.curselection()[0])][0],
                self.genelistNC[int(self.listbox.curselection()[0])][3])
            self.printer(
                "Calculation done and results are available in NetComp.html file.\n"
            )
        #except:
        #self.printer("Something went wrong. Make sure Graphviz is installed.\n")

####################"NetworkComparer step II:"

    def ancestranNetPipe(self):  #Interface
        top = Toplevel()
        top.title("NetworkComparer")
        a = open("NetComp.html", "r").readlines()
        self.queriesAC = []
        quera = 0
        for i in range(len(a)):
            if "START OF QUERIES" in a[i]:
                self.queryOrder = a[i + 1].rstrip().split()
            if "START OF VS. QUERY" in a[i]:
                quera = 1
            if quera == 1:
                self.queriesAC.append(a[i].rstrip().split("\t"))
        self.queriesAC = self.queriesAC[1:len(self.queriesAC) - 1]
        DescriptionLabel = LabelFrame(
            top, text="Select the gene of interest and specify parameters.")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer."
        )
        DescriptionLabel.grid(row=0, column=0)
        Description.grid(row=0)
        self.listbox = Listbox(DescriptionLabel,
                               width=40,
                               height=30,
                               exportselection=0,
                               selectmode=MULTIPLE)
        for gene in self.queriesAC:
            self.listbox.insert(
                END, gene[0] + '   ' + gene[1] + '   ' + gene[2] + '   ' +
                gene[3] + '   ' + gene[4])
        self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarG = Scrollbar(DescriptionLabel)
        scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarG.config(command=self.listbox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.ancestralNet)
        button.grid(row=1, column=0, columnspan=5, sticky=E + W)

    def ancestralNet(
        self
    ):  #Passess selected query and networks to ancestralNetwork.start function
        selected = []
        for i in self.listbox.curselection():
            selected.append(self.queryOrder.index(self.queriesAC[int(i)][1]))
        ancestralNetwork.start(selected)


########################################################################
####################################Settings menu items

####################Change database

    def UseDatabaseFile(self):
        database = askopenfilename(filetypes=[("Expression matrix", ".exp")])
        if database != '':
            self.datafile = database.split('/')[len(database.split('/')) - 1]
            configstring = "%s" % self.datafile
            DB = open(self.datafile, 'r').readlines()
            self.LabVar.set(
                "Using database: %s, Columns=%d, rows=%d." %
                (self.datafile.strip(), len(DB[1].split()), len(DB)))
            newconfig = open('dbconf.txt', 'w')
            newconfig.writelines(configstring)
            newconfig.close()
            self.printer("Using %s database\n" % (self.datafile))
            try:
                config = open('dbconf.txt', 'r').readlines()
                self.currentDB = codecs.open('%s' % (config[0].rstrip()),
                                             mode='r',
                                             encoding='ASCII',
                                             errors='ignore').readlines()
                self.printer(
                    "Currently using database: %s consisting of %d probesets and %d chips.\n"
                    % (config[0].rstrip(), len(self.currentDB),
                       (len(self.currentDB[0].split()) - 3)))
                self.LabVar.set(
                    "Using database: %s, Columns=%d, rows=%d." %
                    (config[0].rstrip(), len(
                        self.currentDB[0].split()), len(self.currentDB)))
                nominator = []
                denominator = []
                self.annoDict = {}
                for i in range(len(self.currentDB)):
                    temp = []
                    splitta = self.currentDB[i].rstrip().split("\t")
                    self.annoDict[i] = splitta[
                        0] + "\t" + splitta[1] + "\t" + splitta[2].replace(
                            "*", " ") + "\t" + splitta[3] + "\t"
                    for j in range(5, len(splitta)):
                        temp.append(float(splitta[j]))
                    expVector = numpy.array(temp)
                    nomi = expVector - (numpy.sum(expVector) / len(expVector))
                    denomi = numpy.sqrt(numpy.sum(nomi**2))
                    nominator.append(nomi)
                    denominator.append(denomi)
                self.nominator = numpy.array(nominator)
                self.denominator = numpy.array(denominator)
            except IOError:
                self.printer("Could not open current database.\n")

    def About(self):
        top = Toplevel()
        top.title("PlaNet standalone")
        label = Label(
            top,
            text=
            "PlaNet standalone\nMarek Mutwil\ncontact: [email protected]",
            width=30)
        OkButton = Button(top, text="OK", command=top.destroy)
        label.pack()
        OkButton.pack()

    def printer(self, text):  #prints text to message box
        #self.messenger.delete(1.0, END)
        self.messenger.insert(END, text)

    def clear(self):  #clears message box
        self.messenger.delete(1.0, END)
Beispiel #28
0
class MainForm(Frame):
    """
    If method is handling some GUI shit, its written in camelCase style
    """
    def __init__(self, parent, caller_instance):
        Frame.__init__(self, parent)
        self.caller_instance = caller_instance
        self.running_on = "%s:%s" % (get_local_addr(),
                                     getattr(self.caller_instance, 'port',
                                             None) or "8888")
        self.parent = parent
        caller_instance.messangers.append(self)
        self.initUI()

    def initUI(self):
        self.__centerWindow()
        self.parent.title("epyks %s" % self.running_on)
        #
        # Addr textbox
        #
        addr_validate = (self.parent.register(self.addrValidation), '%S', '%d')
        self.EntryAddress = Entry(self,
                                  validate='key',
                                  validatecommand=addr_validate,
                                  width=17)
        self.EntryAddress.grid(row=0,
                               column=0,
                               padx=10,
                               pady=5,
                               columnspan=2,
                               sticky=W)
        self.EntryAddress.delete(0, END)
        self.EntryAddress.insert(0, "192.168.0.102:8889")
        #
        # Call button
        #
        self.ButtonCall = Button(self,
                                 text="Call",
                                 command=self.onButtonCallClick)
        self.ButtonCall.grid(row=0, column=1, pady=5)
        #
        #   Callmode status canvas
        #
        self.CanvasCallmode = Canvas(self,
                                     width=20,
                                     height=20,
                                     bg="light grey")
        self.CanvasCallmode.create_oval(1,
                                        1,
                                        20,
                                        20,
                                        fill="red",
                                        outline="light grey")
        self.CanvasCallmode.grid(row=1,
                                 column=0,
                                 pady=0,
                                 padx=10,
                                 sticky=W,
                                 columnspan=2)
        #
        #   Callmode status label
        #
        self.LabelCallmode = Label(self, text="Not connected")
        self.LabelCallmode.grid(row=1, column=0, padx=35)
        #
        #   End call button
        #
        self.ButtonEndCall = Button(self,
                                    text="End call",
                                    command=self.onButtonEndCallClick)
        self.ButtonEndCall.grid(row=1, column=1)

        #
        #   Message listbox
        #
        self.MessagesListBox = Listbox(self)
        self.MessagesListBox.grid(row=2,
                                  column=0,
                                  columnspan=2,
                                  padx=2,
                                  pady=2,
                                  sticky="EW")
        #
        # Message entry
        #
        self.EntryMessage = Entry(self)
        self.EntryMessage.grid(row=3, column=0, padx=2)
        #
        # Send message
        #
        self.ButtonSendMessage = Button(self,
                                        text="Send",
                                        command=self.onButtonSendMessageClick)
        self.ButtonSendMessage.grid(row=3, column=1)

        # Testing

        # Pack all
        self.pack(fill=BOTH, expand=1)

    def onGetAnswerMessageBox(self, interlocutor):
        return tkMessageBox.askyesno(
            title="Incoming call",
            message="A call from {}, wanna answer?".format(interlocutor))

    def addrValidation(self, string, action):
        print string
        if action != 1:
            # 0 - delete, 1 - insert, -1 - focus in/out
            return True
        print "addrValidation: %s" % string
        if len(string) > 1:
            return full_ipv4_check(fulladdr=string)
        return string in ACCEPTABLE_CHARS

    def onTextBoxChange(self, *args, **kwargs):
        print 'lol ' + str(args) + str(kwargs)

    def onButtonCallClick(self):
        address = (self.EntryAddress.get())
        if not full_ipv4_check(fulladdr=address):
            tkMessageBox.showerror(message="Incorrect address")
        ip, port = address.split(':')
        self.caller_instance.call((ip, int(port)))

    def onButtonSendMessageClick(self):
        message = self.EntryMessage.get()
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author="self", message=message))
        ip, port = self.EntryAddress.get().split(':')
        self.caller_instance.send(message=message, address=(ip, int(port)))

    def onButtonEndCallClick(self):
        self.caller_instance.hang_up()

    def onMessageRecieved(self, author, message):
        """
        :param author: Address of author, tuple (ip, port)
        :param message: Content
        """
        author = ''.join([author[0], ':', str(author[1])])
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author=author, message=message))

    def checkStatus(self):
        status = self.caller_instance.status
        if status.startswith('On'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="green",
                                            outline="light grey")
            self.EntryAddress.delete(0, END)
            self.EntryAddress.insert(
                0, "{}:{}".format(self.caller_instance.interlocutor[0],
                                  self.caller_instance.interlocutor[1]))
            self.EntryAddress.configure(state='readonly')

        elif status.startswith('Not'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="red",
                                            outline="light grey")
            self.EntryAddress.configure(state='')
        else:
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="yellow",
                                            outline="light grey")
            self.EntryAddress.configure(state='readonly')
        self.LabelCallmode['text'] = status
        self.parent.after(ms=100, func=self.checkStatus)

    def __centerWindow(self):
        w = 260
        h = 270
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
Beispiel #29
0
class GUI(Frame):
    def __init__(self, parent, register):
        Frame.__init__(self, parent, padding=(3, 3, 3, 3))
        self.parent = parent
        self.register = register
        self.logger = register.get_events_logger()
        self.init_ui()

        self.login()
        self.update_order()

    def login(self):
        logged_in = False
        while not logged_in:
            token = None
            while token is None:
                token = askstring(title="Please login", prompt="Login")
            try:
                self.register.login_employee(token)
                logged_in = True
            except CredentialException:
                self.logger.warning("invalid employee token '" + token +
                                    "', " + "unable to login")
        self.name_var.set(register.get_employee_name())
        # Put focus in barcode field
        self.barcode_field.focus()

    def logout(self, *args):
        self.register.logout_employee()
        self.name_var.set("")
        self.login()

    def print_count(self):
        try:
            print self.register.get_register_count()
        except CredentialException:
            self.logger.warning("insufficient privileges to print register " +
                                "count")
        # Put focus in barcode field
        self.barcode_field.focus()

    def add(self, token):
        try:
            self.register.add(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to add an item")
        except ValueError:
            pass
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def add_custom(self, *args):
        name = askstring(title="Enter item name", prompt="Item name")
        if name is not None:
            price = askfloat(title="Enter item price",
                             prompt="Item price")
            if price is not None:
                try:
                    self.register.add_custom(name, price)
                except CredentialException:
                    self.logger.warning("insufficient privileges to add " +
                                        "a custom item")
                except ValueError as e:
                    self.logger.warning(e.__str__)
                finally:
                    self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def remove(self, token):
        try:
            self.register.remove(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to scan an item")
        except ValueError:
            self.logger.warning("token does not correspond to any item")
        except ItemNotFoundException:
            self.logger.warning("item not in order, unable to remove it")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def clear_order(self, *args):
        try:
            self.register.clear_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to clear the order")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def adjust(self, *args):
        amount = askfloat(title="Enter adjustment amount",
                          prompt="Adjustment amount")
        if amount is not None:
            try:
                self.register.adjust(amount)
            except CredentialException:
                self.logger.warning("insufficient privileges to adjust " +
                                    "register count")
            except ValueError as e:
                self.logger.warning("invalid adjustment amount: " + e)
        # Put focus in barcode field
        self.barcode_field.focus()

    def checkout(self, *args):
        try:
            self.register.checkout_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to checkout order")
        finally:
            self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def count(self, *args):
        # TODO: implement a proper register count
        # TODO: add dialog box telling how register count went
        count = askfloat(title="Enter register count", prompt="Register count")
        if count is not None:
            try:
                self.register.count_register(count)
            except CredentialException:
                self.logger.warning("insufficient privileges to count " +
                                    "register")
        # Put focus in barcode field
        self.barcode_field.focus()

    def parse_barcode_field(self, event):
        command = self.barcode_field.get().strip()
        self.barcode_var.set("")
        tokens = command.split(" ")
        if tokens[0] == "print_count":
            self.print_count()
        elif tokens[0] == "print_order":
            self.print_order()
        elif tokens[0] == "remove":
            if len(tokens) < 2:
                self.logger.warning("need an item to remove")
                return None
            self.remove(tokens[1])
        elif tokens[0] == "adjust_count":
            if len(tokens) < 2:
                self.logger.warning("need an adjustment amount")
                return None
            self.adjust(tokens[1])
        elif tokens[0] == "custom":
            if len(tokens) < 3:
                self.logger.warning("need an name and a price")
                return None
            try:
                self.add_custom(tokens[1], float(tokens[2]))
            except ValueError:
                self.logger.warning("price is not valid")
        elif tokens[0] == "checkout":
            self.checkout()
        elif tokens[0] == "count":
            if len(tokens) < 2:
                self.logger.warning("need an register count")
                return None
            else:
                self.count(tokens[1])
        else:
            if tokens[0] != "":
                self.add(tokens[0])
        # Put focus in barcode field
        self.barcode_field.focus()

    def update_order(self):
        self.items_var.set(tuple(
            item.get_name() + " x " + str(quantity) for
            item, quantity in self.register.get_order().items()))
        self.total_var.set("Total: %0.2f$" % self.register.get_order_total())
        # Put focus in barcode field
        self.barcode_field.focus()

    def init_ui(self):
        # Window configuration
        screen_width = self.parent.winfo_screenwidth()
        screen_height = self.parent.winfo_screenheight()
        self.parent.geometry(
            '%dx%d+%d+%d' % (screen_width, screen_height, 0, 0))
        self.parent.title("Caisse Planck")
        self.parent.rowconfigure(0, weight=1)
        self.parent.columnconfigure(0, weight=1)

        self.grid(column=0, row=0, sticky=(N, S, E, W))
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(7, weight=0)
        self.rowconfigure(8, weight=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=0)

        self.items_var = StringVar()
        self.items_list = Listbox(self, height=10, listvariable=self.items_var)
        self.items_list.grid(row=1, column=0, rowspan=8, sticky=(N, S, E, W))

        self.barcode_var = StringVar(self)
        self.barcode_field = Entry(self, textvariable=self.barcode_var)
        self.barcode_field.bind("<Return>", self.parse_barcode_field)
        self.barcode_field.grid(row=0, column=0, sticky=(N, E, W))

        self.benevole_label = Label(self, text="Volunteer:")
        self.benevole_label.grid(row=0, column=1, sticky=(N, W))

        self.name_var = StringVar(self)
        self.name_label = Label(self, textvar=self.name_var)
        self.name_label.grid(row=0, column=2, sticky=(N, W))


        self.parent.bind("<F1>", self.logout)
        self.logout_button = Button(self, text="Logout (F1)",
                                    command=self.logout)
        self.logout_button.grid(row=1, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F5>", self.count)
        self.count_button = Button(self, text="Count register (F5)",
                                   command=self.count)
        self.count_button.grid(row=2, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.adjust)
        self.adjust_button = Button(self, text="Register adjustment (F6)",
                                    command=self.adjust)
        self.adjust_button.grid(row=3, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.add_custom)
        self.custom_item_button = Button(self, text="Custom item (F7)",
                                         command=self.add_custom)
        self.custom_item_button.grid(row=4, column=1, columnspan=2,
                                     sticky=(E, W))

        self.total_var = StringVar(self, value="Total: 0.00$")
        self.total_label = Label(self, textvar=self.total_var)
        self.total_label.grid(row=7, column=1, columnspan=2, sticky=(S, E, W))

        self.parent.bind("<F12>", self.checkout)
        self.ok_button = Button(self, text="Ok (F12)", command=self.checkout)
        self.ok_button.grid(row=8, column=1, sticky=(S, E, W))

        self.parent.bind("<Escape>", self.clear_order)
        self.cancel_button = Button(self, text="Cancel (ESC)",
                                    command=self.clear_order)
        self.cancel_button.grid(row=8, column=2, sticky=(S, E, W))
Beispiel #30
0
class Ordered_Listbox(Frame):
    def __init__(self, master, data=None, ascending_order = True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs):
        Frame.__init__(self, master)

        self._ignore_case = ignore_case
        self._ascending_order = ascending_order

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

        self._listbox = Listbox(self, *kwargs)        
        self._listbox.grid(row=0, column=0, sticky= N+E+W+S)

        scrollbar_kwargs = {}
        if scrollbar_background is not None:
            scrollbar_kwargs["background"] = scrollbar_background
            
        if scrollbar_troughcolor is not None:
            scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor

        if vscrollbar:
            self._vbar=Scrollbar(self,takefocus=0, command=self._listbox.yview, **scrollbar_kwargs)
            self._vbar.grid(row=0, column=1, sticky= N+S)
            
            if autoscroll:
                self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l))
            else:
                self._listbox.config(yscrollcommand=self._vbar.set)

        if hscrollbar:
            self._hbar=Scrollbar(self,takefocus=0, command=self._listbox.xview, **scrollbar_kwargs)
            self._hbar.grid(row=0, column=1, sticky= E+W)
            
            if autoscroll:
                self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l))
            else:
                self._listbox.config(xscrollcommand=self._hbar.set)

        if data is not None:
            for item in data:
                self.add_item(item)

    def add_item(self, item):
        list_of_items = self._listbox.get(0, END)

        index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order)
        self._listbox.insert(index, item)

    def delete_item(self, item):
        list_of_items = self._listbox.get(0, END)
        index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order)
        self._listbox.delete(index-1)
        
    def selected_items(self):
        list_of_items = []

        for index in self._listbox.curselection():
            list_of_items.append(self._listbox.get(index))
            
        return list_of_items
        
    def selected_item(self):
        return self._listbox.curselection()[0]

    def deselect_all(self):
        self._listbox.selection_clear(0, END)
        
    def select(self, item):
        index = self.index(item)
        
        if index is None:
            return
        
        self._listbox.selection_set(index)

    def deselect(self, item):
        index = self.index(item)
        
        if index is None:
            return
        
        self._listbox.selection_clear(index)

    def index(self, item):
        list_of_items = self._listbox.get(0, END)

        try:
            index = list_of_items.index(item)
        except ValueError:
            return None

        return index

    def bind(self, event, handler):
        self._listbox.bind(event, handler)
    
    def clear(self):
        self._listbox.delete(1,END)

    def __iter__(self):
        return self.items
    
    @property
    def items(self):
        return self._listbox.get(0, END)
Beispiel #31
0
class Example(Frame):
    def __init__(self, parent):
        self.catFactors = {}
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        if hasattr(self, 'frame0'):
            self.frame0.destroy()
        self.initUIRoot()
        self.initUIFrame()

    def initUIRoot(self):
        self.parent.title("集总模型")
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        self.frame0 = Frame(self, relief=RAISED)
        self.frame0.pack(fill=BOTH, expand=True)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label=u"新建催化剂", command=self.onNewCata)
        fileMenu.add_command(label=u"精确预测", command=self.onNewPre)
        fileMenu.add_command(label=u"趋势预测", command=self.onNewGraph)
        fileMenu.add_command(label=u"最优条件预测", command=self.onNewBest)
        helpMenu = Menu(menubar)
        helpMenu.add_command(label=u"关于", command=self.onHelp)

        mainPageMenu = Menu(menubar)
        mainPageMenu.add_command(label=u"主页", command=self.initUI)
        menubar.add_cascade(label="主页", menu=mainPageMenu)
        menubar.add_cascade(label="操作", menu=fileMenu)
        menubar.add_cascade(label="帮助", menu=helpMenu)

    def initUIFrame(self):
        self.frame0.columnconfigure(0, pad=5, weight=1)
        self.frame0.columnconfigure(1, pad=5, weight=1)
        self.frame0.columnconfigure(2, pad=5, weight=1)
        self.frame0.columnconfigure(3, pad=5, weight=1)
        self.frame0.columnconfigure(4, pad=5, weight=1)
        self.frame0.columnconfigure(5, pad=5, weight=1)
        self.frame0.rowconfigure(0, pad=37)
        self.frame0.rowconfigure(1, pad=7)
        self.frame0.rowconfigure(2, pad=7, weight=1)
        titleImg = ImageTk.PhotoImage(file="./imgs/title.png")
        catImg = ImageTk.PhotoImage(file="./imgs/cat.png")
        preImg = ImageTk.PhotoImage(file="./imgs/pre.png")
        chartImg = ImageTk.PhotoImage(file="./imgs/chart.png")
        bestImg = ImageTk.PhotoImage(file="./imgs/bestPoint.png")
        rareImg = ImageTk.PhotoImage(file="./imgs/rare.png")

        lbl = Label(self.frame0, image=titleImg)
        lbl.grid(row=0, column=1,columnspan=5,sticky=S+W)
        lbl.image = titleImg
        lbl = Label(self.frame0, image=rareImg)
        lbl.grid(row=3, column=1,columnspan=5,sticky=S)
        lbl.image = rareImg
        preButton = Button(self.frame0, command=self.onNewPre)
        preButton.config(image=preImg)
        preButton.image = preImg
        preButton.grid(row=1, column=2)
        cateButton = Button(self.frame0, command=self.onNewCata)
        cateButton.config(image=catImg)
        cateButton.image = catImg
        cateButton.grid(row=1, column=1)
        chartButton = Button(self.frame0, command=self.onNewGraph)
        chartButton.config(image=chartImg)
        chartButton.image = chartImg
        chartButton.grid(row=1, column=3)
        chartButton = Button(self.frame0, command=self.onNewBest)
        chartButton.config(image=bestImg)
        chartButton.image = bestImg
        chartButton.grid(row=1, column=4)

        lbl = Label(self.frame0, text="新建催化剂")
        lbl.grid(row=2, column=1, sticky=N)
        lbl = Label(self.frame0, text="精确预测")
        lbl.grid(row=2, column=2, sticky=N)
        lbl = Label(self.frame0, text="趋势预测")
        lbl.grid(row=2, column=3, sticky=N)
        lbl = Label(self.frame0, text="最优条件预测")
        lbl.grid(row=2, column=4, sticky=N)
    def bestUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(11, pad=7, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, sticky=W, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度范围(K 英文逗号分割 )")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        if not self.catObj.withTemp:
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力范围(KPa 英文逗号分割)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比范围 (英文逗号分割)")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间范围(英文逗号分割s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="待预测组分编号(,)")
        lbl.grid(row=9, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.target = Entry(frame2)
        self.target.insert(0, '5,6,7')
        self.target.grid(row=9, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="结果组成")
        lbl.grid(row=0, column=7, columnspan=2, rowspan=1, pady=4, padx=5, sticky=W)
        self.preResult_LB = Listbox(frame2)
        self.preResult_LB.grid(row=1, column=7, columnspan=2, rowspan=8, pady=4, padx=5, sticky=W)

        lbl = Label(frame2, text="最优温度:")
        lbl.grid(row=0, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestT = Entry(frame2)
        self.bestT.delete(0, 'end')
        self.bestT.configure(state='readonly')
        self.bestT.grid(row=0, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优压力:")
        lbl.grid(row=1, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestP = Entry(frame2)
        self.bestP.delete(0, 'end')
        self.bestP.configure(state='readonly')
        self.bestP.grid(row=1, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优剂油比:")
        lbl.grid(row=2, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestR = Entry(frame2)
        self.bestR.delete(0, 'end')
        self.bestR.configure(state='readonly')
        self.bestR.grid(row=2, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优反应时间:")
        lbl.grid(row=3, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestTime = Entry(frame2)
        self.bestTime.delete(0, 'end')
        self.bestTime.configure(state='readonly')
        self.bestTime.grid(row=3, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="目标结果:")
        lbl.grid(row=4, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestSum = Entry(frame2)
        self.bestSum.delete(0, 'end')
        self.bestSum.configure(state='readonly')
        self.bestSum.grid(row=4, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        cateDetailButton = Button(frame2, text="预测", command=self.doBest)
        cateDetailButton.grid(row=9, column=6, columnspan=2)

    def preUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, sticky=W, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        if not self.catObj.withTemp:
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)
        self.preResult_LB = Listbox(frame2)
        self.preResult_LB.grid(row=1, column=7, columnspan=2, rowspan=6, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测", command=self.doPre)
        cateDetailButton.grid(row=8, column=7, columnspan=2)

    def cateUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame4 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame4.pack(fill=BOTH)

        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(0, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.rowconfigure(0, weight=1)

        lbl = Label(frame4, text="已输入温度组数")
        lbl.grid(row=0, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.varCountT = StringVar()
        self.countT = Message(frame4, textvariable=self.varCountT)
        self.varCountT.set('0')

        self.countT.grid(row=0, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        factor_Tree = ttk.Treeview(frame1)
        factor_Tree['show'] = 'headings'
        factor_Tree["columns"] = ['t_resid', 't', 'r_oil', 'p', 'Y0', 'Y_results', 'w_aro', 'w_nitro']
        #
        factor_Tree.heading("t", text="温度")
        factor_Tree.column("t", width=self.winfo_width() / 8)
        factor_Tree.heading("r_oil", text="剂油比")
        factor_Tree.column("r_oil", width=self.winfo_width() / 8)
        factor_Tree.heading("p", text="压力")
        factor_Tree.column("p", width=self.winfo_width() / 8)
        factor_Tree.heading("Y0", text="初始组成")
        factor_Tree.column("Y0", width=self.winfo_width() / 8)
        factor_Tree.heading("Y_results", text="产物组成")
        factor_Tree.column("Y_results", width=self.winfo_width() / 8)
        factor_Tree.heading("w_aro", text="重芳烃含量")
        factor_Tree.column("w_aro", width=self.winfo_width() / 8)
        factor_Tree.heading("w_nitro", text="碱氮含量")
        factor_Tree.column("w_nitro", width=self.winfo_width() / 8)
        factor_Tree.heading("t_resid", text="停留时间")
        factor_Tree.column("t_resid", width=self.winfo_width() / 8)
        factor_Tree.grid(row=0, column=0, pady=4, padx=5)
        self.factor_Tree = factor_Tree
        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(8, weight=1)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=0, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=0, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        self.T_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=0, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="产物组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Y_results_input = Entry(frame2)
        self.Y_results_input.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=2, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=3, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=3, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="分子质量(逗号分割)")
        lbl.grid(row=4, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Molmasses_input = Entry(frame2)
        self.Molmasses_input.grid(row=4, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Molmasses_input.insert('0.8,1.1,1.8,0.2,0.2,0.2,0.11,0.016,0.042,0.056,0.05,0.012')
        addButton = Button(frame2, command=self.addFactors, text="添加条件")
        addButton.grid(row=9, column=2, sticky=E)

        self.newCatButton = Button(frame2, command=self.newCata, text="开始计算", state=DISABLED)
        self.newCatButton.grid(row=9, column=6, sticky=E)

    def graphUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.columnconfigure(1, weight=1)
        frame2.columnconfigure(6, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)

        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="图表设置")
        lbl.grid(row=0, column=6, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="条件变量")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.var = ttk.Combobox(frame2, textvariable=StringVar())
        if not self.catObj.withTemp:
            self.var['values'] = (u'压力', u'剂油比', u'停留时间')
            self.p_input.insert(0, 0)
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
            self.p_input.configure(state='readonly')
            self.lastVar = u'压力'
        else:
            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state='readonly')
            self.var['values'] = (u'温度', u'压力', u'剂油比', u'停留时间', u'温度+压力',u'温度+剂油比',u'剂油比+压力')
            self.lastVar = u'温度'
        self.var.bind('<<ComboboxSelected>>', self.onSelecetedVar)
        self.var.current(0)
        self.var.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        self.rangeLbl = Label(frame2, text="条件范围")
        self.rangeLbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="上限")
        lbl.grid(row=3, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="下限")
        lbl.grid(row=4, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.rangeMin = Entry(frame2)
        self.rangeMax = Entry(frame2)

        self.rangeMin.grid(row=3, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)
        self.rangeMax.grid(row=4, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="结果集(英文逗号分割)")
        lbl.grid(row=5, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultId = Entry(frame2)
        self.chartResultId.insert(0, '1,2,3,4,5,6,7,8,9,10,11,12')
        self.chartResultId.grid(row=5, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="结果名(英文逗号分割\n尽量使用英文)")
        lbl.grid(row=6, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultName = Entry(frame2)
        #TODO,get the default value from lump model
        self.chartResultName.insert(0, 'HS,HA,HR,DIESEL,GS,GO,GA,DGAS,LO3,LO4,LPGD,COKE')
        self.chartResultName.grid(row=6, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="点数")
        lbl.grid(row=7, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.stepNum = Entry(frame2)
        self.stepNum.grid(row=7, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测趋势", command=self.doChart)
        cateDetailButton.grid(row=8, column=6, columnspan=2)

    def onSelecetedVar(self, event):
        varName = self.var.get()
        if self.lastVar == u'温度':
            # u'温度',,,u'停留时间'
            self.T_input.configure(state="normal")
        elif self.lastVar == u'压力':
            self.p_input.configure(state="normal")
        elif self.lastVar == u'剂油比':
            self.roil_input.configure(state="normal")
        elif self.lastVar == u'停留时间':
            self.t_input.configure(state="normal")
        elif self.lastVar == u'温度+压力':
            self.T_input.configure(state="normal")
            self.p_input.configure(state="normal")
        elif self.lastVar == u'温度+剂油比':
            self.roil_input.configure(state="normal")
            self.T_input.configure(state="normal")
        elif self.lastVar == u'剂油比+压力':
            self.roil_input.configure(state="normal")
            self.p_input.configure(state="normal")

        if varName == u'温度':
            self.rangeLbl.config(text='条件范围')

            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")
        elif varName == u'压力':
            self.rangeLbl.config(text='条件范围')

            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")
        elif varName == u'剂油比':
            self.rangeLbl.config(text='条件范围')

            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")
        elif varName == u'停留时间':
            self.rangeLbl.config(text='条件范围')

            self.t_input.delete(0, 'end')
            self.t_input.insert(0, 0)
            self.t_input.configure(state="readonly")
        elif varName == u'温度+压力':
            self.rangeLbl.config(text='条件范围,格式:温度,压力')

            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")
            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")
        elif varName == u'温度+剂油比':
            self.rangeLbl.config(text='条件范围,格式:温度,剂油比')
            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")
            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")

        elif varName == u'剂油比+压力':
            self.rangeLbl.config(text='条件范围,格式:剂油比,压力')
            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")

            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")

        self.lastVar = varName

    def onNewCata(self):
        self.catFactors = {}
        ftypes = [('集总模型', '*.lp')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        # print flmakePreResultUI
        if fl != '':
            self.lumpObj = self.readFile(fl)
            print self.lumpObj
            self.cateUI()

    def onNewPre(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.preUI()
    def onNewBest(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.bestUI()
    def onNewGraph(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.graphUI()

    def saveCate(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        filename = tkFileDialog.asksaveasfilename(title='保存催化剂存档文件', defaultextension='.cat', filetypes=ftypes)
        return filename

    def onHelp(self):
        mbox.showinfo("集总模型软件", "中国石油\n兰州化工研究中心")

    def doPre(self):
        catObj = self.catObj
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        stepLength = float(self.step_input.get())
        n = catObj.n
        print [t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n]
        result = newPre(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, stepLength).tolist()[0]
        self.makePreResultUI(self.preResult_LB, result)
    def doBest(self):
        catObj = self.catObj
        t_resid = [float(self.t_input.get().split(',')[0]),float(self.t_input.get().split(',')[1])]
        p = [float(self.p_input.get().split(',')[0]),float(self.p_input.get().split(',')[1])]
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = [float(self.T_input.get().split(',')[0]),float(self.T_input.get().split(',')[1])]
        r_oil = [float(self.roil_input.get().split(',')[0]),float(self.roil_input.get().split(',')[1])]
        stepLength = float(self.step_input.get())
        n = catObj.n
        target = self.target.get().split(',')
        print [t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n,target]
        result = newBest(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, stepLength,target)
        self.bestP.configure(state='normal')
        self.bestT.configure(state='normal')
        self.bestR.configure(state='normal')
        self.bestTime.configure(state='normal')
        self.bestSum.configure(state='normal')
        self.bestP.insert('end',round(result['bestP'], 4))
        self.bestT.insert('end',round(result['bestT'], 4))
        self.bestR.insert('end',round(result['bestR'], 4))
        self.bestTime.insert('end',round(result['bestTime'], 4))
        self.bestSum.insert('end',round(result['sum'], 4))
        self.makePreResultUI(self.preResult_LB, result['Y'])
    def doChart(self):
        catObj = self.catObj
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        stepNum = int(self.stepNum.get())
        resultId = self.chartResultId.get()
        resultName = self.chartResultName.get()

        stepLength = float(self.step_input.get())
        n = catObj.n
        varName = ''
        if self.lastVar == u'温度':
            varName = 't'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'压力':
            varName = 'p'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'剂油比':
            varName = 'r'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'停留时间':
            varName = 'time'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'温度+压力':
            varName = 't,p'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        elif self.lastVar == u'温度+剂油比':
            varName = 't,r'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        elif self.lastVar == u'剂油比+压力':
            varName = 'r,p'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        chartConfig = {}
        chartConfig['varName'] = varName
        chartConfig['stepNum'] = stepNum

        chartConfig['varMin'] = varMin
        chartConfig['varMax'] = varMax
        chartConfig['resultId'] = resultId
        chartConfig['resultName'] = resultName
        # t_resid=3
        # p=175
        # const_r=8.3145
        # Y0=mat([0.481,0.472,0.047,0,0,0,0])
        # w_aro=0.472
        # w_nitro=0
        # t=685
        # n=7
        # r_oil=8.79
        # chartConfig={'varName': 'time', 'varMax': 0.001, 'varMin': 15.0, 'resultId': '1,2,3,4,5,6,7', 'stepNum': 100,'resultName':u'Hs,Ha,Hr,柴油,汽油,气体,焦炭'}

        print chartConfig
        print [catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig]
        if len(varName)>1:
            result = new3dChart(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig, stepLength)

        else:
            result = new2dChart(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig, stepLength)

    def addFactors(self):
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0_raw = self.Y0_input.get()
        Y0 = numpy.mat(Y0_raw.split(',')).astype(numpy.float)
        Y_results_raw = self.Y_results_input.get()
        Y_results = numpy.mat(Y_results_raw.split(',')).astype(numpy.float)
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        self.Molmasses = numpy.mat(self.Molmasses_input.get().split(',')).astype(numpy.float)
        self.factor_Tree.insert('', END, values=[t_resid, t, r_oil, p, Y0_raw, Y_results_raw, w_aro, w_nitro])
        if self.catFactors.has_key(t):
            self.catFactors[t].append(
                {'t_resid': t_resid, 't': t, 'r_oil': r_oil, 'p': p, 'Y0': Y0, 'Y_results': Y_results, 'w_aro': w_aro,
                 'w_nitro': w_nitro})
        else:
            self.catFactors[t] = [
                {'t_resid': t_resid, 't': t, 'r_oil': r_oil, 'p': p, 'Y0': Y0, 'Y_results': Y_results, 'w_aro': w_aro,
                 'w_nitro': w_nitro}]
        print self.catFactors
        self.varCountT.set(len(self.catFactors))
        self.Molmasses_input.configure(state='readonly')
        self.newCatButton.configure(state='active')

    def newCata(self):
        filename = self.saveCate()
        print filename
        if len(self.catFactors) == 1:
            newCatNoKa(filename, self.lumpObj, 1, 0, 1, self.lumpObj, self.Molmasses, self.catFactors.values()[0],
                       'L-BFGS-B',
                       1e-5, self.lumpObj.shape[0])
        else:
            newCatWithKa(filename, self.lumpObj, 1, 0, 1, self.lumpObj, self.Molmasses, self.catFactors, 'L-BFGS-B',
                         1e-5,
                         self.lumpObj.shape[0])

    def makeMatrixUI(self, targetTree, catObj):
        n = catObj.n
        if not catObj.withTemp:
            targetTree.insert('end', '催化剂模型是在同一温度下,只能计算K\n------------------\nK=\n')
            K = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['K_result'], 4)
            self.makeMatrixOutput(n, targetTree, K)
            targetTree.insert('end', '\n------------------\n重芳烃影响因数:\n')
            targetTree.insert('end', self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['Ka'])
            targetTree.insert('end', '\n------------------\n碱氮影响因数:\n')
            targetTree.insert('end', self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['Kn'])
            targetTree.insert('end', '\n------------------\n')

        else:
            K = self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['K_result']
            print catObj.X0_result
            Ka = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.Ka, catObj.n)['K_result'], 4)
            print catObj.Ka
            Ea = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.Ea, catObj.n)['K_result'], 4)
            print catObj.Ea
            targetTree.insert('end', '\n------------------\nK=\n')
            print len(K)
            for i in K:
                self.makeMatrixOutput(n, targetTree, numpy.round(i, 4))
                targetTree.insert('end', '\n------------------\n')
            targetTree.insert('end', '\n------------------\nKa=\n')
            self.makeMatrixOutput(n, targetTree, Ka)
            targetTree.insert('end', '\n------------------\n')
            targetTree.insert('end', '\n------------------\nEa=\n')
            self.makeMatrixOutput(n, targetTree, Ea)
            targetTree.insert('end', '\n------------------\n')

    def makeMatrixOutput(self, n, targetTree, mat):
        for i in range(n):
            targetTree.insert('end', ','.join(mat[i].astype(numpy.string_).tolist()))
            targetTree.insert('end', '\n')
        return targetTree

    def makeMatrixByResult(self, K_model, result, n):
        if type(result) != type([]):
            K = result[:-3].tolist()
            args = result[-3:]
            K_raw_result = []
            for i in K_model.T.flat:
                if i:
                    K_raw_result.append(K.pop(0))
                else:
                    K_raw_result.append(0)
            K_result = reshape(K_raw_result, (n, n)).T.T.T
            ka_result, kn_result, cata_result = args
            return {'K_result': K_result, 'ka_result': ka_result, 'kn_result': kn_result, 'cata_result': cata_result}
        else:
            K_results = []

            args = result[0][-3:]
            for i in result:
                K = i[:-3].tolist()
                K_raw_result = []
                for i in K_model.T.flat:
                    if i:
                        K_raw_result.append(K.pop(0))
                    else:
                        K_raw_result.append(0)
                K_result = reshape(K_raw_result, (n, n)).T.T.T
                K_results.append(K_result)
            ka_result, kn_result, cata_result = args
            return {'K_result': K_results, 'ka_result': ka_result, 'kn_result': kn_result,
                    'cata_result': cata_result}

    def makePreResultUI(self, target, result):
        target.delete(0, END)
        if type(result)!=type([]):
            result=result.tolist()[0]
        for i in result:
            target.insert(END, round(i, 3))
        return target

    def readFile(self, filename):
        f = open(filename, "r")
        obj = pickle.load(f)
        return obj
Beispiel #32
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)

    def setupView(self, title="AllinOne"):
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self,
                         text='Next',
                         command=lambda: self.
                         confirm())
        self.ok.grid(row=4, column=1, sticky="W")
        self.cancel = Button(self,
                             text='Exit',
                             command=lambda: self.controller.quit())
        self.cancel.grid(row=4, column=0, sticky="E")

    def confirm(self):
        params = {}
        params['device'] = self.deviceList.get(
            self.deviceList.curselection()[0])
        params['version'] = self.versionList.get(
            self.versionList.curselection()[0])
        params['package'] = self.packageList.get(
            self.packageList.curselection()[0])
        params['eng'] = self.engList.get(
            self.engList.curselection()[0])
        self.controller.doFlash(params)

    def setDeviceList(self, list=[]):
        self.deviceLabel = Label(self, text="Select Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        for l in list:
            self.deviceList.insert(END, l)
        self.deviceList.grid(row=2, column=0)

    def setVersionList(self, list=[]):
        self.versionLabel = Label(self, text="Select Version", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        for l in list:
            self.versionList.insert(END, l)
        self.versionList.grid(row=2, column=1)

    def setPackageList(self, list=[]):
        self.packageLabel = Label(
            self,
            text="Gecko/Gaia/Full",
            font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=2)
        self.packageList = Listbox(self, exportselection=0)
        for l in list:
            self.packageList.insert(END, l)
        self.packageList.grid(row=2, column=2)

    def setEngList(self, list=[]):
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=3)
        self.engList = Listbox(self, exportselection=0)
        for l in list:
            self.engList.insert(END, l)
        self.engList.grid(row=2, column=3)
class TrackSelect(tkSimpleDialog.Dialog):

    def __init__(self, master, **kwargs):
        self.vid = {'title': "this video"}
        self.tracks = []
        for k in kwargs:
            k = k.lower()
            if k == "master":
                self.master = kwargs[k]
                continue
            if k == "vid":
                self.vid = kwargs[k]
                continue
            if k == "tracks":
                self.tracks = kwargs[k]
                continue

        self.padx = 3
        self.pady = 3
        self.prefl = IntVar()
        self.preft = IntVar()
        self.preflang = None
        self.prefname = None
        tkSimpleDialog.Dialog.__init__(self, master, "Select caption track")

    def body(self, master):
        Label(master, text="%s contains multiple caption tracks" %
              self.vid['title']).grid(row=0, padx=self.padx, pady=self.pady,
                                      sticky=W, columnspan=5)
        self.__langlist(master)
        self.chosenlangbut = Button(master, text="->",
                                    command=self.__chooselang)
        self.chosenlangbut.grid(row=1, column=2, padx=self.padx,
                                pady=self.pady)
        self.__tracklist(master)
        self.__fillLangs()
        return self.langsel  # initial focus

    def __tracklist(self, master):
        self.trackYscroll = Scrollbar(master, orient=HORIZONTAL)
        self.trackXscroll = Scrollbar(master, orient=VERTICAL)
        self.tracksel = Listbox(master,
                               xscrollcommand=self.trackXscroll.set,
                               yscrollcommand=self.trackYscroll.set,
                               selectmode=SINGLE)
        self.tracksel.grid(row=1, column=3, sticky=N + S + E + W)
        self.trackXscroll.grid(row=1, column=4, sticky=W + N + S)
        self.trackYscroll.grid(row=2, column=3, stick=N + E + W)
        self.trackXscroll.config(command=self.tracksel.xview)
        self.trackYscroll.config(command=self.tracksel.yview)
        self.preftracksel = Checkbutton(master,
                                        variable=self.preft,
                                        text="Set default track name")
        self.preftracksel.grid(row=3, column=3, sticky=W)

    def __langlist(self, master):
        self.langYscroll = Scrollbar(master, orient=HORIZONTAL)
        self.langXscroll = Scrollbar(master, orient=VERTICAL)
        self.langsel = Listbox(master,
                               xscrollcommand=self.langXscroll.set,
                               yscrollcommand=self.langYscroll.set,
                               selectmode=SINGLE, width=6)
        self.langsel.grid(row=1, column=0, sticky=N + S + E + W)
        self.langXscroll.grid(row=1, column=1, sticky=W + N + S)
        self.langYscroll.grid(row=2, column=0, stick=N + E + W)
        self.langXscroll.config(command=self.langsel.xview)
        self.langYscroll.config(command=self.langsel.yview)
        self.preflangsel = Checkbutton(master,
                                       variable=self.prefl,
                                       text="Set default language")
        self.preflangsel.grid(row=3, column=0, sticky=W)

    def __fillLangs(self):
        self.langsadded = []
        for track in self.tracks:
            lang = track['lang']
            if lang not in self.langsadded:
                self.langsel.insert(END, lang)
                self.langsadded.append(lang)

    def __chooselang(self):
        lang = self.langsadded[int(self.langsel.curselection()[0])]
        self.langselected = lang
        self.trackoptions = []
        self.tracksel.delete(0, END)
        for track in self.tracks:
            if track['lang'] == lang:
                name = 'Default' if len(track['name']) == 0 else track['name']
                self.tracksel.insert(END, name)
                self.trackoptions.append(track)
        self.tracksel.activate(0)
        self.tracksel.selection_set(0)

    def apply(self):
        selected = int(self.tracksel.curselection()[0])
        self.result = [self.trackoptions[selected]]
        if int(self.prefl.get()) == 1:
            self.preflang = self.langselected
        if int(self.preft.get()) == 1:
            self.prefname = self.trackoptions[
                    int(self.tracksel.curselection()[0])]['name']

    def buttonbox(self):
        box = Frame(self)

        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Skip", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()
Beispiel #34
0
class App(tk.Frame):
    def __init__(self, master, *args, **kw):
        super().__init__(master, *args, **kw)
        self.root = master
        self.master.title('Rebuild List')
        # Width, Height of application
        self.master.geometry("575x600")
        self.store = Combobox_Autocomplete
        self.alldicts = {}
        self.create_widgets()
        self.create_widgets1()

    def create_widgets(self, *args):
        # Image
        self.imgtitle = ImageTk.PhotoImage(Image.open('snapsrebuild.png'))
        self.lab = tk.Label(image=self.imgtitle)
        self.lab.grid(row=0, column=0, columnspan=6, padx=20, pady=20)
        # Supplies Label
        self.consume_label = tk.Label(self.root, text='Supplies:', font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=0, columnspan=2, padx=50)
        # AutoCompleteBox
        self.entry_0 = tk.StringVar()
        self.combobox_autocomplete = Combobox_Autocomplete(self.root, list_of_items, textvariable=self.entry_0,
                                                           width=32, highlightthickness=1)
        self.combobox_autocomplete.grid(row=2, column=0, sticky="W", padx=20, pady=10)
        # Insert Button
        self.insert_butt = tk.Button(self.root, text='Insert', command=lambda: self.commando())
        self.insert_butt.place(x=220, y=155)
        # List Box
        self.list_box = Listbox(self.root, border=1, width=40, height=20, justify='center')
        self.list_box.grid(row=3, rowspan=5, column=0, padx=20)
        # Delete Button
        self.del_button = tk.Button(self.root, text='Delete', command=lambda: self.delbutton())
        self.del_button.place(x=175, y=520)
        # Check Button
        self.check_button = tk.Button(self.root, text='Check', command=lambda: self.checkbutton())
        self.check_button.place(x=50, y=520)
        # Uncheck Button
        self.uncheck_button = tk.Button(self.root, text='Uncheck', command=lambda: self.uncheckbutton())
        self.uncheck_button.place(x=105, y=520)

        self.list_box.insert(END, "Dragon Claws")
        self.list_box.insert(END, "Super Combat Potions")
    def delbutton(self):
        self.list_box.delete(ACTIVE)

    def checkbutton(self):
        self.list_box.itemconfig(ACTIVE, {'bg': 'green'})

    def uncheckbutton(self):
        self.list_box.itemconfig(ACTIVE, {'bg': '#ffffff'})


    # def commando(self):
    #     x = 'Consumables'
    #     self.alldicts.update({x: (self.entry_0.get())})
    #     self.list_box.insert(END, self.entry_0.get())
    #     for (key, value) in self.alldicts.items():
    #         print(key, "::", value)
    #     return ()

    #######################################################################################################################

    def create_widgets1(self):
        # Gear Label
        self.consume_label1 = tk.Label(self.root, text='Gear', font=('Arial', 12, 'bold'))
        self.consume_label1.grid(row=1, column=2, padx=50)
        self.entry_1 = tk.StringVar()
        self.combobox_autocomplete1 = Combobox_Autocomplete(self.root, list_of_items, textvariable=self.entry_1,
                                                            width=32,
                                                            highlightthickness=1)
        self.combobox_autocomplete1.grid(row=2, column=2, padx=20, pady=10, sticky="W")
        # Insert Button
        self.insert_butt1 = tk.Button(self.root, text='Insert', command=lambda: self.commando1())
        self.insert_butt1.place(x=505, y=155)
        # List Box
        self.list_box1 = Listbox(self.root, border=1, width=40, height=20)
        self.list_box1.grid(row=3, rowspan=5, column=2, padx=20)
        # Delete Button
        self.del_button1 = tk.Button(self.root, text='Delete', command=lambda: self.delbutton1())
        self.del_button1.place(x=502, y=520)
        # Check Button
        self.check_button1 = tk.Button(self.root, text='Check', command=lambda: self.checkbutton1())
        self.check_button1.place(x=305, y=520)
        # Uncheck Button
        self.uncheck_button1 = tk.Button(self.root, text='Uncheck', command=lambda: self.uncheckbutton1())
        self.uncheck_button1.place(x=400, y=520)


        self.headers = [" ITEM", "                                            PRICE"]
        self.row_format = "{:<8}  {:>8}"
        self.list_box1.insert(0, self.row_format.format(*self.headers, sp="       " * 6))
        self.list_box1.insert(1, '-----------------------------------------------------------')

    def delbutton1(self):
        self.list_box1.delete(ACTIVE)

    def checkbutton1(self):
        self.list_box1.itemconfig(ACTIVE, {'bg': 'green'})

    def uncheckbutton1(self):
        self.list_box1.itemconfig(ACTIVE, {'bg': '#ffffff'})




    def commando1(self):
        x = 'Gear'
        self.alldicts.update({x: (self.entry_1.get())})
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        for item in names:
            if item in self.entry_1.get():
                indexNumber = names.index(self.entry_1.get())
                print(indexNumber)
                self.priceIndex = prices[indexNumber]
                self.ent = self.entry_1.get()
                self.headers1 = [self.ent,'                            ', f"{self.priceIndex:,d}"]
                self.row_format1 = "{:<8}  {:>8} {:>8}"
                self.list_box1.insert(END, self.row_format1.format(*self.headers1))
        return ()
class ActionModulation(Frame):
    def __init__(self,parent):
        Frame.__init__(self,parent)
        self.parent = parent
        self.intensityValue = 0.0
        self.initUI()
        
    def initUI(self):
        self.frame = Frame(self.parent, relief=RAISED,borderwidth=1)
        #panel with the information to be introduced
        #self.grid(row=0,column=0)
        self.position = PanelInformation.PanelInformation(self.frame)
        self.position.getFrame().grid(row=0,column=0)
        self.position.setLabelXLabel("Position X:")
        self.position.setLabelYLabel("Position Y:")
        self.position.setLabelThetaLabel("Position Theta:")
        self.velocity = PanelInformation.PanelInformation(self.frame)
        self.velocity.getFrame().grid(row=1,column=0)
        self.velocity.setLabelXLabel("Walk Shoulder:")
        self.velocity.setLabelYLabel("Walk torso:")
        self.velocity.setLabelThetaLabel("Pose:")
        #panel for the emotion intensity
        self.frameIntensity =  Frame(self.frame, relief=RAISED,borderwidth=1)
        self.frameIntensity.grid(row = 4, column = 0)
        self.labelIntensity = Label(self.frameIntensity,text="Intensity:")
        self.labelIntensity.grid(row=0,column=0)
        self.intensity = Scale(self.frameIntensity, from_=0, to = 1,command=self.onScale)
        self.intensity.grid(row = 1, column = 0)
        self.var = IntVar()
        self.labelInfoIntensity = Label(self.frameIntensity, text=0, textvariable=self.var)
        self.labelInfoIntensity.grid(row = 2, column = 0)
        
        #panel with the robot's information
        self.positionInfo = PanelInformation.PanelInformation(self.frame)
        self.positionInfo.setDisableEntry()
        self.positionInfo.getFrame().grid(row=0,column=2)
        self.positionInfo.setLabelXLabel("Position X:")
        self.positionInfo.setLabelYLabel("Position Y:")
        self.positionInfo.setLabelThetaLabel("Position Theta:")
        self.velocityInfo = PanelInformation.PanelInformation(self.frame)
        self.velocityInfo.setDisableEntry()
        self.velocityInfo.getFrame().grid(row=1,column=2)
        self.velocityInfo.setLabelXLabel("Velocity X:")
        self.velocityInfo.setLabelYLabel("Velocity Y:")
        self.velocityInfo.setLabelThetaLabel("Velocity Theta:")
        #emotions and actions
        self.frameEmotionAction = Frame(self.frame, relief=RAISED,borderwidth=1)
        self.frameEmotionAction.grid(row=2,column=0,columnspan=3)
        self.labelEmotion = Label(self.frameEmotionAction,text="Emotion:")
        self.labelEmotion.grid(row=0,column=0)
        scrollbar = Scrollbar(self.frameEmotionAction, orient=VERTICAL)
        scrollbar.grid(row=0,column=3)
        self.listEmotion = Listbox(self.frameEmotionAction,height=4)
        self.listEmotion.grid(row=0,column=2)
        self.listEmotion.bind("<<ListboxSelect>>", self.onSelectEmotion)
        #the new emotions should be added here
        self.emotions = ['neutral','angry','happy','sad','fear','content']
        for item in self.emotions:
            self.listEmotion.insert(END,item)
        self.listEmotion.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listEmotion.yview)
        self.labelAction = Label(self.frameEmotionAction,text="Action:")
        self.labelAction.grid(row=0,column=4)
        scrollbar2 = Scrollbar(self.frameEmotionAction, orient=VERTICAL)
        scrollbar2.grid(row=0,column=6)
        self.listAction = Listbox(self.frameEmotionAction,height=4)
        self.listAction.grid(row=0,column=5)
        #the new actions should be added here
        self.actions = ['not_do_anything','oscillate_shoulder','oscillate_body','move_shoulder','move_body','move_torso','oscillate_torso','walk']
        for item in self.actions:
            self.listAction.insert(END,item)
        self.listAction.config(yscrollcommand=scrollbar2.set)
        self.listAction.bind("<<ListboxSelect>>", self.onSelectAction)
        scrollbar2.config(command=self.listAction.yview)
        
        self.actionSelected = "do_nothing"
        self.emotionSelected = "neutral"
    
    def getFrame(self):
        return self.frame
    
    def onScale(self, val): 
        v = format(float(val),'.2f')
        self.intensityValue = v
        self.var.set(v) 
        
    def getIntensity(self):
        return self.intensityValue
        
    def onSelectAction(self,val):
        sender = val.widget
        idx = sender.curselection()
        self.actionSelected = sender.get(idx)
        
    def onSelectEmotion(self,val):
        sender = val.widget
        idx = sender.curselection()
        self.emotionSelected = sender.get(idx)
    
    def getListEmotion(self):
        return self.emotionSelected
        
    def getListAction(self):
        return self.actionSelected
    
    def getPanelPosition(self):
        return self.position
    
    def getPanelVelocity(self):
        return self.velocity    
    
    def getPanelInfoPosition(self):
        return self.positionInfo
    
    def getPanelInfoVelocity(self):
        return self.velocityInfo
Beispiel #36
0
def open_recipe():

    global Box
    global ingBox
    name = Box.get(ACTIVE)
    protocol_file = name + "protocol"
    '''File=open(protocol_file)
    text=File.read()
    File.close()'''
    openwindow = Tk()
    btn = Button(openwindow, text="save to your computer")
    btn.grid(row=0, column=0)
    label = Label(openwindow, text="Name")
    label.grid(row=1, column=0)
    label1 = Label(openwindow, text="Ingredients")
    label2 = Label(openwindow, text="Preparation Time")
    label3 = Label(openwindow, text="serves:")
    label4 = Label(openwindow, text="Instructions")
    cookit = Button(openwindow, text="cook", command=cook)
    absent = Button(openwindow, text="need to buy", command=go_shopping)
    label1.grid(row=2, column=0)
    label2.grid(row=3, column=0)
    label3.grid(row=4, column=0)
    label4.grid(row=5, column=0)
    cookit.grid(row=6, column=0)
    absent.grid(row=7, column=0)
    box = Text(openwindow, height="1")

    ingBox = Listbox(openwindow, width="107", height="15")

    timeBox = Text(openwindow, height="1")

    serves = Text(openwindow, height="1")

    ins = Text(openwindow, height="10")

    listt = []
    cn = ""
    f = open(protocol_file).readlines()
    nodestart = False
    for i in range(len(f)):
        if "#" in f[i]:
            nodestart = False
            listt.append(cn)
            cn = ""
        if nodestart:
            cn = cn + f[i]
        if "@" in f[i]:
            nodestart = True
    Name = listt[0]
    list_ingred = listt[1].split("\n")
    prepTime = listt[4]
    People = listt[3]
    Instructions = listt[2]
    for k in range(len(Name)):

        box.insert(END, Name[k])

    box.grid(row=1, column=1)

    for q in range(len(list_ingred)):

        ingBox.insert(END, list_ingred[q])

    ingBox.grid(row=2, column=1)

    for w in range(len(prepTime)):

        timeBox.insert(END, prepTime[w])
    timeBox.grid(row=3, column=1)

    for x in range(len(People)):

        serves.insert(END, People[x])

    serves.grid(row=4, column=1)

    for y in range(len(Instructions)):

        ins.insert(END, Instructions[y])

    ins.grid(row=5, column=1)

    openwindow.mainloop()
Beispiel #37
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented")
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError("If not guiven complete function, list_of_items can't be 'None'")

                if ignorecase_match:
                    if startswith_match:
                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:
                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)]
                else:
                    if startswith_match:
                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:
                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    
                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items
        
        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        
        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
        
    def _on_tab(self, event):
        self.post_listbox()
        return "break"

    def _on_change_entry_var(self, name, index, mode):
        
        entry_data = self._entry_var.get()

        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)
                
            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False)
        self._listbox.grid(row=0, column=0,sticky = N+E+W+S)

        self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
        
        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N+S)
            
            self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l))
            
        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E+W)
            
            self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness") 
        y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width=self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)
        
        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)
        
    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            
            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)
            
        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                
                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index +=1
                    
                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"
Beispiel #38
0
    radiobutton1 = Radiobutton(column,
                               variable=variable,
                               value="value1",
                               text="Selection 1")
    radiobutton0.fieldname = "radiobutton"
    radiobutton1.pack(side=LEFT)

    Label(form, text="Text area:").grid(row=6, column=0, sticky=E, pady=(8, 0))

    text = Text(form, height=5)
    text.fieldname = "text"
    text.grid(row=7, column=1, sticky=E + W)

    Label(form, text="Listbox:").grid(row=8, column=0, sticky=E, pady=(8, 0))

    listbox = Listbox(form)
    listbox.fieldname = "listbox"
    listbox.grid(row=9, column=1, sticky=W)

    for item in ["one", "two", "three", "four"]:
        listbox.insert("end", item)

    Label(form, text="Combobox:").grid(row=10, column=0, sticky=E, pady=(8, 0))

    combobox = Combobox(form, values=('X', 'Y', 'Z'), width=5)
    combobox.fieldname = "combobox"
    combobox.grid(row=11, column=1, sticky=W)

    Submit_Button(form, text="Submit").grid(row=12, column=1, sticky=E)

    root.mainloop()
Beispiel #39
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented")
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError("If not guiven complete function, list_of_items can't be 'None'")

                if ignorecase_match:
                    if startswith_match:
                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:
                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)]
                else:
                    if startswith_match:
                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:
                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    
                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items
        
        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        
        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
        #self.bind("<FocusOut>", lambda event: self.unpost_listbox())
        
    def _on_tab(self, event):
        #self.post_listbox()
        self.unpost_listbox()        
        #frmbill.cbouom.focus() 
             

        #self._update_entry_from_listbox()        
        #self.unpost_listbox()
        # if self._listbox is not None:
        #     self._listbox.master.destroy()
        #     self._listbox = None
        return "break"
   
    def _on_change_entry_var(self, name, index, mode):
        
        entry_data = self._entry_var.get()

        if entry_data == '':
            #print('test111')
            self.unpost_listbox()
            self.focus()
        else:
            if len(entry_data) < 3:
                return True
            values = finditem(entry_data)
            #kk
            #self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)
                
            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False)
        self._listbox.grid(row=0, column=0,sticky = N+E+W+S)

        self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
        
        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N+S)
            
            self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l))
            
        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E+W)
            
            self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness") 
        y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width=self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)
        
        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)
        
    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        if len(text) > 0:
            find_price(text)
        #kk

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            
            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)
            
        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                
                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index +=1
                    
                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"

# if __name__ == '__main__':
#     try:
#         from Tkinter import Tk
#     except ImportError:
#         from tkinter import Tk

#     list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"]

#     root = Tk()
#     root.geometry("300x200")

#     combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1)
#     combobox_autocomplete.pack()
    
#     combobox_autocomplete.focus()
    
#     root.mainloop()
Beispiel #40
0
class Application(Frame):
    def compress(self, sCTRL, dCTRL, eCTRL, gCTRL):

        allCTRL = {
            'Student': sCTRL,
            'Discipline': dCTRL,
            'Enroll': eCTRL,
            'Grade': gCTRL
        }
        pickle.dump(allCTRL, open("save.p", "wb"))

    def compare(self):
        if self.oCont >= self.Max:
            self.Max = self.oCont
            return

    def reader(self, Input, InputNumber):
        try:
            Input.getvar((str(InputNumber)))
        except TclError as tcl:
            s = str(tcl)
            return s.split("\"")[1]

    def clearText(self):
        self.textFrame.delete('1.0', END)

    def Srefresh(self):
        controller = self._studentControl.getCurentRepo().getStudents()
        curList = self.sList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Drefresh(self):
        controller = self._disciplineControl.getCurentRepo().getDisciplines()
        curList = self.dList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Erefresh(self):
        controller = self._enrolControl.getCurentRepo().getEnroll()
        curList = self.eList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Grefresh(self):
        controller = self._gradeControl.getCurentRepo().getGrades()
        curList = self.gList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def refreshALL(self):
        self.Srefresh()
        self.Drefresh()
        self.Erefresh()
        self.Grefresh()

    def SreadID(self, string):
        return string[11:string.index('|') - 1]

    def DreadID(self, string):
        return string[15:string.index('|') - 1]

    def EreadID(self, string):
        return [
            string[12:string.index('|') - 1], string[string.index('|') + 15:-2]
        ]

    def sPopup(self, event):
        self.sMenu.post(event.x_root, event.y_root)

    def dPopup(self, event):
        self.dMenu.post(event.x_root, event.y_root)

    def ePopup(self, event):
        self.eMenu.post(event.x_root, event.y_root)

    def gPopup(self, event):
        self.gMenu.post(event.x_root, event.y_root)

    def displayError(self, msg):
        tkMessageBox.showerror('Error', msg)

    def NewFile(self):
        self._studentControl.setRepo(deepcopy(student(1, '')))
        self._disciplineControl.setRepo(deepcopy(discipline(1, '')))
        self._enrolControl.setRepo(deepcopy(enroll(1, 1)))
        self._gradeControl.setRepo(deepcopy(grade(1, 1)))
        self.refreshALL()

    '''
    #============================================#
    :STUDENT:
    #============================================#
    '''

    def add_Student(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = Window2('Enter student ID: ', 'Enter student Name: ', top)
            Input.mainloop()
            top.destroy()

            if not Input.getvar(str(
                    Input.Input1)) == None and not Input.getvar(
                        str(Input.Input2)) == None:

                studentID = Input.getvar(str(Input.Input1))
                name = Input.getvar(str(Input.Input2))

                print studentID
                print name

                Valid().ID(studentID)
                Valid().name(name)

                self._studentControl.getCurentRepo().addStudent(
                    student(int(studentID), name))
                self._studentControl.create(int(studentID), name)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except idError:
            self.displayError('Invalid ID')

    def remove_Student(self):
        try:
            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            name = ''
            eList = []
            gList = []

            for Student in self._studentControl.getCurentRepo().getStudents():
                if int(Student.getId()) == studentID:
                    name = Student.getName()

            for enroll in self._enrolControl.getCurentRepo().getEnroll():
                if enroll.get_student_id() == studentID:
                    eList.append(enroll)

            for grade in self._gradeControl.getCurentRepo().getGrades():
                if int(grade.getStudentID()) == studentID:
                    gList.append(grade)

            try:
                self._studentControl.removeStudent(studentID)
            except classException:
                pass
            try:
                self._enrolControl.removeEnrollStudent(studentID)
            except classException:
                pass
            try:
                self._gradeControl.removeGradeStudent(studentID)
            except classException:
                pass

            self._studentControl.delete(studentID, eList, gList, name)

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_StudentID(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New ID', top)
            Input.mainloop()
            top.destroy()

            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            if not Input.getvar(str(Input.Input1)) == None:
                newID = Input.getvar(str(Input.Input1))
                newID = int(newID)
                self._studentControl.getCurentRepo().updateStudentID(
                    studentID, newID)
                self._enrolControl.getCurentRepo().updateStudentID(
                    studentID, newID)
                self._gradeControl.getCurentRepo().updateGradeStudentID(
                    int(studentID), newID)

                self._studentControl.updateID(studentID, newID)

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_StudentName(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New name', top)
            Input.mainloop()
            top.destroy()

            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            oldName = self.sList.get(index)[self.sList.get(index).index('|') +
                                            9:-2]

            if not Input.getvar(str(Input.Input1)) == None:
                newName = Input.getvar(str(Input.Input1))
                Valid().name(newName)
                self._studentControl.getCurentRepo().updateStudentName(
                    studentID, newName)

                self._studentControl.updateName(studentID, oldName, newName)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #=============================================#
    :DISCIPLINE:
    #=============================================#
    '''

    def add_Discipline(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = Window2('Enter discipline ID: ', 'Enter discipline Name: ',
                            top)
            Input.mainloop()
            top.destroy()

            if not Input.getvar(str(Input.Input1)) == None or not Input.getvar(
                    str(Input.Input2)) == None:
                disciplineID = Input.getvar(str(Input.Input1))
                name = Input.getvar(str(Input.Input2))
                Valid().name(name)
                Valid().ID(disciplineID)
                self._disciplineControl.getCurentRepo().addDiscipline(
                    discipline(int(disciplineID), name))

                self._disciplineControl.create(int(disciplineID), name)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

        except idError:
            self.displayError('Invalid ID')

    def remove_Discipline(self):
        try:
            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            name = ''
            eList = []
            gList = []

            for Discipline in self._disciplineControl.getCurentRepo(
            ).getDisciplines():
                if int(Discipline.getId()) == disciplineID:
                    name = Discipline.getName()

            for enroll in self._enrolControl.getCurentRepo().getEnroll():
                if enroll.get_discipline_id() == disciplineID:
                    eList.append(enroll)

            for grade in self._gradeControl.getCurentRepo().getGrades():
                if grade.getDisciplineID() == disciplineID:
                    gList.append(grade)

            try:
                self._disciplineControl.removeDiscipline(disciplineID)
            except classException:
                pass
            try:
                self._gradeControl.removeGradeDiscipline(disciplineID)
            except classException:
                pass

            try:
                self._enrolControl.removeEnrollDiscipline(disciplineID)
            except classException:
                pass

            try:
                self._disciplineControl.delete(disciplineID, eList, gList,
                                               name)
            except classException:
                pass

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_DisciplineID(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New ID', top)
            Input.mainloop()
            top.destroy()

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            if not Input.getvar(str(Input.Input1)) == None:
                newID = Input.getvar(str(Input.Input1))
                newID = int(newID)
                self._disciplineControl.getCurentRepo().updateDisciplineID(
                    disciplineID, newID)
                self._enrolControl.getCurentRepo().updateDisciplineID(
                    disciplineID, newID)
                self._gradeControl.getCurentRepo().updateGradeDisciplineID(
                    disciplineID, newID)

                self._disciplineControl.updateID(disciplineID, newID)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_DisciplineName(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New name', top)
            Input.mainloop()
            top.destroy()

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            oldName = self.dList.get(index)[self.dList.get(index).index('|') +
                                            8:-2]

            if not Input.getvar(str(Input.Input1)) == None:
                newName = Input.getvar(str(Input.Input1))
                Valid().name(newName)
                self._disciplineControl.getCurentRepo().updateDisciplineName(
                    disciplineID, newName)

                self._disciplineControl.updateName(disciplineID, oldName,
                                                   newName)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #===================================================#
    :ENROLL:
    #===================================================#
    '''

    def remove_Enroll(self):
        try:
            index = self.eList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disicplineID = int(IDs[1])

            self.eList.delete(ANCHOR)
            self._gradeControl.removeGrade(enroll(studentID, disicplineID))
            self._enrolControl.removeEnroll(enroll(studentID, disicplineID))
            self.Erefresh()
            self.Grefresh()

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def add_Enroll(self):
        try:
            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            #try:
            self._enrolControl.addEnroll(enroll(studentID, disciplineID))
            #except ValueError:
            #self.displayError('Enrollment allready exists')

            self._enrolControl.create(enroll(studentID, disciplineID))

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def add_EnrollGrade(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('Grade: ', top)
            Input.mainloop()
            top.destroy()

            index = self.eList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disciplineID = int(IDs[1])

            if not Input.getvar(str(Input.Input1)) == None:
                gradeValue = Input.getvar(str(Input.Input1))
                gradeValue = float(gradeValue)

                Valid().grade(gradeValue)

                self._gradeControl.addGrade(grade(disciplineID, studentID),
                                            gradeValue)
                self.Grefresh()

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #=======================================================#
    :GRADE:
    #=======================================================#
    '''

    def add_Grade(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('Grade: ', top)
            Input.mainloop()
            top.destroy()

            index = self.gList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disciplineID = int(IDs[1])

            if not Input.getvar(str(Input.Input1)) == None:
                gradeValue = Input.getvar(str(Input.Input1))
                gradeValue = float(gradeValue)

                Valid().grade(gradeValue)

                self._gradeControl.addGrade(grade(disciplineID, studentID),
                                            gradeValue)

                self._gradeControl.create(grade(disciplineID, studentID),
                                          gradeValue)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #================================================#  
    :SEARCH:
    #================================================#
    '''

    def SearchALL(self):

        top = tk.Toplevel()
        top.title('Input')
        Input = WindowRemove('Search: ', top)
        Input.mainloop()
        top.destroy()

        searchString = Input.getvar(str(Input.Input1))

        top = tk.Toplevel()
        top.title('Serch Results')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        top.text.insert(END, 'Disciplines:')
        for discipline in self._disciplineControl.getCurentRepo(
        ).getDisciplines():
            if searchString.lower() in str(discipline.getId()).lower() or str(
                    discipline.getId()).lower() in searchString.lower(
                    ) or searchString.lower() in discipline.getName().lower(
                    ) or discipline.getName().lower() in searchString.lower():
                top.text.insert(END, discipline)

        top.text.insert(END, 'Students:')
        for student in self._studentControl.getCurentRepo().getStudents():
            if searchString.lower() in str(student.getId()).lower() or str(
                    student.getId()).lower() in searchString.lower(
                    ) or searchString.lower() in student.getName().lower(
                    ) or student.getName().lower() in searchString.lower():
                top.text.insert(END, student)

    '''
    #===============================================#
    :STATISCTICS:
    #===============================================#
    '''

    def StudentEnrollA(self):

        try:

            top = tk.Toplevel()
            top.title('Enrollment List')
            top.text = Listbox(top)
            top.text.grid(row=0, column=0)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            SList = self._enrolControl.studentEnrollA(disciplineID)

            for index in SList:
                top.text.insert(END, index)

            del SList[:]

        except TclError:
            top.destroy()
            self.displayError('No disicpline Selected')

    def StudentEnrollB(self):

        try:
            top = tk.Toplevel()
            top.title('Enrollment List')
            top.text = Listbox(top)
            top.text.grid(row=0, column=0)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            SList = [[' ', -1]]
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if grade.getDisciplineID() == disciplineID:
                    for student in self._studentControl.getCurentRepo(
                    ).getStudents():
                        if student.getId() == grade.getStudentID():
                            if grade.getGrade() != []:
                                gradeAvg = self.listAvg(
                                    grade.getGrade(), grade.getGradeSize())
                                SList.append([student.getName(), gradeAvg])

            SList.sort(key=itemgetter(1), reverse=True)
            del SList[-1]
            for index in SList:
                top.text.insert(END, index)
            del SList[:]

        except TclError:
            top.destroy()
            self.displayError('No disicpline Selected')

    def FailingStudents(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        for grade in self._gradeControl.getCurentRepo().getGrades():
            for student in self._studentControl.getCurentRepo().getStudents():
                for discipline in self._disciplineControl.getCurentRepo(
                ).getDisciplines():
                    if grade.getStudentID() == student.getId():
                        if grade.getDisciplineID() == discipline.getId():
                            if grade.getGrade() != []:
                                gradeAvg = self.listAvg(
                                    grade.getGrade(), grade.getGradeSize())
                                if gradeAvg < 5:
                                    sList.append([
                                        student.getName(),
                                        discipline.getName()
                                    ])

        for index in sList:
            top.text.insert(END, '\n' + index[0] + ' - ' + index[1])
        del sList[:]

    def BestStudents(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        gList = []
        sName = ''
        for student in self._studentControl.getCurentRepo().getStudents():
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if student.getId() == grade.getStudentID():
                    if (grade.getGrade() != []):
                        gAvg = self.listAvg(grade.getGrade(),
                                            grade.getGradeSize())
                        gList.append(gAvg)
                        sName = student.getName()
            if gList != []:
                sAvg = self.listAvg(gList, len(gList))
                sList.append([sName, round(sAvg, 2)])

        sList.sort(key=itemgetter(1), reverse=True)
        for index in range(1, len(sList)):
            top.text.insert(
                END, str(sList[index][0] + ' - ' + str(sList[index][1])))
        del sList[:]

    def DisciplineH(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        gList = []
        dName = ''
        for discipline in self._disciplineControl.getCurentRepo(
        ).getDisciplines():
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if discipline.getId() == grade.getDisciplineID():
                    if (grade.getGrade() != []):
                        gAvg = self.listAvg(grade.getGrade(),
                                            grade.getGradeSize())
                        gList.append(gAvg)
                        dName = discipline.getName()
            if gList != []:
                sAvg = self.listAvg(gList, len(gList))
                sList.append([dName, round(sAvg, 2)])

        sList.sort(key=itemgetter(1), reverse=True)

        for index in range(1, len(sList)):
            top.text.insert(
                END,
                '\n' + str(sList[index][0]) + ' - ' + str(sList[index][1]))
        del sList[:]

    '''
    #======================================#
    :EDIT:
    #======================================#
    '''

    def undo(self, event):

        self._undoControl.undo()
        self.refreshALL()

    def redo(self, event):

        self._undoControl.redo()
        self.refreshALL()

    '''
    #===========================================================================================#
    :Widgets:
    #===========================================================================================#
    '''

    def createWidgets(self):
        '''
        #==================================================#
        :TOPBAR:
        #==================================================#
        '''
        self.fileButton = Menubutton(self, text='File', relief='flat')
        self.fileButton.grid(row=0, column=0)

        self.fileButton.menu = Menu(self.fileButton, tearoff=0)
        self.fileButton["menu"] = self.fileButton.menu

        self.fileButton.menu.add_command(label="New", command=self.NewFile)
        self.fileButton.menu.add_command(label="Exit", command=self.quit)

        self.eButton = Menubutton(self, text="Enrollment", relief='flat')
        self.eButton.grid(row=0, column=1)

        self.eButton.menu = Menu(self.eButton, tearoff=0)
        self.eButton["menu"] = self.eButton.menu

        self.eButton.menu.add_command(label="Add Enrollment",
                                      command=self.add_Enroll)

        self.statButton = Menubutton(self, text="Statistics", relief='flat')
        self.statButton.grid(row=0, column=2)

        self.statButton.menu = Menu(self.statButton, tearoff=0)
        self.statButton["menu"] = self.statButton.menu

        self.discMenu = Menu(tearoff=0)
        self.discMenu.add_command(label="Sort by name",
                                  command=self.StudentEnrollA)
        self.discMenu.add_command(label="Sort by grade",
                                  command=self.StudentEnrollB)

        self.statButton.menu.add_cascade(
            label="Students Enrolled at disicpline", menu=self.discMenu)
        self.statButton.menu.add_command(label="Failing Students",
                                         command=self.FailingStudents)
        self.statButton.menu.add_command(label="Best Students",
                                         command=self.BestStudents)
        self.statButton.menu.add_command(label="Discipline Averages",
                                         command=self.DisciplineH)

        self.searchButton = Menubutton(self, text="Search", relief='flat')
        self.searchButton.grid(row=0, column=3)

        self.searchButton.menu = Menu(self.searchButton, tearoff=0)
        self.searchButton["menu"] = self.searchButton.menu

        self.searchButton.menu.add_command(label="Search",
                                           command=self.SearchALL)

        self.editButton = Menubutton(self, text="Edit", relief='flat')
        self.editButton.grid(row=0, column=4)

        self.editButton.menu = Menu(self.editButton, tearoff=0)
        self.editButton["menu"] = self.editButton.menu

        self.editButton.menu.add_command(label="Undo", command=self.undo)
        self.editButton.menu.add_command(label="Redo", command=self.redo)

        self.root.bind('<Control-z>', self.undo)
        self.root.bind('<Control-y>', self.redo)
        '''
        #===================================================#
        :Student:
        #===================================================#
        '''

        self.sbar = Label(self,
                          text='Student list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.sbar.grid(row=1, column=0, columnspan=16)

        self.sList = Listbox(self, exportselection=0)
        for index in self._studentControl.getCurentRepo().getStudents():
            self.sList.insert(END, index)
        self.sList.grid(row=2, column=0, columnspan=16)
        self.sList.config(width=57, height=40)

        self.sMenu = Menu(self, tearoff=0)
        self.sMenu.add_command(label="Add Student", command=self.add_Student)
        self.sMenu.add_command(label="Remove Student",
                               command=self.remove_Student)
        self.sMenu.add_command(label='Update Student ID',
                               command=self.update_StudentID)
        self.sMenu.add_command(label='Update Student name',
                               command=self.update_StudentName)
        self.sMenu.add_command(label='Refresh', command=self.Srefresh)
        self.sList.bind("<Button-3>", self.sPopup)
        '''
        #===================================================#
        :Discipline:
        #===================================================#
        '''
        self.dbar = Label(self,
                          text='Discipline list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.dbar.grid(row=1, column=16, columnspan=16)

        self.dList = Listbox(self, exportselection=0)
        for index in self._disciplineControl.getCurentRepo().getDisciplines():
            self.dList.insert(END, index)
        self.dList.grid(row=2, column=16, columnspan=16)
        self.dList.config(width=57, height=40)

        self.dMenu = Menu(self, tearoff=0)
        self.dMenu.add_command(label="Add Discipline",
                               command=self.add_Discipline)
        self.dMenu.add_command(label="Remove Discipline",
                               command=self.remove_Discipline)
        self.dMenu.add_command(label='Update Discipline ID',
                               command=self.update_DisciplineID)
        self.dMenu.add_command(label='Update Discipline name',
                               command=self.update_DisciplineName)
        self.dMenu.add_command(label='Refresh', command=self.Drefresh)
        self.dList.bind("<Button-3>", self.dPopup)
        '''
        #===================================================#
        :Enroll:
        #===================================================#
        '''

        self.ebar = Label(self,
                          text='Enroll list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.ebar.grid(row=1, column=32, columnspan=16)

        self.eList = Listbox(self, exportselection=0)
        for index in self._enrolControl.getCurentRepo().getEnroll():
            self.eList.insert(END, '\n' + str(index))
        self.eList.grid(row=2, column=32, columnspan=16)
        self.eList.config(width=57, height=40)

        self.eMenu = Menu(self, tearoff=0)
        self.eMenu.add_command(label="Remove Enrollment",
                               command=self.remove_Enroll)
        self.eMenu.add_command(label="Grade Student",
                               command=self.add_EnrollGrade)
        self.eMenu.add_command(label='Refresh', command=self.Erefresh)
        self.eList.bind("<Button-3>", self.ePopup)
        '''
        #===================================================#
        :Grade:
        #===================================================#
        '''
        self.gbar = Label(self,
                          text='Grade list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.gbar.grid(row=1, column=48, columnspan=16)

        self.gList = Listbox(self, exportselection=0)
        for index in self._gradeControl.getCurentRepo().getGrades():
            self.gList.insert(END, '\n' + str(index))
        self.gList.grid(row=2, column=48, columnspan=16)
        self.gList.config(width=57, height=40)

        self.gMenu = Menu(self, tearoff=0)
        self.gMenu.add_command(label="Grade Student", command=self.add_Grade)
        self.gMenu.add_command(label='Refresh', command=self.Grefresh)
        self.gList.bind("<Button-3>", self.gPopup)

    def __init__(self,
                 studentControl,
                 disciplineControl,
                 gradeControl,
                 enrolControl,
                 U1,
                 master=None):
        Frame.__init__(self, master)
        self.pack()
        self.grid()
        self.Max = 0
        self.oCont = 0
        self.root = master

        self._studentControl = studentControl
        self._disciplineControl = disciplineControl
        self._gradeControl = gradeControl
        self._enrolControl = enrolControl
        self._undoControl = U1

        self.createWidgets()

    @staticmethod
    def listAvg(myList, size):
        s = 0.0
        for index in range(size):
            s += myList[index]
        s /= size
        return s
class App(tk.Frame):
    def __init__(self, master, *args, **kw):
        super().__init__(master, *args, **kw)
        self.root = master
        self.master.title('Rebuild List')
        # Width, Height of application
        self.master.geometry("775x700")
        self.store = Combobox_Autocomplete
        self.alldicts = {}
        self.create_widgets()
        self.create_widgets1()
        self.refresh_button()

    def create_widgets(self, *args):
        # Calculate button
        self.imgtitle = ImageTk.PhotoImage(
            Image.open(
                'C:\\Users\\Chris\\PycharmProjects\\untitled\\snapsrebuild.png'
            ))
        self.lab = tk.Label(image=self.imgtitle)
        self.lab.grid(row=0, column=3, padx=20, pady=20)
        # Heading Labels
        # Consumable Label
        self.consume_label = tk.Label(self.root,
                                      text='Items:',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=0, columnspan=3, padx=50)
        # Rebuild List Center Text
        self.consume_label = tk.Label(self.root,
                                      text='Rebuild List',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=3, padx=50)
        # Armour Text
        self.consume_label = tk.Label(self.root,
                                      text='items:',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=5, columnspan=3, padx=50)
        #######################################################################################################################
        #                                               Left Side buttons and input
        #######################################################################################################################
        # 111111
        # Check Button Number One
        self.is_checked = IntVar()
        self.option_yes = tk.Checkbutton(self.root,
                                         text="",
                                         onvalue=1,
                                         offvalue=0,
                                         variable=self.is_checked,
                                         command=self.callback)
        self.option_yes.grid(row=2, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_0 = tk.StringVar()
        self.combobox_autocomplete = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_0,
            highlightthickness=1)
        self.combobox_autocomplete.grid(row=2, column=1)
        # Insert button
        self.insert_butt = tk.Button(self.root,
                                     text='Insert',
                                     command=lambda: self.commando())
        self.insert_butt.grid(row=2, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Two                                                                                22222
        self.is_checked1 = IntVar()
        self.option_yes1 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked1,
                                          command=self.callback1)
        self.option_yes1.grid(row=3, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_1 = tk.StringVar()
        self.combobox_autocomplete1 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_1,
            highlightthickness=1)
        self.combobox_autocomplete1.grid(row=3, column=1)
        # Insert button
        self.insert_butt1 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando1())
        self.insert_butt1.grid(row=3, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Three                                                                             3333333
        self.is_checked2 = IntVar()
        self.option_yes2 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked2,
                                          command=self.callback2)
        self.option_yes2.grid(row=4, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_2 = tk.StringVar()
        self.combobox_autocomplete2 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_2,
            highlightthickness=1)
        self.combobox_autocomplete2.grid(row=4, column=1)
        # Insert button
        self.insert_butt2 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando2())
        self.insert_butt2.grid(row=4, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Four                                                                              4444444
        self.is_checked3 = IntVar()
        self.option_yes3 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked3,
                                          command=self.callback3)
        self.option_yes3.grid(row=5, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_3 = tk.StringVar()
        self.combobox_autocomplete3 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_3,
            highlightthickness=1)
        self.combobox_autocomplete3.grid(row=5, column=1)
        # Insert button
        self.insert_butt3 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando3())
        self.insert_butt3.grid(row=5, column=2, padx=10)
        ########################################################################################################################
        # Parts list (listbox)                                                                                 LISTBOX:
        self.list_box = Listbox(self.root,
                                border=0,
                                width=40,
                                height=20,
                                justify='center')
        self.list_box.grid(row=2, rowspan=5, column=3, pady=5)
        # Create scrollbar
        self.scrollbar = tk.Scrollbar(self.root)
        self.scrollbar.grid(row=3, column=4)
        # Set scrollbar to parts
        self.list_box.configure(yscrollcommand=self.scrollbar.set)
        self.scrollbar.configure(command=self.list_box.yview)

    ########################################################################################################################
    # LEFT SIDE FUNCTIONS
    ########################################################################################################################
    # Insert Button On the left right
    def commando(self):
        x = 'Consumables'
        self.alldicts.update({x: (self.entry_0.get())})
        self.list_box.delete(0)
        self.list_box.insert(0, self.entry_0.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando1(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_1.get())})
        self.list_box.delete(1)
        self.list_box.insert(1, self.entry_1.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()
        # Insert Button On the left right

    def commando2(self):
        x = 'Consumables2'
        self.alldicts.update({x: (self.entry_2.get())})
        self.list_box.delete(2)
        self.list_box.insert(2, self.entry_2.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()
        # Insert Button On the left right

    def commando3(self):
        x = 'Consumables3'
        self.alldicts.update({x: (self.entry_3.get())})
        self.list_box.delete(3)
        self.list_box.insert(3, self.entry_3.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    #######################################################################################################################
    def callback(self):
        if self.is_checked.get():
            self.list_box.itemconfig(0, {'bg': 'green'})
        else:
            self.list_box.itemconfig(0, {'bg': '#ffffff'})

    def callback1(self):
        if self.is_checked1.get():
            self.list_box.itemconfig(1, {'bg': 'green'})
        else:
            self.list_box.itemconfig(1, {'bg': '#ffffff'})

    def callback2(self):
        if self.is_checked2.get():
            self.list_box.itemconfig(2, {'bg': 'green'})
        else:
            self.list_box.itemconfig(2, {'bg': '#ffffff'})

    def callback3(self):
        if self.is_checked3.get():
            self.list_box.itemconfig(3, {'bg': 'green'})
        else:
            self.list_box.itemconfig(3, {'bg': '#ffffff'})

    ########################################################################################################################
    # RIGHT SIDE BUTTONS AND LABELS
    ########################################################################################################################
    # 5555555
    def create_widgets1(self, *args):
        # Check Button Number One
        self.is_checked4 = IntVar()
        self.option_yes4 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked4,
                                          command=self.callback4)
        self.option_yes4.grid(row=2, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_4 = tk.StringVar()
        self.combobox_autocomplete4 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_4,
            highlightthickness=1)
        self.combobox_autocomplete4.grid(row=2, column=6)
        # Insert button
        self.insert_butt4 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando4())
        self.insert_butt4.grid(row=2, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Two                                                                               666666
        self.is_checked5 = IntVar()
        self.option_yes5 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked5,
                                          command=self.callback5)
        self.option_yes5.grid(row=3, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_5 = tk.StringVar()
        self.combobox_autocomplete5 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_5,
            highlightthickness=1)
        self.combobox_autocomplete5.grid(row=3, column=6)
        # Insert button
        self.insert_butt5 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando5())
        self.insert_butt5.grid(row=3, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Three                                                                             777777
        self.is_checked6 = IntVar()
        self.option_yes6 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked6,
                                          command=self.callback6)

        self.option_yes6.grid(row=4, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_6 = tk.StringVar()
        self.combobox_autocomplete6 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_6,
            highlightthickness=1)
        self.combobox_autocomplete6.grid(row=4, column=6)
        # Insert button
        self.insert_butt6 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando6())
        self.insert_butt6.grid(row=4, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Four                                                                             888888
        self.is_checked7 = IntVar()
        self.option_yes7 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked7,
                                          command=self.callback7)

        self.option_yes7.grid(row=5, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_7 = tk.StringVar()
        self.combobox_autocomplete7 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_7,
            highlightthickness=1)
        self.combobox_autocomplete7.grid(row=5, column=6)
        # Insert button
        self.insert_butt7 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando7())
        self.insert_butt7.grid(row=5, column=5, padx=10)

    ########################################################################################################################
    #        FUNCTIONS FOR THE RIGHT SIDE
    ########################################################################################################################
    # Insert Buttons on the right side
    def commando4(self):
        x = 'Consumables'
        self.alldicts.update({x: (self.entry_4.get())})
        self.list_box.delete(4)
        self.list_box.insert(4, self.entry_4.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando5(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_5.get())})
        self.list_box.delete(5)
        self.list_box.insert(5, self.entry_5.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando6(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_6.get())})
        self.list_box.delete(6)
        self.list_box.insert(6, self.entry_6.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando7(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_7.get())})
        self.list_box.delete(7)
        self.list_box.insert(7, self.entry_7.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    ########################################################################################################################
    def callback4(self):
        if self.is_checked4.get():
            self.list_box.itemconfig(4, {'bg': 'green'})
        else:
            self.list_box.itemconfig(4, {'bg': '#ffffff'})

    def callback5(self):
        if self.is_checked5.get():
            self.list_box.itemconfig(5, {'bg': 'green'})
        else:
            self.list_box.itemconfig(5, {'bg': '#ffffff'})

    def callback6(self):
        if self.is_checked6.get():
            self.list_box.itemconfig(6, {'bg': 'green'})
        else:
            self.list_box.itemconfig(6, {'bg': '#ffffff'})

    def callback7(self):
        if self.is_checked7.get():
            self.list_box.itemconfig(7, {'bg': 'green'})
        else:
            self.list_box.itemconfig(7, {'bg': '#ffffff'})

    #########################################################################################################################
    # Refresh button
    def refresh_button(self, *args):
        self.refresher = tk.Button(self.root,
                                   text='Refresh',
                                   command=lambda: self.refresh())
        self.refresher.grid(row=7, column=3, pady=10)

    # Need to refresh the colours that have been checked already, must clear the list box.
    def refresh(self, *args):
        self.list_box.delete(0, END)
        self.combobox_autocomplete.delete(0, "end")
        self.combobox_autocomplete1.delete(0, "end")
        self.combobox_autocomplete2.delete(0, "end")
        self.combobox_autocomplete3.delete(0, "end")
        self.combobox_autocomplete4.delete(0, "end")
        self.combobox_autocomplete5.delete(0, "end")
        self.combobox_autocomplete6.delete(0, "end")
        self.combobox_autocomplete7.delete(0, "end")
Beispiel #42
0
class ListHeap(Frame):
    """
    A widget that encapsulates a list box, allow adding and delete and contextual interaction
        with a set of items in a list box
    """

    def __init__(self, parent, populator, max_limit=sys.maxint):
        """

        :param parent:          The parent tk item
        :param max_limit:       The maximum number of items allowed to be added to the listheap
        :return:
        """
        Frame.__init__(self, parent)
        self._items = {}
        self._parent = parent
        self._max_limit = max_limit
        self._listbox = Listbox(self, selectmode=SINGLE)
        self._listbox.grid(row=0, column=0)

        # Bind mouse events
        self._listbox.bind("<Double-Button-1>", self._handle_db_click)
        self._listbox.bind("<Button-2>", self._handle_r_click)

        # Populate the widget with custom params if they are available
        if populator is not None:
            self.populate(populator)

    def populate(self, populator):
        """
        Override to define the population paramaters for this widget
        This allows default values to be provided
        """
        pass

    def add_new(self, item, key):
        """
        Add new item to the list heap

        Adds a new item to the list box and the data structure that defines the heap

        :param item:            The item to be added to the ListHeap
        :param key:             The key that is to be used to identify the item, must be unique
        :throws:                DuplicateListHeapItemException  - duplicate key attempted to add to the heap
        :throws:                MaxItemLimitReachedException    - Attempted item addition when max sized already reached
        """
        if key in self._items:
            raise DuplicateListHeapItemException(key)
        if len(self._items) >= self._max_limit:
            raise MaxItemLimitReachedException()
        self._items[key] = item
        self._listbox.insert(END, key)

    def _remove(self, key):
        """
        Remove an item from the ListHeap
        :param key:             The key of the item that is to be removed
        """
        del self._items[key]
        self._listbox.delete(ANCHOR)

    def _remove_all(self):
        """
        Removes all of the items from the ListHeap
        """
        self._items.clear()
        self._listbox.delete(0, END)

    def _handle_db_click(self, event):
        """
        Override: define a handler for the doubleclick event on the ListHeap
        :param event:           The tk event generated by user input
        """
        pass

    def _handle_r_click(self, event):
        """
        Override: Define a handler for the rightclick event on the ListHeap
        :param event:           The tk event generated by user input
        """
        pass
Beispiel #43
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.parent = master

        self.dict = scrapeStart()
        self.initUI()


    def initUI(self):
        """ Build the grid """
        self.grid()
        for r in range(66):
            self.parent.rowconfigure (r, weight = 1)
        for c in range(8):
            self.parent.columnconfigure (c, weight = 1)
        """ Center the window on the display """
        width = 768
        height = 1024

        screenWidth = self.parent.winfo_screenwidth()
        screenHeight = self.parent.winfo_screenheight()

        x = (screenWidth - width) / 2
        y = (screenHeight - height) / 2

        self.parent.geometry('%dx%d+%d+%d' % (width, height, x, y))
        self.parent.configure(bg = "grey10")

        status = "home"
        self.drawScreen(status)


    def drawScreen(self, status):
        print ("%s is the status" % status)

        if (status == "home"):
            self.drawHome()
        elif (status == "film"):
            self.drawFilm()
        elif (status == "recipes"):

            self.drawRecipes()
        else:
            print('Bad mojo')


    def drawHome(self):
        infoText = ("Some Louisiana urban environments have a multicultural, multilingual heritage, being so strongly "
            "by an admixture of 18th century French, Spanish, Native American (Indian), and African cultures that they "
            "are considered to be somewhat exceptional in the U.S. Before the American influx and statehood at the "
            "beginning of the 19th century, the territory of current Louisiana State had been both a Spanish and "
            "French colony. In addition, the pattern of development included importing numerous African slaves in "
            "the 18th century, with many from the same region of West Africa, thus concentrating their culture.")

        self.img = ImageTk.PhotoImage(Image.open("louisiana.png"))

        self.title = Label(self.parent, width = 1, height = 1, text = "Louisiana", fg = "white", bg = "grey30",
                        font = ("Times 48 italic"), bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.info = Label(self.parent, width = 1, height = 1, text = infoText, fg = "white", bg = "grey30",
                        font = ("Times 14"), bd = 5, relief = RAISED, wraplength = 350, justify = LEFT)
        self.info.grid(row = 23, column = 4, rowspan = 24, columnspan = 4, sticky = W+E+N+S)

        self.image1 = Label(self.parent, width = 1, height = 1, image = self.img, bg = "grey10")
        self.image1.grid(row = 23, column = 0, rowspan = 24, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Recipes", command = lambda: self.drawScreen("recipes"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button3 = Button()
        self.Button3.grid_remove()
        self.Button4 = Button()
        self.Button4.grid_remove()
        self.Button5 = Button()
        self.Button5.grid_remove()
        self.listbox = Listbox()
        self.listbox.grid_remove()
        self.image2 = Label()
        self.image2.grid_remove()


    def drawFilm(self):
        self.title = Label(self.parent, text = "Film", fg="white", bg="grey30", font=("Times 48 italic"),
                        bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Recipes", command = lambda: self.drawScreen("recipes"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.info.grid_remove()
        self.image1.grid_remove()
        self.image2.grid_remove()
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.listbox.grid_remove()


    def drawRecipes(self):
        self.title = Label(self.parent, text = "Recipes", fg="white", bg="grey30", font=("Times 48 italic"),
                        bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button3 = Button(self.parent, text = "Gumbo", command = self.drawRecipeList)
        self.Button3.grid(row = 24, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button4 = Button(self.parent, text = "Jambalaya", command = self.quit)
        self.Button4.grid(row = 29, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button5= Button(self.parent, text = "Seafood", command = self.quit)
        self.Button5.grid(row = 34, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.info.grid_remove()
        self.image1.grid_remove()
        self.listbox.grid_remove()
        self.image2.grid_remove()


    def drawRecipeList(self):
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.image2.grid_remove()

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.listbox = Listbox(self.parent)
        for key in self.dict:
            index = 1
            self.listbox.insert(index, key)
            index += 1
        self.listbox.grid(row = 29, column = 1, rowspan = 12, columnspan = 6, sticky = W+E+N+S)
        self.listbox.bind("<<ListboxSelect>>", self.get_List)


    def get_List(self, *args):
        self.info.grid_remove()
        self.image1.grid_remove()
        self.image2.grid_remove()
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.listbox.grid_remove()

        self.index = self.listbox.curselection()

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.img2 = ImageTk.PhotoImage(Image.open("creole_gumbo.png"))
        self.image2 = Label(self.parent, width = 1, height = 1, image = self.img2, bg = "grey10")
        self.image2.grid(row = 21, column = 1, rowspan = 34, columnspan = 6, sticky = W+E+N+S)
Beispiel #44
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)
        self.mutex = Lock()

    def prepare(self):
        self.deviceList.config(state='normal')
        self.versionList.config(state='disabled')
        self.engList.config(state='disabled')
        self.packageList.config(state='disabled')
        self.ok.config(state='disabled')
        self.setData(self.controller.data)
        self.setDeviceList(self.data.keys())
        self.controller.setDefault(self, self.controller.loadOptions())
        self.deviceList.focus_force()

    def printErr(self, message):
        self.errLog.config(text=message)

    def setData(self, data):
        self.data = data

    def setupView(self, title="Select your flash", data=None):
        if(data):
            self.setData(data)
        self.errLog = Label(self, text="")
        self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE")
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self,
                         text='Next',
                         command=lambda: self.
                         confirm())
        self.ok.grid(row=4, column=3, sticky="E")
        self.ok.config(state="disabled")
        self.deviceLabel = Label(self, text="Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        self.deviceList.grid(row=2, column=0)
        self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect)
        self.deviceList.config(state="disabled")
        self.versionLabel = Label(self, text="Branch", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        self.versionList.grid(row=2, column=1)
        self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect)
        self.versionList.config(state="disabled")
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=2)
        self.engList = Listbox(self, exportselection=0)
        self.engList.grid(row=2, column=2)
        self.engList.bind('<<ListboxSelect>>', self.engOnSelect)
        self.engList.config(state="disabled")
        self.packageLabel = Label(
            self,
            text="Gecko/Gaia/Full",
            font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=3)
        self.packageList = Listbox(self, exportselection=0)
        self.packageList.grid(row=2, column=3)
        self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect)
        self.packageList.config(state="disabled")
        self.bidVar = StringVar()
        Label(self, text="Build ID").grid(row=3, column=0, sticky='E')
        self.bidInput = Entry(
            self,
            textvariable=self.bidVar,
            width="30")
        self.bidInput.grid(
            row=3,
            column=1,
            columnspan=2,
            sticky="W")
        self.bidVar.set('latest')
        # binding unfocus for build id field
        self.bidInput.bind('<FocusOut>', self.updateBuildId)
        # binding the Return Key to each componments
        self.deviceList.bind('<Return>', self.pressReturnKey)
        self.versionList.bind('<Return>', self.pressReturnKey)
        self.engList.bind('<Return>', self.pressReturnKey)
        self.packageList.bind('<Return>', self.pressReturnKey)
        self.bidInput.bind('<Return>', self.pressReturnKey)
        self.ok.bind('<Return>', self.pressReturnKey)

    def selection_all_checked(self):
        result = False
        if len(self.deviceList.curselection()) == 0:
            self.logger.log('Please select device.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.deviceList.focus_set()
        elif len(self.versionList.curselection()) == 0:
            self.logger.log('Please select branch.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.versionList.focus_set()
        elif len(self.engList.curselection()) == 0:
            self.logger.log('Please select user or engineer build.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.engList.focus_set()
        elif len(self.packageList.curselection()) == 0:
            self.logger.log('Please select package to flash.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.packageList.focus_set()
        elif len(self.bidVar.get()) == 0:
            self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr)
            self.bidVar.set('latest')
        else:
            result = True
        return result

    def updateBuildId(self, event=None):
        if len(self.engList.curselection()) != 0:
            self.refreshPackageList()

    def pressReturnKey(self, event=None):
        if self.selection_all_checked():
            self.ok.config(state="disabled")
            self.confirm()

    def deviceOnSelect(self, evt):
        self.setVersionList()

    def versionOnSelect(self, evt):
        self.setEngList()

    def engOnSelect(self, evt):
        self.refreshPackageList()  # hard coded right now

    def packageOnSelect(self, evt):
        self.ok.config(state="normal")

    def confirm(self):
        self.mutex.acquire()
        try:
            if self.selection_all_checked():
                self.ok.config(state="disabled")
                params = []
                package = self.packageList.get(self.packageList.curselection()[0])
                self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr)
                if(PathParser._IMAGES in package):
                    params.append(PathParser._IMAGES)
                else:
                    if(PathParser._GAIA in package):
                        params.append(PathParser._GAIA)
                    if(PathParser._GECKO in package):
                        params.append(PathParser._GECKO)
                self.controller.doFlash(params)
                self.packageList.select_clear(0, END)
                self.controller.transition(self)
        finally:
            self.mutex.release()

    def setDeviceList(self, device=[]):
        self.deviceList.delete(0, END)
        for li in device:
            self.deviceList.insert(END, li)

    def setVersionList(self, version=[]):
        if len(version) == 0:
            version = self.data[
                self.deviceList.get(self.deviceList.curselection())
                ]
        self.versionList.config(state="normal")
        self.engList.config(state="disabled")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.versionList.delete(0, END)
        for li in version:
            self.versionList.insert(END, li)

    def setEngList(self, eng=[]):
        if len(eng) == 0:
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.data[device][version]
        self.engList.config(state="normal")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.engList.delete(0, END)
        for li in eng:
            self.engList.insert(END, li)

    def refreshPackageList(self):
        self.mutex.acquire()
        try:
            self.packageList.config(state="normal")
            self.ok.config(state="normal")
            self.packageList.delete(0, END)
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.engList.get(self.engList.curselection())
            # if the value is '' or 'latest', the set the build_id option as ''.
            buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get()
            package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId)
            if len(package) == 0:
                package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES]
            for li in package:
                self.packageList.insert(END, li)
        finally:
            self.mutex.release()
Beispiel #45
0
class TkApp:
    def __init__(self, ncffile, options):
        try:
            from Tkinter import Checkbutton, Frame, Label, Scrollbar
            from Tkinter import Listbox, Button, IntVar, Tk, VERTICAL
            from Tkinter import EXTENDED, END, N, S, SINGLE, Entry
            from Tkinter import StringVar, Text, DISABLED, LEFT
        except Exception:
            try:
                from tkinter import Checkbutton, Frame, Label, Scrollbar
                from tkinter import Listbox, Button, IntVar, Tk, VERTICAL
                from tkinter import EXTENDED, END, N, S, SINGLE, Entry
                from tkinter import StringVar, Text, DISABLED, LEFT
            except Exception:
                warn('tkinter unavailable')

        master = self.root = Tk()
        self.ncffile = ncffile
        self.options = options
        self.plotted_variables = set()
        frame = Frame(master)
        frame.grid(row=0)
        codeframe = Frame(master)
        codeframe.grid(row=1)
        metaframe = Frame(master)
        metaframe.grid(row=2)
        goframe = Frame(frame)
        goframe.grid(column=3, row=1)

        var_label = Label(frame, text='Select Variable')
        var_label.grid(column=0, row=0)
        var_scrollbar = Scrollbar(frame, orient=VERTICAL)
        var_scrollbar.grid(column=1, row=1, sticky=N + S)
        self.var = Listbox(frame, selectmode=EXTENDED,
                           exportselection=0,
                           yscrollcommand=var_scrollbar.set)
        self.var.grid(column=0, row=1)
        var_scrollbar.config(command=self.var.yview)

        what_to_do = Label(frame, text='Execute')
        what_to_do.grid(column=2, row=0)
        self.method_list = Listbox(frame, selectmode=SINGLE, exportselection=0)
        self.method_list.grid(column=2, row=1)
        self.pre_txt = StringVar()
        pre_label = Label(codeframe, text='Before any figures, execute code')
        self.pre_txt.set(_pre_code)
        pre_label.grid(row=2, sticky='W')
        self.pre = Entry(codeframe, width=120, textvariable=self.pre_txt)
        self.pre.grid(row=3, sticky='E')

        self.before_txt = StringVar()
        self.before_txt.set(_before_code)
        before_label = Label(
            codeframe, text='Before each figure, execute code')
        before_label.grid(row=4, sticky='W')
        self.before = Entry(codeframe, width=120, textvariable=self.before_txt)
        self.before.grid(row=5, sticky='E')

        self.after_txt = StringVar()
        self.after_txt.set(_after_code)
        after_label = Label(codeframe, text='After each figure, execute code')
        after_label.grid(row=6, sticky='W')
        self.after = Entry(codeframe, width=120, textvariable=self.after_txt)
        self.after.grid(row=7, sticky='E')

        self.post_txt = StringVar()
        self.post_txt.set(_post_code)
        post_label = Label(codeframe, text='After all figures, execute code')
        post_label.grid(row=8, sticky='W')
        self.post = Entry(codeframe, width=120, textvariable=self.post_txt)
        self.post.grid(row=9, sticky='E')

        options_label = Label(goframe, text='Options:')
        options_label.grid(column=0, row=1, sticky='W')
        self.logscale = IntVar()
        self.logscale.set(0)
        c = Checkbutton(goframe, text="log-scale?", variable=self.logscale)
        c.grid(column=0, row=2, sticky='W')

        self.coastlines = IntVar()
        self.coastlines.set(_coastlines_opt)
        coastlines = Checkbutton(
            goframe, text="coastlines?", variable=self.coastlines,
            justify=LEFT)
        coastlines.grid(column=0, row=3, sticky='W')

        self.countries = IntVar()
        self.countries.set(_countries_opt)
        countries = Checkbutton(
            goframe, text="countries?", variable=self.countries, justify=LEFT)
        countries.grid(column=0, row=4, sticky='W')

        self.states = IntVar()
        self.states.set(_states_opt)
        states = Checkbutton(goframe, text="states?",
                             variable=self.states, justify=LEFT)
        states.grid(column=0, row=5, sticky='W')

        self.counties = IntVar()
        self.counties.set(_counties_opt)
        counties = Checkbutton(goframe, text="counties?",
                               variable=self.counties, justify=LEFT)
        counties.grid(column=0, row=6, sticky='W')

        self.execute_button = Button(
            goframe, text="Make Figure", command=self.execute)
        self.execute_button.grid(row=0, column=0, sticky='W')

        self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat',
                        'profile', 'timeseries', 'pressx', 'tileplot', 'plot']
        method_labels = ['lat-lon', 'press-lat', 'press-lon', 'time-lat',
                         'Vertical Profile', 'Time Series', 'press-? (2-D)',
                         'Tile Plot (2-D)', 'Plot (1-D)']
        for method in method_labels:
            self.method_list.insert(END, method)
        var_keys = [k for k, v in self.ncffile.variables.items()
                    if k not in _coordkeys]
        var_keys.sort()
        self.vars = []
        for spc in var_keys:
            self.var.insert(END, spc)
            self.vars.append(spc)

        meta_label = Label(metaframe, text='Common Data Language Header:')
        meta_label.grid(column=0, row=0, sticky='W')
        meta_scrollbar = Scrollbar(metaframe, orient=VERTICAL)
        meta_scrollbar.grid(column=1, row=1, sticky=N + S)
        self.meta = Text(metaframe, height=10, width=118, bg='white',
                         relief='flat', yscrollcommand=meta_scrollbar.set)
        self.meta.grid(column=0, row=1, sticky='W')
        from PseudoNetCDF.pncdump import pncdump
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        pdump = StringIO("")
        pncdump(self.ncffile, header=True, outfile=pdump, )
        pdump.seek(0, 0)
        self.meta.insert(END, pdump.read())
        self.meta.config(state=DISABLED)
        help = Button(goframe, text='Help', command=self.help)
        help.grid(column=0, row=7)
        quit = Button(goframe, text='Quit', command=self.quit)
        quit.grid(column=0, row=8)
        master.mainloop()

    def help(self):
        print("pl is pylab: details at matplotlib;")

    def quit(self):
        self.root.destroy()

    def _get_var(self, list):
        items = list.curselection()
        try:
            items = map(int, items)
        except Exception:
            pass
        items = [self.vars[i] for i in items]
        return items

    def get_var(self):
        return self._get_var(self.var)

    def get_methods(self):
        items = self.method_list.curselection()
        try:
            items = map(int, items)
        except Exception:
            pass
        items = [self.methods[i] for i in items]
        return items

    def execute(self):
        os.system('clear')
        vars = self.get_var()
        self.plotted_variables = self.plotted_variables.union(vars)
        methods, = self.get_methods()
        self.options.logscale = bool(self.logscale.get())
        self.options.coastlines = bool(self.coastlines.get())
        self.options.countries = bool(self.countries.get())
        self.options.states = bool(self.states.get())
        self.options.counties = bool(self.counties.get())
        self.options.pre_txt = self.pre_txt.get()
        self.options.before_txt = self.before_txt.get()
        self.options.after_txt = self.after_txt.get()
        self.options.post_txt = self.post_txt.get()
        plotwithopts(self.ncffile, methods, vars, self.options)
Beispiel #46
0
class Ordered_Listbox(Frame):
    def __init__(self,
                 master,
                 data=None,
                 ascending_order=True,
                 ignore_case=False,
                 autoscroll=False,
                 vscrollbar=True,
                 hscrollbar=False,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 **kwargs):
        Frame.__init__(self, master)

        self._ignore_case = ignore_case
        self._ascending_order = ascending_order

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

        self._listbox = Listbox(self, *kwargs)
        self._listbox.grid(row=0, column=0, sticky=N + E + W + S)

        scrollbar_kwargs = {}
        if scrollbar_background is not None:
            scrollbar_kwargs["background"] = scrollbar_background

        if scrollbar_troughcolor is not None:
            scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor

        if vscrollbar:
            self._vbar = Scrollbar(self,
                                   takefocus=0,
                                   command=self._listbox.yview,
                                   **scrollbar_kwargs)
            self._vbar.grid(row=0, column=1, sticky=N + S)

            if autoscroll:
                self._listbox.config(yscrollcommand=lambda f, l:
                                     make_autoscroll(self._vbar, f, l))
            else:
                self._listbox.config(yscrollcommand=self._vbar.set)

        if hscrollbar:
            self._hbar = Scrollbar(self,
                                   takefocus=0,
                                   command=self._listbox.xview,
                                   **scrollbar_kwargs)
            self._hbar.grid(row=0, column=1, sticky=E + W)

            if autoscroll:
                self._listbox.config(xscrollcommand=lambda f, l:
                                     make_autoscroll(self._hbar, f, l))
            else:
                self._listbox.config(xscrollcommand=self._hbar.set)

        if data is not None:
            for item in data:
                self.add_item(item)

    def add_item(self, item):
        list_of_items = self._listbox.get(0, END)

        index = bisect(list_of_items,
                       item,
                       ignore_case=self._ignore_case,
                       ascending_order=self._ascending_order)
        self._listbox.insert(index, item)

    def delete_item(self, item):
        list_of_items = self._listbox.get(0, END)
        index = bisect(list_of_items,
                       item,
                       ignore_case=self._ignore_case,
                       ascending_order=self._ascending_order)
        self._listbox.delete(index - 1)

    def selected_items(self):
        list_of_items = []

        for index in self._listbox.curselection():
            list_of_items.append(self._listbox.get(index))

        return list_of_items

    def selected_item(self):
        return self._listbox.curselection()[0]

    def deselect_all(self):
        self._listbox.selection_clear(0, END)

    def select(self, item):
        index = self.index(item)

        if index is None:
            return

        self._listbox.selection_set(index)

    def deselect(self, item):
        index = self.index(item)

        if index is None:
            return

        self._listbox.selection_clear(index)

    def index(self, item):
        list_of_items = self._listbox.get(0, END)

        try:
            index = list_of_items.index(item)
        except ValueError:
            return None

        return index

    def bind(self, event, handler):
        self._listbox.bind(event, handler)

    def clear(self):
        self._listbox.delete(1, END)

    def __iter__(self):
        return self.items

    @property
    def items(self):
        return self._listbox.get(0, END)
Beispiel #47
0
class GetKeysDialog(Toplevel):
    def __init__(self,parent,title,action,currentKeySequences,_htest=False):
        """
        action - string, the name of the virtual event these keys will be
                 mapped to
        currentKeys - list, a list of all key sequence lists currently mapped
                 to virtual events, for overlap checking
        _htest - bool, change box location when running htest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE,width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.action=action
        self.currentKeySequences=currentKeySequences
        self.result=''
        self.keyString=StringVar(self)
        self.keyString.set('')
        self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label
        self.modifier_vars = []
        for modifier in self.modifiers:
            variable = StringVar(self)
            variable.set('')
            self.modifier_vars.append(variable)
        self.advanced = False
        self.CreateWidgets()
        self.LoadFinalKeyList()
        self.withdraw() #hide while setting geometry
        self.update_idletasks()
        self.geometry(
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )  #centre dialog over parent (or below htest box)
        self.deiconify() #geometry set, unhide
        self.wait_window()

    def CreateWidgets(self):
        frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
        frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
        frameButtons=Frame(self)
        frameButtons.pack(side=BOTTOM,fill=X)
        self.buttonOK = Button(frameButtons,text='OK',
                width=8,command=self.OK)
        self.buttonOK.grid(row=0,column=0,padx=5,pady=5)
        self.buttonCancel = Button(frameButtons,text='Cancel',
                width=8,command=self.Cancel)
        self.buttonCancel.grid(row=0,column=1,padx=5,pady=5)
        self.frameKeySeqBasic = Frame(frameMain)
        self.frameKeySeqAdvanced = Frame(frameMain)
        self.frameControlsBasic = Frame(frameMain)
        self.frameHelpAdvanced = Frame(frameMain)
        self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.lift()
        self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.lift()
        self.buttonLevel = Button(frameMain,command=self.ToggleLevel,
                text='Advanced Key Binding Entry >>')
        self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5)
        labelTitleBasic = Label(self.frameKeySeqBasic,
                text="New keys for  '"+self.action+"' :")
        labelTitleBasic.pack(anchor=W)
        labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT,
                textvariable=self.keyString,relief=GROOVE,borderwidth=2)
        labelKeysBasic.pack(ipadx=5,ipady=5,fill=X)
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check=Checkbutton(self.frameControlsBasic,
                command=self.BuildKeyString,
                text=label,variable=variable,onvalue=modifier,offvalue='')
            check.grid(row=0,column=column,padx=2,sticky=W)
            self.modifier_checkbuttons[modifier] = check
            column += 1
        labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
                            text=\
                            "Select the desired modifier keys\n"+
                            "above, and the final key from the\n"+
                            "list on the right.\n\n" +
                            "Use upper case Symbols when using\n" +
                            "the Shift modifier.  (Letters will be\n" +
                            "converted automatically.)")
        labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
        self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
                selectmode=SINGLE)
        self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
        self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
        scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
                command=self.listKeysFinal.yview)
        self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
        scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
        self.buttonClear=Button(self.frameControlsBasic,
                text='Clear Keys',command=self.ClearKeySeq)
        self.buttonClear.grid(row=2,column=0,columnspan=4)
        labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
                text="Enter new binding(s) for  '"+self.action+"' :\n"+
                "(These bindings will not be checked for validity!)")
        labelTitleAdvanced.pack(anchor=W)
        self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
                textvariable=self.keyString)
        self.entryKeysAdvanced.pack(fill=X)
        labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
            text="Key bindings are specified using Tkinter keysyms as\n"+
                 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
                 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
                 "Upper case is used when the Shift modifier is present!\n\n" +
                 "'Emacs style' multi-keystroke bindings are specified as\n" +
                 "follows: <Control-x><Control-y>, where the first key\n" +
                 "is the 'do-nothing' keybinding.\n\n" +
                 "Multiple separate bindings for one action should be\n"+
                 "separated by a space, eg., <Alt-v> <Meta-v>." )
        labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)

    def SetModifiersForPlatform(self):
        """Determine list of names of key modifiers for this platform.

        The names are used to build Tk bindings -- it doesn't matter if the
        keyboard has these keys, it matters if Tk understands them. The
        order is also important: key binding equality depends on it, so
        config-keys.def must use the same ordering.
        """
        if sys.platform == "darwin":
            self.modifiers = ['Shift', 'Control', 'Option', 'Command']
        else:
            self.modifiers = ['Control', 'Alt', 'Shift']
        self.modifier_label = {'Control': 'Ctrl'} # short name

    def ToggleLevel(self):
        if  self.buttonLevel.cget('text')[:8]=='Advanced':
            self.ClearKeySeq()
            self.buttonLevel.config(text='<< Basic Key Binding Entry')
            self.frameKeySeqAdvanced.lift()
            self.frameHelpAdvanced.lift()
            self.entryKeysAdvanced.focus_set()
            self.advanced = True
        else:
            self.ClearKeySeq()
            self.buttonLevel.config(text='Advanced Key Binding Entry >>')
            self.frameKeySeqBasic.lift()
            self.frameControlsBasic.lift()
            self.advanced = False

    def FinalKeySelected(self,event):
        self.BuildKeyString()

    def BuildKeyString(self):
        keyList = modifiers = self.GetModifiers()
        finalKey = self.listKeysFinal.get(ANCHOR)
        if finalKey:
            finalKey = self.TranslateKey(finalKey, modifiers)
            keyList.append(finalKey)
        self.keyString.set('<' + string.join(keyList,'-') + '>')

    def GetModifiers(self):
        modList = [variable.get() for variable in self.modifier_vars]
        return [mod for mod in modList if mod]

    def ClearKeySeq(self):
        self.listKeysFinal.select_clear(0,END)
        self.listKeysFinal.yview(MOVETO, '0.0')
        for variable in self.modifier_vars:
            variable.set('')
        self.keyString.set('')

    def LoadFinalKeyList(self):
        #these tuples are also available for use in validity checks
        self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9',
                'F10','F11','F12')
        self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
        self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
        self.whitespaceKeys=('Tab','Space','Return')
        self.editKeys=('BackSpace','Delete','Insert')
        self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
                'Right Arrow','Up Arrow','Down Arrow')
        #make a tuple of most of the useful common 'final' keys
        keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
                self.whitespaceKeys+self.editKeys+self.moveKeys)
        self.listKeysFinal.insert(END, *keys)

    def TranslateKey(self, key, modifiers):
        "Translate from keycap symbol to the Tkinter keysym"
        translateDict = {'Space':'space',
                '~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
                '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
                '(':'parenleft',')':'parenright','_':'underscore','-':'minus',
                '+':'plus','=':'equal','{':'braceleft','}':'braceright',
                '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
                ':':'colon',',':'comma','.':'period','<':'less','>':'greater',
                '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
                'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
                'Down Arrow': 'Down', 'Tab':'Tab'}
        if key in translateDict.keys():
            key = translateDict[key]
        if 'Shift' in modifiers and key in string.ascii_lowercase:
            key = key.upper()
        key = 'Key-' + key
        return key

    def OK(self, event=None):
        if self.advanced or self.KeysOK():  # doesn't check advanced string yet
            self.result=self.keyString.get()
            self.destroy()

    def Cancel(self, event=None):
        self.result=''
        self.destroy()

    def KeysOK(self):
        '''Validity check on user's 'basic' keybinding selection.

        Doesn't check the string produced by the advanced dialog because
        'modifiers' isn't set.

        '''
        keys = self.keyString.get()
        keys.strip()
        finalKey = self.listKeysFinal.get(ANCHOR)
        modifiers = self.GetModifiers()
        # create a key sequence list for overlap check:
        keySequence = keys.split()
        keysOK = False
        title = 'Key Sequence Error'
        if not keys:
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No keys specified.')
        elif not keys.endswith('>'):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='Missing the final Key')
        elif (not modifiers
              and finalKey not in self.functionKeys + self.moveKeys):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No modifier key(s) specified.')
        elif (modifiers == ['Shift']) \
                 and (finalKey not in
                      self.functionKeys + self.moveKeys + ('Tab', 'Space')):
            msg = 'The shift modifier by itself may not be used with'\
                  ' this key symbol.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        elif keySequence in self.currentKeySequences:
            msg = 'This key combination is already in use.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        else:
            keysOK = True
        return keysOK
Beispiel #48
0
class Cell:
    def __init__(self, parent, type, x, y, height, temperature_multiplier,
                 moisture, owner):
        self.parent = parent

        self.type = type

        self.x = x
        self.y = y

        self.cell_id = self.parent.get_next_id('cell')

        self.id = -1

        self.building_capacity = 100

        self.terrain = Terrain(height, moisture)

        self.temperature_multiplier = max(0, temperature_multiplier)
        self.temperature = None

        self.buildings = building.base_buildings(None)

        self.high_temp_range = random.random() / 5
        self.low_temp_range = random.random() / 5

        self.owner = owner

        self.make_id()

        self.can_pass = not self.terrain.is_water()

    # Determines whether it is legal for a group to move onto this square
    # Kenny - detects whether or not the cell's terrain is water. If it is water unit can't move through
    def can_move(self, group):
        return self.can_pass  # For now it is always lega

    def save(self):
        self.parent.db.execute(
            'db/internal/terrain/cell_insert.sql', {
                'cell_id': self.cell_id,
                'type': self.type,
                'x': self.x,
                'y': self.y,
                'height': self.terrain.height,
                'temperature_multiplier': self.temperature_multiplier,
                'moisture': self.terrain.moisture,
                'owner': self.owner.id if self.owner is not None else -1,
                'building_capacity': self.building_capacity,
                'high_temp_range': self.high_temp_range,
                'low_temp_range': self.low_temp_range
            })

        for building in self.buildings:
            if building.number > 0:
                building.save(self.parent.db, self.cell_id)

    def get_population_capacity(self):
        return sum([
            building.get_population_capacity() for building in self.buildings
        ])

    def get_food_output(self):
        result = random.randint(BASE_CELL_MIN_FOOD_PRODUCTION,
                                BASE_CELL_FOOD_PRODUCTION)
        result *= self.food_production_multiplier()

        return result

    def building_count(self):
        return sum([building.number for building in self.buildings])

    def get_total_buiding_size(self):
        return sum([
            building.get_size() * building.number
            for building in self.buildings
        ])

    def get_available_building_capacity(self):
        multiplier = 1.0
        if self.owner is not None:
            best = self.owner.nation.tech.get_best_in_category(
                'compact_building')

            if best is not None:
                multiplier = best.multiplier

        return multiplier * self.building_capacity - self.get_total_buiding_size(
        )

    def build_buildings(self):
        improvement_chance = int((self.building_count() + 1) /
                                 (math.sqrt(self.owner.population) + 1))
        if random.randint(0, improvement_chance + 1) == 0:
            available_buildings = filter(
                lambda b: b.get_size() <= self.get_available_building_capacity(
                ), self.buildings)

            if len(available_buildings) > 0:
                build_building = utility.weighted_random_choice(
                    available_buildings,
                    weight=lambda _, b: 1.0 / b.get_cost())

                if self.owner.nation.money > build_building.get_cost():
                    self.owner.nation.money -= build_building.get_cost()
                    build_building.number += 1

    def get_resource_productions(self):
        result = {}
        for curBuilding in self.buildings:
            production = curBuilding.get_resource_productions()

            for resource in production:
                if resource in result:
                    result[resource] += production[resource]
                else:
                    result[resource] = production[resource]
        return result

    def get_tax_rate(self):
        return utility.product(
            [building.get_tax_rate() for building in self.buildings])

    def get_money_output(self):
        return sum(
            [building.get_money_output() for building in self.buildings])

    def get_elevation(self):
        return to_meters(self.terrain.height * MAX_HEIGHT)

    def get_high_temperature(self):
        return self.get_temperature(
        ) + self.get_temperature() * self.high_temp_range

    def get_low_temperature(self):
        return self.get_temperature(
        ) - self.get_temperature() * self.low_temp_range

    def get_temperature_range(self):
        return self.get_high_temperature() - self.get_low_temperature()

    def get_temperature(self):
        # The base temperature never changes, so we only need to calculate it once.
        if self.temperature is None:
            self.temperature = temperature(
                self.terrain.height * MAX_HEIGHT, self.y,
                utility.S_HEIGHT) * (1 - self.temperature_multiplier)

        return self.temperature

    # http://www.sciencedirect.com/science/article/pii/0002157177900073
    def get_dew_point(self):
        return 0.0023 * self.get_elevation() + 0.37 * self.get_temperature(
        ) + 0.53 * self.get_temperature_range() - 10.9

    def get_evaporation(self):
        amount = (self.get_temperature() + 15.0 * self.get_dew_point()) / (
            80.0 - self.get_temperature())
        amount *= random.random()

        if self.terrain.is_water():
            return amount

        if amount > self.terrain.moisture:
            amount = self.terrain.moisture
            self.terrain.moisture = 0

            return amount
        else:
            self.terrain.moisture -= amount

            return amount

    def food_production_multiplier(self):
        # Higher temperature means better production.
        multiplier = self.get_temperature(
        ) / 98.0 * self.terrain.get_food_production_multiplier()
        for neighbor in self.neighbors():
            # So does being surrounding by water
            if neighbor.terrain.is_water():
                multiplier *= neighbor.terrain.get_food_production_multiplier()

        return multiplier

    def reset_color(self):
        if self.id >= 0:
            if self.owner is not None:
                self.parent.canvas.itemconfig(self.id,
                                              fill=self.owner.nation.color)
            else:
                self.parent.canvas.itemconfig(self.id, fill=self.terrain.color)

    def make_id(self):
        start_x, start_y = self.x * utility.CELL_SIZE, self.y * utility.CELL_SIZE
        end_x, end_y = start_x + utility.CELL_SIZE, start_y + utility.CELL_SIZE
        try:
            if self.owner is not None:
                self.id = self.parent.canvas.create_rectangle(
                    start_x,
                    start_y,
                    end_x,
                    end_y,
                    width=0,
                    fill=self.owner.nation.color)
            else:
                self.id = self.parent.canvas.create_rectangle(
                    start_x,
                    start_y,
                    end_x,
                    end_y,
                    width=0,
                    fill=self.terrain.color)
        except:
            pass

    def show_information_gui(self):
        self.gui_window = Tk()
        self.gui_window.title('Cell Information: ({}, {})'.format(
            self.x, self.y))
        self.gui_window.geometry("400x300+0+0")
        self.gui_window.config(background='white')

        self.type_label = gui.Label(self.gui_window,
                                    text='Type: {}'.format(self.type))
        self.type_label.grid(row=0, sticky=W)

        self.owning_city_label = gui.Label(self.gui_window,
                                           text='Owning city: ')
        self.owning_city_label.grid(row=1, sticky=W)

        self.owning_nation_label = gui.Label(self.gui_window,
                                             text='Owning nation: ')
        self.owning_nation_label.grid(row=2, sticky=W)

        if self.owner is not None:
            self.owning_city_button = gui.Button(
                self.gui_window,
                text=self.owner.name,
                command=self.owner.show_information_gui)
            self.owning_nation_button = gui.Button(
                self.gui_window,
                text=self.owner.nation.name,
                command=self.owner.nation.show_information_gui)
        else:
            self.owning_city_button = gui.Button(self.gui_window, text='None')
            self.owning_nation_button = gui.Button(self.gui_window,
                                                   text='None')

        self.owning_city_button.grid(row=1, column=1, sticky=W)
        self.owning_nation_button.grid(row=2, column=1, sticky=W)

        self.building_capacity_label = gui.Label(
            self.gui_window,
            text='{} of {} filled.'.format(self.get_total_buiding_size(),
                                           self.building_capacity))
        self.building_capacity_label.grid(row=3)

        self.buildings_display = Listbox(self.gui_window)

        for building in self.buildings:
            self.buildings_display.insert(
                END, '{}: {}'.format(building.name, building.number))

        self.buildings_display.grid(row=4,
                                    column=0,
                                    columnspan=3,
                                    sticky=W + E)

    def update_self(self):
        if self.owner is None:
            self.parent.canvas.itemconfig(self.id, fill=self.terrain.color)
        else:
            self.parent.canvas.itemconfig(self.id,
                                          fill=self.owner.nation.color)

    def change_type(self, new_type):
        self.type = new_type

        self.update_self()

    def change_owner(self, new_owner, new_type=None):
        if self.owner is not None:  # Remove this cell from the list of owned cells
            self.owner.remove_cell(self)

        # This must be before .add_cell
        if new_type is not None:
            self.change_type(new_type)

        self.owner = new_owner

        if self.owner is not None:
            for curBuilding in self.buildings:
                curBuilding.city = new_owner
            self.owner.add_cell(self)
        else:
            self.new_type = ''  # There is no cell type for an unowned cell.
            self.buildings = building.base_buildings(None)

        self.update_self()

    def neighbors(self):
        result = []

        if self.x > 0:
            result.append(self.parent.cells[self.x - 1][self.y])
        # else:
        #     result.append(self.parent.cells[utility.S_WIDTH // utility.CELL_SIZE - 1][self.y])

        if self.y > 0:
            result.append(self.parent.cells[self.x][self.y - 1])
        # else:
        #     result.append(self.parent.cells[self.x][utility.S_HEIGHT // utility.CELL_SIZE - 1])

        if self.x < utility.S_WIDTH // utility.CELL_SIZE - 1:
            result.append(self.parent.cells[self.x + 1][self.y])
        # else:
        #     result.append(self.parent.cells[0][self.y])

        if self.y < utility.S_HEIGHT // utility.CELL_SIZE - 1:
            result.append(self.parent.cells[self.x][self.y + 1])
        # else:
        #     result.append(self.parent.cells[self.x][0])

        return result
Beispiel #49
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)
        self.target_keep_profile_var = IntVar()
        self.mutex = Lock()

    def prepare(self):
        self.deviceList.config(state='normal')
        self.versionList.config(state='disabled')
        self.engList.config(state='disabled')
        self.packageList.config(state='disabled')
        self.ok.config(state='disabled')
        self.setData(self.controller.data)
        self.setDeviceList(self.data.keys())
        self.controller.setDefault(self, self.controller.loadOptions())
        self.deviceList.focus_force()

    def printErr(self, message):
        self.errLog.config(text=message)

    def setData(self, data):
        self.data = data

    def setupView(self, title="Select your flash", data=None):
        if (data):
            self.setData(data)
        self.errLog = Label(self, text="")
        self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE")
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self, text='Next', command=lambda: self.confirm())
        self.ok.grid(row=4, column=3, sticky="E")
        self.ok.config(state="disabled")
        # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase
        self.keepProfileCheckbutton = Checkbutton(
            self,
            text="Keep User Profile (BETA)",
            variable=self.target_keep_profile_var)
        self.keepProfileCheckbutton.grid(row=5,
                                         column=0,
                                         columnspan=4,
                                         sticky="W")
        self.deviceLabel = Label(self, text="Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        self.deviceList.grid(row=2, column=0)
        self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect)
        self.deviceList.config(state="disabled")
        self.versionLabel = Label(self, text="Branch", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        self.versionList.grid(row=2, column=1)
        self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect)
        self.versionList.config(state="disabled")
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=2)
        self.engList = Listbox(self, exportselection=0)
        self.engList.grid(row=2, column=2)
        self.engList.bind('<<ListboxSelect>>', self.engOnSelect)
        self.engList.config(state="disabled")
        self.packageLabel = Label(self,
                                  text="Gecko/Gaia/Full",
                                  font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=3)
        self.packageList = Listbox(self, exportselection=0)
        self.packageList.grid(row=2, column=3)
        self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect)
        self.packageList.config(state="disabled")
        self.bidVar = StringVar()
        Label(self, text="Build ID").grid(row=3, column=0, sticky='E')
        self.bidInput = Entry(self, textvariable=self.bidVar, width="30")
        self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W")
        self.bidVar.set('latest')
        # binding unfocus for build id field
        self.bidInput.bind('<FocusOut>', self.updateBuildId)
        # binding the Return Key to each componments
        self.deviceList.bind('<Return>', self.pressReturnKey)
        self.versionList.bind('<Return>', self.pressReturnKey)
        self.engList.bind('<Return>', self.pressReturnKey)
        self.packageList.bind('<Return>', self.pressReturnKey)
        self.bidInput.bind('<Return>', self.pressReturnKey)
        self.ok.bind('<Return>', self.pressReturnKey)

    def selection_all_checked(self):
        result = False
        if len(self.deviceList.curselection()) == 0:
            self.logger.log('Please select device.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.deviceList.focus_set()
        elif len(self.versionList.curselection()) == 0:
            self.logger.log('Please select branch.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.versionList.focus_set()
        elif len(self.engList.curselection()) == 0:
            self.logger.log('Please select user or engineer build.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.engList.focus_set()
        elif len(self.packageList.curselection()) == 0:
            self.logger.log('Please select package to flash.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.packageList.focus_set()
        elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest':
            self.logger.log(
                'Please enter build ID to flash or use "latest" to get the newest',
                status_callback=self.printErr)
            self.logger.log(self.bidVar.get() + ' is invalid: ' +
                            str(len(self.bidVar.get())))
            self.bidVar.set('latest')
        else:
            result = True
        return result

    def updateBuildId(self, event=None):
        # if the value is '' or 'latest', the set the build_id option as ''.
        buildId = self.bidVar.get()
        if buildId == 'latest':
            buildId = ''
        elif len(buildId) != 14:
            self.printErr("Invalid build ID: " + buildId + ", reset to latest")
            buildId = ''
            self.bidVar.set('latest')
        else:
            if len(self.engList.curselection()) != 0:
                self.refreshPackageList()

    def pressReturnKey(self, event=None):
        if self.selection_all_checked():
            self.ok.config(state="disabled")
            self.confirm()

    def deviceOnSelect(self, evt):
        self.setVersionList()

    def versionOnSelect(self, evt):
        self.setEngList()

    def engOnSelect(self, evt):
        self.refreshPackageList()  # hard coded right now

    def packageOnSelect(self, evt):
        self.ok.config(state="normal")

    def confirm(self):
        self.mutex.acquire()
        try:
            if self.selection_all_checked():
                self.ok.config(state="disabled")
                params = []
                package = self.packageList.get(
                    self.packageList.curselection()[0])
                self.logger.log('Start to flash [' + package + '].',
                                status_callback=self.printErr)
                if (PathParser._IMAGES in package):
                    params.append(PathParser._IMAGES)
                else:
                    if (PathParser._GAIA in package):
                        params.append(PathParser._GAIA)
                    if (PathParser._GECKO in package):
                        params.append(PathParser._GECKO)
                keep_profile = (self.target_keep_profile_var.get() == 1)
                archives = self.controller.do_download(params)
                self.controller.do_flash(params,
                                         archives,
                                         keep_profile=keep_profile)
                self.packageList.select_clear(0, END)
                self.controller.transition(self)
        finally:
            self.mutex.release()

    def setDeviceList(self, device=[]):
        self.deviceList.delete(0, END)
        for li in device:
            self.deviceList.insert(END, li)

    def setVersionList(self, version=[]):
        if len(version) == 0:
            version = self.data[self.deviceList.get(
                self.deviceList.curselection())]
        self.versionList.config(state="normal")
        self.engList.config(state="disabled")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.versionList.delete(0, END)
        for li in version:
            self.versionList.insert(END, li)

    def setEngList(self, eng=[]):
        if len(eng) == 0:
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.data[device][version]
        self.engList.config(state="normal")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.engList.delete(0, END)
        for li in eng:
            self.engList.insert(END, li)

    def refreshPackageList(self):
        self.mutex.acquire()
        try:
            self.packageList.config(state="normal")
            self.ok.config(state="normal")
            self.packageList.delete(0, END)
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.engList.get(self.engList.curselection())
            buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get()
                             == 'latest') else self.bidVar.get()
            package = self.controller.getPackages(
                self.data[device][version][eng]['src'], build_id=buildId)
            if len(package) == 0:
                self.logger.log('Invalid build ID: ' + buildId +
                                ', reset to latest',
                                status_callback=self.printErr)
                buildId = ''
                self.bidVar.set('latest')
                package = self.controller.getPackages(
                    self.data[device][version][eng]['src'], build_id=buildId)
            for li in package:
                self.packageList.insert(END, li)
        finally:
            self.mutex.release()
Beispiel #50
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self,
                 master,
                 list_of_items=None,
                 autocomplete_function=None,
                 listbox_width=None,
                 listbox_height=7,
                 ignorecase_match=False,
                 startswith_match=True,
                 vscrollbar=True,
                 hscrollbar=True,
                 **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError(
                    "Combobox_Autocomplete subclass has 'autocomplete_function' implemented"
                )
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError(
                        "If not guiven complete function, list_of_items can't be 'None'"
                    )

                if ignorecase_match:
                    if startswith_match:

                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:

                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [
                        item for item in self.list_of_items
                        if matches_function(entry_data, item)
                    ]
                else:
                    if startswith_match:

                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item,
                                        re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:

                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item,
                                         re.IGNORECASE):
                                return True
                            else:
                                return False

                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [
                            item for item in self.list_of_items
                            if matches_function(escaped_entry_data, item)
                        ]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items

        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())

    def _on_tab(self, event):
        self.post_listbox()
        return "break"

    def _on_change_entry_var(self, name, index, mode):

        entry_data = self._entry_var.get()

        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)

            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame,
                                background="white",
                                selectmode=SINGLE,
                                activestyle="none",
                                exportselection=False)
        self._listbox.grid(row=0, column=0, sticky=N + E + W + S)

        self._listbox.bind("<ButtonRelease-1>",
                           self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())

        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame,
                             orient=VERTICAL,
                             command=self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N + S)

            self._listbox.configure(
                yscrollcommand=lambda f, l: autoscroll(vbar, f, l))

        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame,
                             orient=HORIZONTAL,
                             command=self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E + W)

            self._listbox.configure(
                xscrollcommand=lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness")
        y = self.winfo_height() - self.cget("borderwidth") - self.cget(
            "highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width = self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)

        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)

    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)

        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index += 1

                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"
Beispiel #51
0
class TkApp:
    def __init__(self, ncffile, options):
        master = self.root = Tk()
        self.ncffile = ncffile
        self.options = options
        self.plotted_variables = set()
        frame = Frame(master)
        frame.grid(row = 0)
        codeframe = Frame(master)
        codeframe.grid(row = 1)
        metaframe = Frame(master)
        metaframe.grid(row = 2)
        goframe = Frame(frame)
        goframe.grid(column = 3, row = 1)

        var_label = Label(frame, text = 'Select Variable')
        var_label.grid(column = 0, row = 0)
        var_scrollbar = Scrollbar(frame, orient = VERTICAL)
        var_scrollbar.grid(column = 1, row = 1, sticky = N + S)
        self.var = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = var_scrollbar.set)
        self.var.grid(column = 0, row = 1)
        var_scrollbar.config(command = self.var.yview)

        what_to_do = Label(frame, text = 'Execute')
        what_to_do.grid(column = 2, row = 0)
        self.method_list = Listbox(frame, selectmode = SINGLE, exportselection = 0)
        self.method_list.grid(column = 2, row = 1)
        self.pre_txt = StringVar()
        pre_label = Label(codeframe, text = 'Before any figures, execute code')
        self.pre_txt.set(_pre_code)
        pre_label.grid(row = 2, sticky = 'W')
        self.pre = Entry(codeframe, width = 120, textvariable = self.pre_txt)
        self.pre.grid(row =3, sticky = 'E')

        self.before_txt = StringVar()
        self.before_txt.set(_before_code)
        before_label = Label(codeframe, text = 'Before each figure, execute code')
        before_label.grid(row = 4, sticky = 'W')
        self.before = Entry(codeframe, width = 120, textvariable = self.before_txt)
        self.before.grid(row =5, sticky = 'E')

        self.after_txt = StringVar()
        self.after_txt.set(_after_code)
        after_label = Label(codeframe, text = 'After each figure, execute code')
        after_label.grid(row = 6, sticky = 'W')
        self.after = Entry(codeframe, width = 120, textvariable = self.after_txt)
        self.after.grid(row =7, sticky = 'E')

        self.post_txt = StringVar()
        self.post_txt.set(_post_code) 
        post_label = Label(codeframe, text = 'After all figures, execute code')
        post_label.grid(row = 8, sticky = 'W')
        self.post = Entry(codeframe, width = 120, textvariable = self.post_txt)
        self.post.grid(row = 9, sticky = 'E')

        options_label = Label(goframe, text = 'Options:')
        options_label.grid(column = 0, row = 1, sticky = 'W')
        self.logscale = IntVar()
        self.logscale.set(0)
        c = Checkbutton(goframe, text = "log-scale?", variable = self.logscale)
        c.grid(column = 0, row = 2, sticky = 'W')

        self.coastlines = IntVar()
        self.coastlines.set(_coastlines_opt)
        coastlines = Checkbutton(goframe, text = "coastlines?", variable = self.coastlines, justify = LEFT)
        coastlines.grid(column = 0, row = 3, sticky = 'W')

        self.countries = IntVar()
        self.countries.set(_countries_opt)
        countries = Checkbutton(goframe, text = "countries?", variable = self.countries, justify = LEFT)
        countries.grid(column = 0, row = 4, sticky = 'W')

        self.states = IntVar()
        self.states.set(_states_opt)
        states = Checkbutton(goframe, text = "states?", variable = self.states, justify = LEFT)
        states.grid(column = 0, row = 5, sticky = 'W')

        self.counties = IntVar()
        self.counties.set(_counties_opt)
        counties = Checkbutton(goframe, text = "counties?", variable = self.counties, justify = LEFT)
        counties.grid(column = 0, row = 6, sticky = 'W')

        self.execute_button = Button(goframe, text = "Make Figure", command = self.execute)
        self.execute_button.grid(row = 0, column = 0, sticky = 'W')
                
        self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot']
        method_labels= ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)']
        for method in method_labels:
            self.method_list.insert(END, method)
            
        var_keys = [k for k, v in self.ncffile.variables.items() if k not in ('time', 'latitude', 'longitude', 'latitude_bounds', 'longitude_bounds', 'time_bounds', 'tau0', 'tau1', 'TFLAG')]
        var_keys.sort()
        self.vars = []
        for spc in var_keys:
            self.var.insert(END, spc)
            self.vars.append(spc)

        meta_label = Label(metaframe, text = 'Common Data Language Header:')
        meta_label.grid(column = 0, row = 0, sticky = 'W')
        meta_scrollbar = Scrollbar(metaframe, orient = VERTICAL)
        meta_scrollbar.grid(column = 1, row = 1, sticky = N + S)
        self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand = meta_scrollbar.set)
        self.meta.grid(column = 0, row = 1, sticky = 'W')
        from PseudoNetCDF.pncdump import pncdump
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        pdump = StringIO("")
        try:
            name = ', '.join(options.ifile)
        except:
            name = 'ifile'
        pncdump(self.ncffile, header = True, outfile = pdump, )
        pdump.seek(0, 0)
        self.meta.insert(END, pdump.read())
        self.meta.config(state=DISABLED)
        help = Button(goframe, text = 'Help', command = self.help)
        help.grid(column = 0, row = 7)
        quit = Button(goframe, text = 'Quit', command = self.quit)
        quit.grid(column = 0, row = 8)
        master.mainloop()
   
    def help(self):
        print("pl is pylab: details at matplotlib;")
        
    def quit(self):
        self.root.destroy()

    def _get_var(self, list):
        items = list.curselection()
        try: items = map(int, items)
        except: pass
        items = [self.vars[i] for i in items]
        return items
        
    def get_var(self):
        return self._get_var(self.var)
        
    def get_methods(self):
        items = self.method_list.curselection()
        try: items = map(int, items)
        except: pass
        items = [self.methods[i] for i in items]
        return items
    def execute(self):
        os.system('clear')
        vars = self.get_var()
        self.plotted_variables = self.plotted_variables.union(vars)
        methods, = self.get_methods()
        self.options.logscale = bool(self.logscale.get())
        self.options.coastlines = bool(self.coastlines.get())
        self.options.countries = bool(self.countries.get())
        self.options.states = bool(self.states.get())
        self.options.counties = bool(self.counties.get())
        self.options.pre_txt = self.pre_txt.get()
        self.options.before_txt = self.before_txt.get()
        self.options.after_txt = self.after_txt.get()
        self.options.post_txt = self.post_txt.get()
        plotwithopts(self.ncffile, methods, vars, self.options)
Beispiel #52
0
class JobList(Frame):
    # NOTE: job_params contains information about a Job in the Joblist
    # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created

    def __init__(self, parent=None, **kwargs):
        Frame.__init__(self, parent)
        self.parent = parent
        self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL)
        self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll)
        self.job_list_xscroll['command'] = self.job_list.xview
        self.job_list_yscroll['command'] = self.job_list.yview
        self.new_job_frame = Frame(self)
        add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None
        if add_icon_filename == None:
            self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add)
        else:
            add_icon = PhotoImage(file=add_icon_filename)
            self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add)
        self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove)
        self.progress_frame = Frame(self)
        self.progress_value = Tkinter.IntVar()
        self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value)
        self.button_frame = Frame(self)
        self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs)
        self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows)

        self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None

        self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None

        self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None

        self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs)
        self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs)
        self.bind('<<CreatePlotGUI>>', self.create_plot_gui)
        self.parent.bind('<ButtonPress>', self.on_press)
        self.parent.bind('<Configure>', self.on_resize)

        self.reinit_variables()

        self.top_level_windows = list()

        # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized,
        # the resize option will be disabled for this window
        self.parent.resizable(width=False, height=False)

        self.lift()

    def reinit_variables(self):
        self.job_params = dict()

        self.last_job_id = -1

        self.job_outcomes = list()

        self.plot_args = list()

        self.on_button = False

    def add_job_params(self, input_args):
        self.job_params = input_args
        # Add each element to the job list
        for job in self.job_params:
            self.add_job(job)

    def add_job(self, job):
        try:
            index_end = job['input_directory'].rindex('/')
            index_start = job['input_directory'].rindex('/', 0, index_end)
            input_directory_text = job['input_directory']
            list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\''
            if job['start'] != None:
                list_text += ' ' + str(job['start'])
                if job['end'] != None:
                    list_text += ' to'
            if job['end'] != None:
                list_text += ' ' + str(job['end'])

            if job['job_id'] > self.last_job_id:
                self.last_job_id = job['job_id']

            self.job_list.insert(Tkinter.END, list_text)

            # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose)
            job['list_text'] = list_text

            # The line number is used wrt the GUI to indicate which job in the job list is being currently executed.
            job['line_number'] = self.job_list.size() - 1
            #print str(job['line_number'])

            self.job_params[job['job_id']] = job
        except KeyError as ke:
            # Should show some error message indicating that there is a problem.
            pass

        #print str(self.job_params)
        #print 'Added Job ' + str(job['job_id'])

    def ask_to_clear_jobs(self, event):
        for job in self.job_params.itervalues():
            line_number = job['line_number']
            self.job_list.itemconfig(line_number, foreground='black')

        # Update parent to refresh widget appearance
        self.parent.update()

        # Reactivate process button
        self.process_button.config(state = Tkinter.NORMAL)

        # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared.

        clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed.  Would you like to clear the job list?', master=self)
        if clearList:
            self.clear_list()

    def ask_to_plot_graphs(self, event):
        # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot'
        plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self)

        if not plotGraphs:
            return

        # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs
        if self.create_plots != None:
            output_files_list = list()
            for job_outcome in self.job_outcomes:
                for output_outcomes in job_outcome[2]:
                    (station, output_directory, output_files) = output_outcomes
                    for output_files_tuple in output_files:
                        for output_file_tuple in output_files_tuple:
                            (output_file, output_file_success) = output_file_tuple
                            if output_file_success:
                                # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list
                                if len(job_outcome) == 4:
                                    output_files_list.append([output_file, job_outcome[3]])
                                else:
                                    output_files_list.append([output_file])

            plots_thread = PlotsThread(self.create_plots, output_files_list, self)
            plots_thread.start()

    def add_plot(self, args=dict()):
        self.plot_args.append(args)

    def finished_adding_plots(self):
        self.event_generate('<<CreatePlotGUI>>', when='tail')

    def create_plot_gui(self, event):
        # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another
        graph_names = list()
        for args in self.plot_args:
            graph_name = args['output_file']
            graph_names.append(graph_name)
        dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui)

    # This is the entry point for the
    def finish_creating_plot_gui(self, plot_labels):
        graph_count = 1
        for plot_label in plot_labels:
            for args in self.plot_args:
                #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label
                #print 'The plot label is: ' + plot_label
                #print 'The output file is: ' + args['output_file']
                if plot_label == args['output_file']:
                    #print 'Creating graph ' + str(graph_count)
                    graph_count += 1
                    graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename)
                    graph_window.set_grid()
                    self.top_level_windows.append(graph_window)
        #print 'Creating plot GUI

        # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read
        # them and create the appropriate plot graph windows
        self.reinit_variables()

    # Clear all the elements in the list
    def clear_list(self):

        # Save plot args because they are need later in this run
        plot_args = self.plot_args
        self.reinit_variables()
        # Restore the plot args
        self.plot_args = plot_args

        self.job_list.delete(0, self.job_list.size())
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_add(self):
        single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self)
        single_job.set_grid()

    def on_remove(self):
        selection = self.job_list.curselection()
        for line_number in selection:
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            job = self.job_params.pop(job_id)
            self.job_list.delete(line_number)
            print 'Removed Job ' + str(job['job_id'])
        # Fix line number
        for line_number in range(self.job_list.size()):
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number)
            self.job_params[job_id]['line_number'] = line_number

    def set_grid(self):
        self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4)
        self.columnconfigure(0, minsize=600)
        self.rowconfigure(0, minsize=300)
        self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W)
        self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W)
        self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N)
        self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W)
        self.remove_job_button.grid(row=0, column=0)
        self.add_job_button.grid(row=0, column=1)
        self.progress_frame.grid(row=3, column=0, pady=3)
        self.progress_frame.columnconfigure(0, minsize=600)
        self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.columnconfigure(0, minsize=300)
        self.button_frame.columnconfigure(1, minsize=300)
        self.process_button.pack(side=Tkinter.RIGHT)
        self.quit_button.pack(side=Tkinter.RIGHT)

    def start_jobs(self):
        # If there are no queued jobs then simply return
        if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0:
            return
        # Deactivate the process button
        self.process_button.config(state = Tkinter.DISABLED)
        # Initialize the progress bar
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()
        # Start process thread
        jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume)
        jobs_thread.start()
        self['cursor'] = 'wait'

    def on_update(self, status, line_number, step):
        if status == 'init':
            self.job_list.itemconfig(line_number, foreground='green')
            self.job_list.activate(line_number)
        elif status == 'success':
            self.job_list.itemconfig(line_number, foreground='blue')
        elif status == 'fail':
            self.job_list.itemconfig(line_number, foreground='red')
        self.progress_value.set(step)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_resume(self, job_outcomes=list()):
        self.progress_value.set(100)
        self.job_outcomes = job_outcomes
        self.event_generate('<<AskToClearJobs>>', when='tail')
        self.event_generate('<<AskToPlotGraphs>>', when='tail')
        self['cursor'] = 'arrow'

    def close_top_level_windows(self):
        #print 'Closing other top level windows'
        for top_level_window in self.top_level_windows:
            if top_level_window:
                top_level_window.withdraw()
                top_level_window.destroy()

    def notify_of_close(self, top_level_window):
        if top_level_window in self.top_level_windows:
            #print 'Removing top level window'
            self.top_level_windows.remove(top_level_window)

    def on_press(self, event):
        self.on_button = True
        self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num)
        self.parent.bind(self.release_pattern, self.on_release)

    def on_release(self, event):
        self.on_button = False

    def on_resize(self, event):
        self.parent.lift()

        if self.on_button:

            self.set_grid()

    def on_close(self):
        self.plot_args = list()
        self.withdraw()
        self.destroy()
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.padx = 3
        self.pady = 3
        self.grid()
        self.results = []
        self.playlists = []
        self.vids = []
        self.__createWidgets()

    def __createWidgets(self):
        self.__searchFields()
        self.__resultArea()
        self.__buttons()
        self.__markdownArea()
        self.bind('<Return>', self.search_button)

    def __buttons(self):
        self.resultSelect = Button(text='OK', state=DISABLED)
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)
        self.status = Label(text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.grid(row=9, column=0, columnspan=10, sticky=N + E + S + W)
        self.__vidButtons()
        self.__rmVidButtons()
        self.resultSelect.grid_forget()

    def __searchFields(self):
        Label(text="User", anchor=E).grid(row=0, column=0,
                                          padx=self.padx, pady=self.pady,
                                          sticky=W)
        self.user_entry = Entry()
        self.user_entry.grid(row=0, column=1, padx=self.padx, pady=self.pady,
                             sticky=W)
        Label(text="Search terms").grid(row=0, column=3,
                                        padx=self.padx, pady=self.pady,
                                        sticky=W)
        self.search_terms = Entry()
        self.search_terms.grid(row=0, column=4,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        Label(text="playlist id").grid(row=1, column=3,
                                       padx=self.padx, pady=self.pady,
                                       sticky=W)
        self.playlist_id = Entry()
        self.playlist_id.grid(row=1, column=4, padx=self.padx, pady=self.pady,
                              sticky=W)
        self.search_button = Button(text="Search", command=self.__search)
        self.search_button.grid(row=2, column=4,
                                padx=self.padx, pady=self.pady, sticky=E)

    def __resultArea(self):
        self.result_label = Label(text="Results")
        self.result_label.grid(row=2, column=0,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        self.resultshowbut = Button(text="View", command=self.__showResults)
        self.resultshowbut.grid(row=2, column=1, sticky=W)
        self.yScroll = Scrollbar(orient=VERTICAL)
        self.xScroll = Scrollbar(orient=HORIZONTAL)
        self.listbox = Listbox(xscrollcommand=self.xScroll.set,
                                yscrollcommand=self.yScroll.set,
                                selectmode=SINGLE)
        self.xScroll.config(command=self.listbox.xview)
        self.yScroll.config(command=self.listbox.yview)

    def __showResults(self):
        self.resultshowbut.config(text="Hide", command=self.__hideResults)
        self.yScroll.grid(row=3, column=5, sticky=N + S)
        self.xScroll.grid(row=4, column=0, sticky=E + W, columnspan=5)
        self.listbox.grid(row=3, column=0, sticky=N + S + E + W, columnspan=5)
        self.markdownarea.config(height=10)

    def __hideResults(self):
        self.resultshowbut.config(text="View", command=self.__showResults)
        self.yScroll.grid_forget()
        self.xScroll.grid_forget()
        self.listbox.grid_forget()
        self.markdownarea.config(height=30)

    def __markdownArea(self):
        self.markdownlabel = Label(text="Markdown")
        self.mdyScroll = Scrollbar(orient=VERTICAL)
        self.mdxScroll = Scrollbar(orient=HORIZONTAL)
        self.markdownarea = Text(wrap=WORD, height=10,
                                 yscrollcommand=self.mdyScroll.set,
                                 xscrollcommand=self.mdxScroll.set)
        self.copymarkdown = Button(text="Copy To Clipboard",
                                  command=self.__copyMarkdown)
        self.mdxScroll.config(command=self.markdownarea.xview)
        self.mdyScroll.config(command=self.markdownarea.yview)

    def __vidButtons(self):
        self.modtitle = Button(text='Modify titles', command=self.__modTitles)
        #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2,
        #                   padx=self.padx, pady=self.pady)
        self.getcaps = Button(text="Get captions", command=self.__getCaptions)
        self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmVidButtons(self):
        self.modtitle.grid_remove()
        self.getcaps.grid_remove()
        self.bind('<Return>', self.search_button)

    def __search(self):
        user = self.user_entry.get()
        playlist = self.playlist_id.get()
        searchterms = self.search_terms.get()
        self.__showResults()
        self.resultSelect.config(state=DISABLED)
        self.__rmVidButtons()
        self.__rmMarkdown()
        if not self.__validparams(user, searchterms, playlist):
            return False

        if len(playlist) > 0:
            self.__searchPlaylist(playlist)
            return

        self.__searchUser(user, searchterms)

    def __showMarkdown(self):
        self.markdownlabel.grid(row=5, column=0,
                                    padx=self.padx, pady=self.pady,
                                    sticky=W)
        self.markdownarea.grid(row=6, column=0, columnspan=5,
                               padx=self.padx, pady=self.pady,
                               sticky=N + S + E + W)
        self.mdyScroll.grid(row=6, column=5, sticky=N + S)
        self.mdxScroll.grid(row=7, column=0, sticky=E + W, columnspan=5)
        self.copymarkdown.grid(row=8, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmMarkdown(self):
        self.markdownarea.grid_forget()
        self.markdownlabel.grid_forget()
        self.copymarkdown.grid_forget()
        self.mdyScroll.grid_forget()
        self.mdxScroll.grid_forget()

    def __searchPlaylist(self, playlistid):
        self.__getvids(playlistid)

    def __searchUser(self, user, searchterms):
        self.listbox.delete(0, END)
        self.__status("Searching for%splaylists by user \"%s\"" % (
                      " \"%s\" " % searchterms if len(searchterms) else " ",
                      user))
        self.playlists = []
        try:
            self.playlists = lib.yt.search.PlaylistSearch(user=user,
                                                 search=searchterms).query()
        except HTTPError:
            self.__status("User %s does not exist at youtube" % user)
            return
        if self.playlists is None or len(self.playlists) == 0:
            self.__status("Search returned no results")
            return
        self.__populateResults([v['title'] for v in self.playlists])
        self.resultSelect.config(command=self.__getVidsFromSelected,
                                 state=NORMAL)
        self.__status("")
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)

    def __populateResults(self, values):
        self.listbox.delete(0, END)
        for i, val in enumerate(values):
            self.listbox.insert(i, val)
        self.listbox.activate(0)
        self.listbox.selection_set(0)

    def __getVidsFromSelected(self):
        selected = int(self.listbox.curselection()[0])
        self.__getvids(self.playlists[selected]['id'])

    def __getvids(self, playlistid):
        self.playlist_id.delete(0, END)
        self.playlist_id.insert(0, playlistid)
        self.resultSelect.grid_forget()
        title = playlistid
        if len(self.playlists) > 0:
            for playlist in self.playlists:
                if playlist['id'] == playlistid:
                    title = playlist['title']
                    break

        self.__status("Getting videos for %s" % title)
        self.listbox.delete(0, END)
        try:
            self.vids = lib.yt.search.PlaylistVideoSearch(
                                                    id=playlistid).query()
            self.__populateResults([v['title'] for v in self.vids])
            self.__status("%d Videos found" % len(self.vids))
            self.__vidButtons()
            self.bind('<Return>', self.getcaps)
        except HTTPError:
            self.__status("No videos found! is %s a valid playlist?" %
                          playlistid)

    def __status(self, msg):
        if len(msg) > 75:
            msg = msg[:70] + '...'
        self.status.config(text=msg)
        self.status.update_idletasks()

    def __trackSelect(self, vid, tracks, preftrack=None):
        pref = self.__prefAvailable(preftrack, tracks)
        if pref is None:
            sel = lib.trackSelect.TrackSelect(self, vid=vid,
                                              tracks=tracks)
            if sel.result is None:
                self.__status("skipped")
                tracks = None
            else:
                tracks = [sel.result[0]]
                if sel.preflang is not None:
                    preftrack['lang'] = sel.preflang
                if sel.prefname is not None:
                    preftrack['name'] = sel.prefname
        else:
            tracks = pref
        return tracks, preftrack

    def __getCaptions(self):
        preftrack = {'name': None, 'lang': None}
        self.listbox.delete(0, END)
        self.markdownarea.delete(1.0, END)
        self.__showMarkdown()
        for i, vid in enumerate(self.vids):
            nocapmsg = '[%02d] --NO CAPTIONS-- %s' % (i + 1, vid['title'])
            tracks = lib.yt.search.CaptionSearch(id=vid['id']).query()
            self.vids[i]['text'] = ''
            if len(tracks) == 0:
                self.__status('No captions available for %s' %
                              self.vids[i]['title'])
                self.listbox.insert(END, nocapmsg)

            elif len(tracks) > 1:
                sel = self.__trackSelect(vid, tracks, preftrack)
                if sel[0] is None:
                    msg = '[%02d] --SKIPPED-- %s' % (i + 1, vid['title'])
                    self.listbox.insert(END, msg)
                    self.listbox.see(END)
                    continue
                tracks = sel[0]

            if len(tracks) == 1:
                self.__trackCaps(i, tracks, nocapmsg)
        self.__status('')
        self.__hideResults()

    def __trackCaps(self, vidIndex, tracks, nocapmsg):
        i = vidIndex
        vid = self.vids[i]
        msg = '%02d of %02d Getting captions for %s' % (
                        i + 1, len(self.vids), self.vids[i]['title'])
        self.__status(msg)
        self.listbox.insert(END, msg)
        self.vids[i]['text'] = lib.markdown.heading(vid['title'])
        captions = lib.yt.search.GetCaptions(id=vid['id'],
                                lang=tracks[0]['lang'],
                                name=tracks[0]['name'])
        captions.query()
        captiontext = captions.textOnly()
        sleep(0.2)
        msg = nocapmsg
        if captiontext is not None and len(captiontext) > 0:
            self.vids[i]['text'] += (lib.markdown.to_utf8(captiontext)
                                     + '\n\n')
            msg = '[%02d] --DONE-- %s' % (i + 1, vid['title'])
        self.listbox.delete(END, END)
        self.listbox.insert(END, msg)
        self.listbox.see(END)
        self.markdownarea.insert(END, self.vids[i]['text'])
        self.markdownarea.see(END)

    def __prefAvailable(self, preftrack, tracks):
        if preftrack['lang'] is None:
            return None

        pref = None
        for track in tracks:
            if (track['lang'] == preftrack['lang'] and
                track['name'] == preftrack['name']):
                return [track]
            if track['lang'] == preftrack['lang'] and pref is None:
                pref = [track]

        return pref

    def __modTitles(self):
        pass

    def __validparams(self, user, searchterms, playlist):
        if len(user) == 0 and len(playlist) == 0:
            msg = "Either a valid youtube user or playlist id must be given."
            tkMessageBox.showwarning("missing information", msg)
            return False

        if len(user) > 0 and not self.__validstring(user):
            msg = "The user given contains invalid characters"
            tkMessageBox.showwarning('Bad user', msg)
            return False

        if len(playlist) > 0 and not self.__validstring(playlist):
            msg = "The playlist given contains invalid characters"
            tkMessageBox.showwarning('Bad playlist', msg)
            return False

        if len(searchterms) > 0 and not self.__validstring(searchterms, True):
            msg = "The search terms given contain invalid characters"
            tkMessageBox.showwarning('Bad search', msg)
            return False

        return True

    def __validstring(self, s, spacechar=False):
        validchars = string.letters + string.digits + string.punctuation
        if spacechar:
            validchars += ' '
        for c in s:
            if c not in validchars:
                return False
        return True

    def __copyMarkdown(self):
        self.markdownarea.clipboard_clear()
        self.markdownarea.clipboard_append(self.markdownarea.get(1.0, END))
Beispiel #54
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.
            
        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = range(columns)
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)

        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Beispiel #55
0
class GUI:
    def _run(self):
        self.saveBtn.config(state=DISABLED)
        self.progressTxt.config(state=NORMAL)
        self.progressTxt.delete('1.0', END)
        self.progressTxt.update()
        self.progressTxt.config(state=DISABLED)
        inputId = self.txEntry.get()
        item = map(int, self.dbLbox.curselection())
        db = self.dbids[item[0]]
        self.runBtn.config(state=DISABLED)
        self.inputId, self.inputName, self.hprobes = main(inputId,
                                                          db,
                                                          debug=self.debug,
                                                          txt=self.progressTxt)
        self.runBtn.config(state=NORMAL)
        if self.hprobes is not None:
            self.saveBtn.config(state=NORMAL)

    def _quitGUI(self):
        #rpath = self.progressTxt.get('8.0','end-1c')
        #if rpath.startswith('Your results'):
        #  tkMessageBox.showinfo("Quit", self.progressTxt.get('8.0','end-1c'))
        self.master.destroy()

    def _save(self):
        hps = filter_probes(self.hprobes, self.spec.get(), self.mingc.get(),
                            self.multiexon.get(), self.mintm.get(),
                            self.maxtm.get(), self.mindimer.get(),
                            self.minfold.get(), self.maxduplex.get())
        result_csv = write_probesCSV(self.inputId, self.inputName, hps,
                                     self.progressTxt)
        result_fna = write_probesFNA(self.inputId, self.inputName, hps,
                                     self.progressTxt)
        tkMessageBox.showinfo('Result file',
                              'Details on ' + str(len(hps)) + \
                              ' hybridization probe(s) were exported to ' + \
                              result_csv + "\n\n" + \
                              'Sequences of '+ str(len(hps)) + \
                              ' hybridization probe(s) were exported to ' + \
                              result_fna)

    def __init__(self, master, dbnames, dbids, debug, version):
        self.dbids = dbids
        self.debug = debug

        self.master = master
        master.title('Plish Probe Designer')

        self.logoImg = PhotoImage(file=get_script_path() +
                                  '/img/plishLogo.gif')
        self.logoLbl = Label(master, image=self.logoImg)
        self.logoLbl.grid(row=0, columnspan=3)
        self.logoLbl.img = self.logoImg

        self.dbLbl = Label(master, text='Database')
        self.dbLbl.grid(row=1, sticky=W + N)
        self.dbLbox = Listbox(master, width=63, height=4)
        self.dbLbox.configure(exportselection=False)

        for i in range(len(dbnames)):
            self.dbLbox.insert(i, dbnames[i])
        self.dbLbox.select_set(0)
        self.dbLbox.grid(row=1, column=1, columnspan=2, sticky=N)

        self.txLbl = Label(master, text='Transcript ID')
        self.txLbl.grid(row=2, sticky=W + N)
        self.txEntry = Entry(master, width=39)
        self.txEntry.grid(row=2, column=1, sticky=W + N)

        self.runBtn = Button(master, text='Run', command=self._run, width=15)
        self.runBtn.grid(row=2, column=2)

        self.progressLbl = Label(master, text='Progress')
        self.progressLbl.grid(row=4, sticky=W + N)
        self.progressTxt = Text(bg="#263238",
                                fg="#ffffff",
                                state=DISABLED,
                                width=51,
                                height=16)
        self.progressTxt.grid(row=4, column=1)

        self.saveBtn = Button(master,
                              text='Save',
                              command=self._save,
                              state=DISABLED,
                              width=15)
        self.saveBtn.grid(row=5, column=2, sticky=N)

        self.quitBtn = Button(master,
                              text='Quit',
                              command=self._quitGUI,
                              width=15)
        self.quitBtn.grid(row=6, column=2, sticky=N)

        self.aboutLF = LabelFrame(master, text='About', width=300)
        self.aboutLF.grid(row=5,
                          column=0,
                          rowspan=2,
                          columnspan=2,
                          sticky=N + W)
        self.versionLbl = Label(self.aboutLF, text='PLISH Probe Designer, Version ' + version + '\n' + \
                          '(c) Heller lab, Stanford University School of Medicine\n' + \
                          '     Daniel C. Ellwanger <*****@*****.**>                       ',
                          justify=LEFT)
        self.versionLbl.grid(row=0, column=0, sticky=N)

        # Filter
        self.filterLF = LabelFrame(master, text='Filter')
        self.filterLF.grid(row=4, column=2, rowspan=2, sticky=N + W)

        self.mingc = DoubleVar()
        self.mingc.set(_defaultGC)
        self.mingcLbl = Label(self.filterLF, text='Min. GC')
        self.mingcLbl.grid(row=0, column=0, sticky=N + W)
        self.mingcEntry = Entry(self.filterLF, width=5, text=self.mingc)
        self.mingcEntry.grid(row=0, column=1, sticky=N + W)
        self.mingcLbl2 = Label(self.filterLF, text='%')
        self.mingcLbl2.grid(row=0, column=2, sticky=N + W)

        self.spec = StringVar(master)
        self.spec.set("isoform")
        self.specLbl = Label(self.filterLF, text='Specificity')
        self.specLbl.grid(row=1, column=0, sticky=N + W)
        self.specOm = OptionMenu(self.filterLF, self.spec, "isoform", "gene",
                                 "none")
        self.specOm.grid(row=1, column=1, sticky=N + W, columnspan=2)

        self.mintm = DoubleVar()
        self.mintm.set(_defaultMinTm)
        self.mintmLbl = Label(self.filterLF, text='Min. Tm')
        self.mintmLbl.grid(row=2, column=0, sticky=N + W)
        self.mintmEntry = Entry(self.filterLF, width=5, text=self.mintm)
        self.mintmEntry.grid(row=2, column=1, sticky=N + W)
        self.mintmLbl2 = Label(self.filterLF, text=u'\N{DEGREE SIGN}' + 'C')
        self.mintmLbl2.grid(row=2, column=2, sticky=N + W)

        self.maxtm = DoubleVar()
        self.maxtm.set(_defaultMaxTm)
        self.maxtmLbl = Label(self.filterLF, text='Max. Tm')
        self.maxtmLbl.grid(row=3, column=0, sticky=N + W)
        self.maxtmEntry = Entry(self.filterLF, width=5, text=self.maxtm)
        self.maxtmEntry.grid(row=3, column=1, sticky=N + W)
        self.maxtmLbl2 = Label(self.filterLF, text=u'\N{DEGREE SIGN}' + 'C')
        self.maxtmLbl2.grid(row=3, column=2, sticky=N + W)

        self.minfold = DoubleVar()
        self.minfold.set(_defaultMinFold)
        self.minfoldLbl = Label(self.filterLF, text='Min. Fold')
        self.minfoldLbl.grid(row=4, column=0, sticky=N + W)
        self.minfoldEntry = Entry(self.filterLF, width=5, text=self.minfold)
        self.minfoldEntry.grid(row=4, column=1, sticky=N + W)
        self.minfoldLbl2 = Label(self.filterLF, text='kcal/mol')
        self.minfoldLbl2.grid(row=4, column=2, sticky=N + W)

        self.mindimer = DoubleVar()
        self.mindimer.set(_defaultMinDimer)
        self.mindimerLbl = Label(self.filterLF, text='Min. Dimer')
        self.mindimerLbl.grid(row=5, column=0, sticky=N + W)
        self.mindimerEntry = Entry(self.filterLF, width=5, text=self.mindimer)
        self.mindimerEntry.grid(row=5, column=1, sticky=N + W)
        self.mindimerLbl2 = Label(self.filterLF, text='kcal/mol')
        self.mindimerLbl2.grid(row=5, column=2, sticky=N + W)

        self.maxduplex = DoubleVar()
        self.maxduplex.set(_defaultMaxDuplex)
        self.maxduplexLbl = Label(self.filterLF, text='Max. Duplex')
        self.maxduplexLbl.grid(row=6, column=0, sticky=N + W)
        self.maxduplexEntry = Entry(self.filterLF,
                                    width=5,
                                    text=self.maxduplex)
        self.maxduplexEntry.grid(row=6, column=1, sticky=N + W)
        self.maxduplexLbl2 = Label(self.filterLF, text='kcal/mol')
        self.maxduplexLbl2.grid(row=6, column=2, sticky=N + W)

        self.multiexon = BooleanVar()
        self.multiexon.set(_defaultMultiExon)
        self.multiexonCb = Checkbutton(self.filterLF,
                                       text='Multi-exon',
                                       variable=self.multiexon,
                                       onvalue=True,
                                       offvalue=False)
        self.multiexonCb.grid(row=7, column=0, sticky=N + W)
class photGUI(Frame):
    """The base class for the phot_calc GUI"""
    
    # This is the constructor for the GUI
    def __init__(self,master=None):
        # We begin by calling the base class's constructor first
        Frame.__init__(self,master)
    
        # We now have an empty window!
        
        # This command sets up a grid structure in the window
        self.grid()
        
        # This loop generates rows and columns in the grid
        for i in range(13):
            self.rowconfigure(i,minsize=10)
        for i in range(3):
            self.columnconfigure(i,minsize=30)
        
        # These are methods which appear below the constructor
        self.defineUnits() # this sets up the units I'll be using in the converter
        self.createWidgets() # this places the elements (or widgets) in the grid
        
        # This command "binds" the user's click to a method (varChoice)
        # This method will determine which variable the user wants (Distance, Mass, Time)
        self.inputlist.bind("<Button-1>",self.__varChoice)
    
        # This is a similar command for the selection of unit
        self.unitlist.bind("<Button-1>",self.__unitChoice)
    
        # Finally, this bind reads in whatever value is in the text box when the user hits return
        # and carries out the unit conversion
        
        self.inputfield.bind("<Return>",self.__calcConversion)
    
    # This function creates and defines the units
    
    def defineUnits(self):
        '''Method defines tuples that carry the various units stored by the converter'''
        
        self.speed = 2.997924580000019e10
        self.h = 6.6260755e-27     
        # Wavelengths
        
        self.wavunits = ('nm','um', 'cm','m')
        self.wavvalues = (1.0e-7, 1.0e-4,1.0,1.0e2)
        
        self.frequnits = ('Hz','MHz','GHz','THz')
        self.freqvalues = (1.0, 1.0e6, 1.0e9, 1.0e12)
        
        self.energunits = ('eV','keV','MeV','GeV','erg')
        self.energvalues = (1.0,1.0e3,1.0e6,1.0e9,1.6e-12)
        
        # Keep the unit values in dictionaries, and use the above strings as keys
        
        self.wavdict = {}        
        self.createUnitDict(self.wavdict,self.wavunits,self.wavvalues) # this method is shown below
        
        self.freqdict = {}
        self.createUnitDict(self.freqdict,self.frequnits,self.freqvalues)
        
        self.energdict = {}
        self.createUnitDict(self.energdict, self.energunits, self.energvalues)  
    
        self.myunits = self.wavunits
        self.myvalues = self.wavvalues
        self.mydict = self.wavdict
    
        
    def createUnitDict(self,mydict,mykeys,myvalues):
        '''This method takes a set of units and values, and creates a dictionary to store them in'''
        for i in range(len(myvalues)):
            mydict[mykeys[i]] = myvalues[i]
               
    def createWidgets(self):
        '''This method creates all widgets and adds them to the GUI'''
        
        # Create Widgets in order of appearance
        # This is not necessary, but makes code easier to read
        
        # Start with text telling user what to do
        self.varlabel = Text(self,height=1, width=20)
        self.varlabel.insert(END,"Which Variable?")
        
        # Place widget on the Frame according to a grid
        self.varlabel.grid(row=0,column=0,sticky=W)
        
        # Second text label asking user which units are being used
        self.unitlabel = Text(self,height=1,width=20)
        self.unitlabel.insert(END,"Which Units?")
        self.unitlabel.grid(row=0,column=1,sticky=W)
        
        # Third text label asking user for numerical value
        
        self.numlabel = Text(self,height=1, width=20)
        self.numlabel.insert(END,"Enter Variable Values")
        self.numlabel.grid(row=0,column=2,sticky=W)
        
        # This creates a list of options for the user to select
        self.inputlist = Listbox(self, height=4, selectmode=SINGLE)
      
        # Tuple of choices we're going to put in this list
        self.paramlist = ('Frequency', 'Wavelength', 'Energy')
        
        # Add each item separately
        for item in self.paramlist:
            self.inputlist.insert(END,item)
            
        # Add it to the grid    
        self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W)
        
        # Add a unit list (several combinations of units allowed)
        
        self.unitlist = Listbox(self, height=4,selectmode=SINGLE)
        self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W)
    
        # Number Entry Boxes (and Text Labels)
        
        self.inputlabel = Text(self,height=1,width=20)
        self.inputlabel.insert(END,"Waiting Selection")
        self.inputlabel.grid(row=1,column=2,sticky=W)
        
        self.inputfield = Entry(self)
        self.inputfield.grid(row=2,column=2,sticky=W)
        
        # Text Output Boxes
        self.wavoutput = Text(self, height=5, width=20)
        self.wavoutput.grid(row=7,column=0,rowspan=5,sticky=W)
        self.wavoutput.insert(END, "Wavelength: \n")
        
        self.freqoutput = Text(self, height=5, width=20)
        self.freqoutput.grid(row=7,column=1,rowspan=5,sticky=W)
        self.freqoutput.insert(END, "Frequency: \n")
        
        self.energoutput = Text(self, height=5, width=20)
        self.energoutput.grid(row=7,column=2,rowspan=5,sticky=W)
        self.energoutput.insert(END, "Energy: \n")
        
        # Create the Quit Button
        self.quitButton=Button(self,text='Quit',command=self.quit)
        self.quitButton.grid(row =13, column=0, sticky=W)
             

    # Event handler functions begin here    
    # This handler defines the choice of units available to the user, 
    # depending on selected variable
    
    def __varChoice(self, event):
        '''Handles the selection of variable: updates the list of units'''
        # Firstly, delete anything already in the units column
        self.unitlist.delete(first=0,last=len(self.myvalues))
        num = 0
        
        # Identify which option was clicked on
        try:
            num = self.inputlist.curselection()[0]       
            self.varchoice = int(num)
            
        except:
            self.varchoice = 0
            return
        
        # Get the string associated with this choice
        selection= self.inputlist.get(self.varchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.inputlist.itemconfig(self.varchoice, selectbackground='red')
        
        # If statement defines units being used
        if selection =='Wavelength':
            self.myunits = self.wavunits
            self.myvalues = self.wavvalues
            self.mydict = self.wavdict
        elif selection == 'Frequency':
            self.myunits = self.frequnits
            self.myvalues = self.freqvalues
            self.mydict = self.freqdict
        elif selection == 'Energy':
            self.myunits = self.energunits
            self.myvalues = self.energvalues
            self.mydict = self.energdict
            
        
        self.inputlabel.delete("1.0",index2=END)
        self.inputlabel.insert(END,selection)
        
        
        for i in range(len(self.myunits)):
            self.unitlist.insert(END,self.myunits[i])
        
    def __unitChoice(self,event):
        '''Handles the selection of units'''
        num = 0
        # Find which number is selected
        try:
            num = self.unitlist.curselection()[0]       
            self.unitchoice = int(num)
            
        except:
            self.unitchoice = 0
            return
        
        # Get the string (i.e. which unit is selected)
        selection= self.unitlist.get(self.unitchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.unitlist.itemconfig(self.unitchoice, selectbackground='red')
        
    # Handler takes current state of GUI, and calculates results
    def __calcConversion(self,event):
        '''This method takes the current state of all GUI variables, calculates one of four equations'''
        
        # Which variable has been selected for calculation?
        # This decides what equation to use
        
        a = self.inputfield.get()
        var = self.unitlist.get(self.unitchoice)
        a=float(a)
        
        freq = 0.0
        wav = 0.0
        energy = 0.0
        
        if self.varchoice==0:
            freq = a
            freq = freq*self.mydict[var]
            wav = self.speed/freq
            energy = self.h*freq/self.energdict['erg']
            
        elif self.varchoice==1:
            wav = a
            wav = wav*self.mydict[var]
            freq = self.speed/wav
            energy = self.speed*self.h/wav
            
        elif self.varchoice==2:
            energy = a
            energy=energy*self.energdict["erg"]
            freq = energy/self.h
            wav = self.speed*self.h/energy
            energy = energy*self.mydict[var]/self.energdict["erg"]
        
        # Remove all text in the output boxes
        self.wavoutput.delete("1.0",index2=END)
        self.freqoutput.delete("1.0",index2=END)
        self.energoutput.delete("1.0",index2=END)
        
        self.wavoutput.insert(END, "Wavelength: \n")
        self.freqoutput.insert(END, "Frequency: \n")
        self.energoutput.insert(END, "Energy: \n")
        
        # Calculate each conversion and output it to the GUI
        for i in range(len(self.wavvalues)):
            # As all units stored in cgs values, conversion is simple
            output = wav/self.wavvalues[i]
            
            # Express output in 
            
            # Add to the output list
            self.wavoutput.insert(END,self.wavunits[i] + ":  %.4e" % output+"\n")  
            
            
        for i in range(len(self.freqvalues)):
            # As all units stored in cgs values, conversion is simple
            output = freq/self.freqvalues[i]
            # Add to the output list
            self.freqoutput.insert(END,self.frequnits[i] + ":  %.4e" % output+"\n")        
            
        for i in range(len(self.energvalues)):
            # As all units stored in cgs values, conversion is simple
            output = energy/self.energvalues[i]
            # Add to the output list
            self.energoutput.insert(END,self.energunits[i] + ":  %.4e" % output+"\n")       
Beispiel #57
-1
    def startUI(self):

        self.parent.title("Testing")

        self.file_list = listdir(getcwd())

        fileBox = Listbox(self.parent, selectmode=SINGLE)
        fileBox.pack()
        fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S)

        textBox = Text(self.parent)
        textBox.grid(column=4, row=0, columnspan=4, rowspan=10, sticky=N + S + E)

        ipBox = Entry(self.parent)
        ipBox.grid(column=0, row=0)

        btn = Button(text="Open ->", command=lambda: self.readFile(fileBox, textBox))
        btn.grid(column=3, row=2)

        btnFire = Button(text="Fire away!", command=lambda: self.fireTorpedoes(ipBox, textBox))
        btnFire.grid(column=3, row=3)

        scrlBar = Scrollbar(self.parent, command=textBox.yview)
        scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S)
        textBox.config(yscrollcommand=scrlBar.set)

        for i in self.file_list:
            fileBox.insert(END, i)
Beispiel #58
-1
def CreateListBox(parent, x, y, val):
    """ Listbox to show the spelling list """
    lstbox = Listbox(parent, listvariable=val, selectmode="extended")
    lstbox.grid(column=x, row=y)
    sbar = Scrollbar(parent, orient="vertical", command=lstbox.yview)
    sbar.grid(column=x+1, row=y, sticky="ns")
    lstbox['yscrollcommand'] = sbar.set
    return lstbox
Beispiel #59
-1
class ResultList(Frame):
    """
    Result List widget
    """

    def __init__(self, master=None):
        Frame.__init__(self, master, padx=3, pady=3)
        self.columnconfigure(0, weight=1, minsize=50)
        self.columnconfigure(1, weight=1000)
        self.columnconfigure(2, weight=1, minsize=10)
        self.__createWidgets()
        self.show()

    def __createWidgets(self):
        self.lbl = Label(text="")
        self.lbl.grid(row=1, column=0, columnspan=2, in_=self)
        self.__hide_button = Button(text="Hide", command=self.hide)
        self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self)
        self.__yScroll = Scrollbar(orient=VERTICAL)
        self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE)
        self.__yScroll.config(command=self.list.yview)

    def show(self):
        self.__hide_button.config(text="Hide", command=self.hide)
        self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self)
        self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self)

    def hide(self):
        self.__hide_button.config(text="Show", command=self.show)
        self.list.grid_forget()
        self.__yScroll.grid_forget()

    def clear(self):
        self.list.delete(0, END)

    def fill(self, valList):
        self.clear()
        for v in valList:
            self.list.insert(END, v)
        self.list.see(0)
        self.select(0)

    def append(self, val):
        self.list.insert(END, val)
        self.list.see(END)

    def select(self, index=0):
        self.list.selection_set(index)

    def selected(self):
        return int(self.list.curselection()[0])

    def width(self, width):
        self.list.config(width=width)