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

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

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        """构建界面"""
        self.radio_value = IntVar()

        Label(self, text="网络安全").grid(row=0, column=2, pady=10)
        # 生成label
        Label(self, text="用户名").grid(row=3, column=1, pady=10)
        Label(self, text="密码").grid(row=4, column=1)
        # 生成用户名和密码输入框
        self.name_input = Entry(self)
        self.name_input.grid(row=3, column=2)
        self.password = Entry(self)
        self.password['show'] = '*'
        self.password.grid(row=4, column=2)

        self.radio = Radiobutton(self, text="rsa", variable=self.radio_value, padx=20, value=1)
        self.radio.grid(row=5, column=1)

        self.radio1 = Radiobutton(self, text="des", variable=self.radio_value, padx=20, value=2)
        self.radio1.grid(row=6, column=1)

        self.alert_button = Button(self, text='提交', command=self.submit)
        self.alert_button.grid(row=7, column=1)

    def submit(self):
        """提交处理"""
        name = self.name_input.get() or 'username'
        password = self.password.get() or "password"
        cryption = self.radio_value.get() or "1"
        # 构造传输的数据
        data = name + ',' + password

        cryption = Crypt()
        my_socket = Mysocket()
        # 判断使用des还是rsa
        if cryption == 2:
            data = "des" + data
            need = 8 - (len(data) % 8)
            while need > 0:
                data += " "
                need -= 1
            result = cryption.des_encrypt(data)
            result = "des" + result
        else:
            result = cryption.rsa_encrypt(data)
            result = "rsa" + result
        result = my_socket.make_connect(result)

        if result >= 0:
            tkMessageBox.showinfo('Message', '%s' % '合法用户')
        else:
            tkMessageBox.showinfo('Message', '%s' % '非法用户')
예제 #3
0
def addRadioButton(frame, label, value, variable, position, bindEvent=1):
    button = Radiobutton(frame, text=label, variable=variable, value=value)
    button.grid(row=0, column=position)
    
    if bindEvent:
        variable.trace("w", calculate)
        
    return button
예제 #4
0
    def minormax(self):
        objheader = headersmall(self.frame, text="Objective:")

        rmim = Radiobutton(self.frame, text="Minimize", variable=self.params["objective"], value="min", bg=Styles.colours["grey"])
        rmax = Radiobutton(self.frame, text="Maximize", variable=self.params["objective"], value="max", bg=Styles.colours["grey"])

        objheader.grid(row=7, column=1, sticky=W, columnspan=2)
        rmim.grid(row=8, column=1, pady=0, sticky=W, padx=10)
        rmax.grid(row=9, column=1, pady=0, sticky=W, padx=10)
	def time(self):
		from Tkinter import LabelFrame
		time_frame = LabelFrame(self.root, height = 100, width = 150, text = "Time settings")
		time_frame.grid(column = 1, row = 0, columnspan = 1, rowspan = 1)

		from Tkinter import Radiobutton
		time_now = Radiobutton(time_frame, text = "Now", variable = time, value = 1)
		time_now.grid(column = 0, row = 0, columnspan = 1, rowspan = 1)
		time_selection = Radiobutton(time_frame, text = "Select", variable = time, value = 2)
		time_selection.grid(column = 0, row = 1, columnspan = 1, rowspan = 1)
예제 #6
0
    def interface_parametres(self, root):
        """!Création de l'interface de choix des logiciels de visualisation
        On permet à l'utilisateur de choisir Gmsh/Xmgrace ou Salome
        """

        main_param = Frame(root)
        main_param.rowconfigure(1, weight=1)
        main_param.columnconfigure(0, weight=1)

        f = Frame(main_param, relief='sunken', borderwidth=1)
        # les parametres vont dans 'f'
        logiciels_frame = Frame(f, borderwidth=4)

        label_parametres_salome = Label(
            logiciels_frame, text=u"Paramètres Salome")
        label_parametres_salome.grid(row=2, column=1, columnspan=2)
        self.salome_widgets.append(label_parametres_salome)

        label_port = Label(logiciels_frame, text=u"Port")
        label_port.grid(row=3, column=1, sticky='w')
        self.salome_widgets.append(label_port)

        entry_salome_port = Entry(
            logiciels_frame, textvariable=self.salome_port)
        entry_salome_port.grid(row=3, column=2)
        self.salome_widgets.append(entry_salome_port)
        self.salome_port.set(self.get_runnig_salome_port())
        self.ce_salome = None

        liste_etudes = StudyList(
            logiciels_frame, self, u"choix de l'étude Salomé")
        liste_etudes.grid(row=4, column=2, sticky='w')
        self.salome_widgets.append(liste_etudes.liste)
        self.salome_widgets.append(liste_etudes.titre)
        liste_etudes.actualiser()

        label_choix_logiciel = Label(
            logiciels_frame, text=u"Choix du logiciel")
        label_choix_logiciel.grid(row=0, column=0, columnspan=3)
        button_gmsh = Radiobutton(
            logiciels_frame, text=u"Gmsh/Xmgrace", value="Gmsh/Xmgrace", variable=self.logiciel,
                                  command=self.desactivate_salome_widgets)
        button_gmsh.grid(row=1, column=0, sticky='w')

        button_salome = Radiobutton(
            logiciels_frame, text=u"Salomé", value="Salome", variable=self.logiciel,
            command=self.activate_salome_widgets)
        button_salome.grid(row=2, column=0, rowspan=3, sticky='w')

        self.logiciel.set("Salome")

        logiciels_frame.grid(row=1)

        f.grid(row=1, sticky='w' + 'e' + 's' + 'n')
        return main_param
예제 #7
0
 def create_radio_buttons(self):
     # Scale related
     entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR']
     self.scale = StringVar()
     self.scale.set('DIATONIC')
     self.rb_frame = Frame(self)
     for e in entries:
         rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W,
                          command=self.send_scale, variable=self.scale)
         rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W)
     self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3)
예제 #8
0
 def build_widgets(self, master, row):
     self.var = IntVar(master)
     self.init_var()
     label = Label(master, text = self.label + ':')
     label.grid(row = row, columnspan = 4, sticky = W)
     choices = self.range
     for j in range(len(choices)):
         # XXX Translatable text
         b = Radiobutton(master, text=choices[j], command = self.var_changed,
                         variable = self.var, value = j, indicatoron = 1)
         b.grid(row = row+j+1, column = 1, columnspan = 3, sticky = W)
    def time(self):
        from Tkinter import LabelFrame
        time_frame = LabelFrame(self.root,
                                height=100,
                                width=150,
                                text="Time settings")
        time_frame.grid(column=1, row=0, columnspan=1, rowspan=1)

        from Tkinter import Radiobutton
        time_now = Radiobutton(time_frame, text="Now", variable=time, value=1)
        time_now.grid(column=0, row=0, columnspan=1, rowspan=1)
        time_selection = Radiobutton(time_frame,
                                     text="Select",
                                     variable=time,
                                     value=2)
        time_selection.grid(column=0, row=1, columnspan=1, rowspan=1)
예제 #10
0
    def Show():
        Gui.configuration.ReadConfiguration()

        Gui.top = Tkinter.Tk()
        Gui.top.title("SGS performance test")

        label = Label(Gui.top, text="Select options and execute tasks", height=2)
        label.grid(row=0, sticky=W)

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

        Gui.var = IntVar()
        Gui.var.set(1 if Gui.configuration.IsBuildTypeDebug() else 2)
        R1 = Radiobutton(Gui.top, text="Debug Build", variable=Gui.var, value=1, height=2,command=Gui.BuildType)
        R1.grid(row=1, sticky=W)
        R2 = Radiobutton(Gui.top, text="Release Build", variable=Gui.var, value=2, height=2, command=Gui.BuildType)
        R2.grid(row=2, sticky=W)

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

        Gui.dirLabel = Label(Gui.top, text='Dir: ', bd=4)
        Gui.dirLabel.grid(row=3, sticky=W)
        Gui.UpdateDirLabel()

        dirButton = Tkinter.Button(Gui.top, text='Select dir containing cpp/external', bd=4, command=Gui.AskDirectory)
        dirButton.grid(row=4, sticky=W)

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

        def SetupCallBack():
           print "Setup"
        setup = Tkinter.Button(Gui.top, text ="Setup", bd=4, command = Gui.SetupCallBack)
        setup.grid(row=5, sticky=W)

        def ExecuteCallBack():
           print "Execute"
        execute = Tkinter.Button(Gui.top, text ="Execute", bd=4, command = Gui.ExecuteCallBack)
        execute.grid(row=6, sticky=W)

        # new line
        print ''
        Gui.top.mainloop()
예제 #11
0
    def solver(self):
        solverheader = headersmall(self.frame, text="Solvers:")
        direct = Radiobutton(self.frame, text="Direct", variable=self.params["solver"], value="direct",
                             bg=Styles.colours["grey"])
        lbfgs = Radiobutton(self.frame, text="LBFGS", variable=self.params["solver"], value="lbfgs",
                            bg=Styles.colours["grey"])
        message = Message(self.frame, text="Enable normalization if you use lbfgs", width=200)
        try:
            import nlopt
        except:
            self.params["solver"].set("lbfgs")
            self.params["normalize"].set(1)
            direct.config(state=DISABLED)
            message.config(text="You do not have nlopt library installed to use the Direct Solver",
                           bg=Styles.colours["lightRed"])

        normalize = Checkbutton(self.frame, text="Normalize Input", variable=self.params["normalize"],
                                bg=Styles.colours["grey"])

        solverheader.grid(row=1, column=0, sticky=W, columnspan=2)
        direct.grid(row=2, column=0, pady=0, sticky=W, padx=10)
        lbfgs.grid(row=3, column=0, pady=0, sticky=W, padx=10)
        message.grid(row=2, column=1, rowspan=1)
        normalize.grid(row=3, column=1)
예제 #12
0
파일: widgets.py 프로젝트: arnew/dxf2gcode
    def add_screen(self, fr, title):

        b = Radiobutton(self.rb_fr, bd=1, text=title, indicatoron=0, \
                        variable=self.choice, value=self.count, \
                        command=lambda: self.display(fr))
        
        b.grid(column=self.count, row=0, sticky=N + E + W)
        self.rb_fr.columnconfigure(self.count, weight=1)

        fr.grid(sticky=N + W + E)
        self.screen_fr.columnconfigure(0, weight=1)
        fr.grid_remove()

        # ensures the first frame will be
        # the first selected/enabled
        if not self.active_fr:
            fr.grid()
            self.active_fr = fr

        self.count += 1

        # returns a reference to the newly created
        # radiobutton (allowing its configuration/destruction)
        return b
예제 #13
0
    def rec(self):
        recheader = headersmall(self.frame, text="Recommender:")

        incumbent = Radiobutton(self.frame, text="Incumbent", variable=self.params["recommender"], value="incumbent",
                                bg=Styles.colours["grey"])
        latent = Radiobutton(self.frame, text="Latent", variable=self.params["recommender"], value="latent",
                             bg=Styles.colours["grey"])
        observed = Radiobutton(self.frame, text="Observed", variable=self.params["recommender"], value="observed",
                               bg=Styles.colours["grey"])

        recheader.grid(row=4, column=0, sticky=W, columnspan=1)
        incumbent.grid(row=5, column=0, pady=0, sticky=W, padx=10)
        latent.grid(row=6, column=0, pady=0, sticky=W, padx=10)
        observed.grid(row=7, column=0, pady=0, sticky=W, padx=10)
예제 #14
0
    def initial(self):
        iniheader = headersmall(self.frame, text="Initial points sampler:")

        latin = Radiobutton(self.frame, text="Latin", variable=self.params["initializer"], value="latin",
                            bg=Styles.colours["grey"])
        sobol = Radiobutton(self.frame, text="Sobol", variable=self.params["initializer"], value="sobol",
                            bg=Styles.colours["grey"])
        uniform = Radiobutton(self.frame, text="Uniform", variable=self.params["initializer"], value="uniform",
                              bg=Styles.colours["grey"])

        iniheader.grid(row=4, column=1, sticky=W, columnspan=1)
        latin.grid(row=5, column=1, pady=0, sticky=W, padx=10)
        sobol.grid(row=6, column=1, pady=0, sticky=W, padx=10)
        uniform.grid(row=7, column=1, pady=0, sticky=W, padx=10)
class getDist():
    def __init__(self, master):
        self.master = master
        self.startwindow()
        #self.b=0    # no need for this, directly store in the global variable

    def startwindow(self):

        self.var1 = IntVar()
        self.textvar = StringVar()

        self.Label1 = Label(self.master, text="Search distance (meters)")
        self.Label1.grid(row=0, column=0)

        self.Label2 = Label(self.master, textvariable=self.textvar)
        self.Label2.grid(row=2, column=0)

        self.rb1 = Radiobutton(self.master,
                               text="5000",
                               variable=self.var1,
                               value=5000,
                               command=self.cb1select)
        self.rb1.grid(row=1, column=0, sticky=W)

        self.rb2 = Radiobutton(self.master,
                               text="625",
                               variable=self.var1,
                               value=625,
                               command=self.cb1select)
        self.rb2.grid(row=1, column=1, sticky=W)

        self.rb3 = Radiobutton(self.master,
                               text="160",
                               variable=self.var1,
                               value=160,
                               command=self.cb1select)
        self.rb3.grid(row=1, column=2, sticky=W)

        self.Button1 = Button(self.master, text="ok", command=self.ButtonClick)
        self.Button1.grid(row=2, column=2)

    def ButtonClick(self):
        global dist
        dist = self.var1.get()
        self.master.quit()

    def cb1select(self):
        return self.var1.get()
class getDist():
    def __init__(self, master):
        self.master=master
        self.startwindow()
        #self.b=0    # no need for this, directly store in the global variable

    def startwindow(self):

        self.var1 = IntVar()
        self.textvar = StringVar()

        self.Label1=Label(self.master, text="Search distance (meters)")
        self.Label1.grid(row=0, column=0)

        self.Label2=Label(self.master, textvariable=self.textvar)
        self.Label2.grid(row=2, column=0)

        self.rb1 = Radiobutton(self.master, text="5000", variable=self.var1,
                               value=5000, command=self.cb1select)
        self.rb1.grid(row=1, column=0, sticky=W)

        self.rb2 = Radiobutton(self.master, text="625", variable=self.var1,
                               value=625, command=self.cb1select)
        self.rb2.grid(row=1, column=1, sticky=W)

        self.rb3 = Radiobutton(self.master, text="160", variable=self.var1,
                               value=160, command=self.cb1select)
        self.rb3.grid(row=1, column=2, sticky=W)
        
        self.Button1=Button(self.master, text="ok", command=self.ButtonClick)
        self.Button1.grid(row=2, column=2)
    def ButtonClick(self):
        global dist
        dist = self.var1.get()
        self.master.quit()

    def cb1select(self):
        return self.var1.get()
예제 #17
0
    def __draw_current_choice(self, parent):
        
        choice = IntVar()
        other_player = StringVar()
        recommended = self.game.most_recommended_player_remaining()
        valuable = self.game.get_best_player_remaining()
        
        recommended_button = Radiobutton(parent, text=recommended, variable=choice, value=1)
        valuable_button = Radiobutton(parent, text=valuable, variable=choice, value=2)
        other_button = Radiobutton(parent, text="", variable=choice, takefocus=0, value=3)
        other_text = Entry(parent, textvariable=other_player)
        
        def text_focus(event):
            other_button.select()
        
        other_text.bind("<Button-1>", text_focus)

        def pick_player():

            decision = choice.get()

            if decision == 1:

                player = self.game.most_recommended_player_remaining()
                self.game.add_player_to_team(player)
                utils.remove_player_from_possible_players(
                    player,
                    self.game.connection,
                    self.game.cursor)
                self.user_pick_made.set(True)

            elif decision == 2:

                player = self.game.get_best_player_remaining()
                self.game.add_player_to_team(player)
                utils.remove_player_from_possible_players(
                    player,
                    self.game.connection,
                    self.game.cursor)
                self.user_pick_made.set(True)

            elif decision == 3:
                player = other_player.get()
                try:
                    self.game.add_player_to_team(player)
                    utils.remove_player_from_possible_players(
                        player,
                        self.game.connection,
                        self.game.cursor)
                    self.user_pick_made.set(True)
                except:
                    tkMessageBox.showinfo("Error", "Can't add that player to team, try again.")
                    self.user_pick_logic()

            else:
                tkMessageBox.showinfo("No Selection", "Please make a selection")
                self.user_pick_logic()

        def pick_player_button(event):
            pick_player()

        Label(parent, text="Recommended Player").grid(sticky="w", row=1)
        recommended_button.grid(sticky="w", row=1, column=1, columnspan=2)
        
        Label(parent, text="Most Valuable Player").grid(sticky="w", row=2)
        valuable_button.grid(sticky="w", row=2, column=1, columnspan=2)
        
        Label(parent, text="Choose other Player").grid(sticky="w", row=3)
        other_button.grid(sticky="w", row=3, column=1)
        other_text.grid(row=3, column=2, sticky="w", padx=5)
        
        pick_button = Button(parent, text="Pick", command=pick_player).grid(
            row=4, columnspan=3, sticky="ne", padx=5)
        self.parent.bind("<Return>", pick_player_button)
예제 #18
0
chk = Checkbutton(window, text='Choose', var=chk_state)
chk.grid(column=1, row=3)
''' radiobutton ( [1] [2] [3] button )'''

selected = IntVar()
rad1 = Radiobutton(window, text='First', value=1, variable=selected)
rad2 = Radiobutton(window, text='Second', value=2, variable=selected)
rad3 = Radiobutton(window, text='Third', value=3, variable=selected)


def clicked():
    print(selected.get())


btn = Button(window, text="Click Me", command=clicked)
rad1.grid(column=0, row=4)
rad2.grid(column=1, row=4)
rad3.grid(column=2, row=4)
btn.grid(column=3, row=4)
''' textarea '''

txt = tkst.ScrolledText(window, width=40, height=10)
txt.grid(column=0, row=5)
txt.insert(INSERT, 'You text goes here')


def delete_text():
    ''' show this text when the button is clicked'''
    txt.delete(1.0, END)  # to clear the text

예제 #19
0
    def Show():
        Gui.configuration.ReadConfiguration()

        Gui.top = Tkinter.Tk()
        Gui.top.title("SGS performance test")

        label = Label(Gui.top,
                      text="Select options and execute tasks",
                      height=2)
        label.grid(row=0, sticky=W)

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

        Gui.var = IntVar()
        Gui.var.set(1 if Gui.configuration.IsBuildTypeDebug() else 2)
        R1 = Radiobutton(Gui.top,
                         text="Debug Build",
                         variable=Gui.var,
                         value=1,
                         height=2,
                         command=Gui.BuildType)
        R1.grid(row=1, sticky=W)
        R2 = Radiobutton(Gui.top,
                         text="Release Build",
                         variable=Gui.var,
                         value=2,
                         height=2,
                         command=Gui.BuildType)
        R2.grid(row=2, sticky=W)

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

        Gui.dirLabel = Label(Gui.top, text='Dir: ', bd=4)
        Gui.dirLabel.grid(row=3, sticky=W)
        Gui.UpdateDirLabel()

        dirButton = Tkinter.Button(Gui.top,
                                   text='Select dir containing cpp/external',
                                   bd=4,
                                   command=Gui.AskDirectory)
        dirButton.grid(row=4, sticky=W)

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

        def SetupCallBack():
            print "Setup"

        setup = Tkinter.Button(Gui.top,
                               text="Setup",
                               bd=4,
                               command=Gui.SetupCallBack)
        setup.grid(row=5, sticky=W)

        def ExecuteCallBack():
            print "Execute"

        execute = Tkinter.Button(Gui.top,
                                 text="Execute",
                                 bd=4,
                                 command=Gui.ExecuteCallBack)
        execute.grid(row=6, sticky=W)

        # new line
        print ''
        Gui.top.mainloop()
예제 #20
0
class HutGame:
    def __init__(self, parent):
        """A game where the player selects a hut to rest.

        The program initially puts 'enemy' or a 'friend' inside each hut. Some
        huts could also be left 'unoccupied'. You are asked to select a hut.
        You win if the hut occupant is either a 'friend' or if the hut is not
        occupied.

        :param parent: the parent tkinter widget
        :ivar list huts: list to store occupant types (as strings)
        :ivar int hut_width: the width of the application window in pixels
        :ivar int hut_height: the height of the application window in pixels
        :ivar PhotoImage village_image: background image for the app
        :ivar PhotoImage hut_image: the hut image for the radio buttons
        :ivar Tk container: the main widget serving as a parent for others. In
            this example it is just the main Tk instance.
        :ivar str result: the string to declare the result via a messagebox.
        """
        self.village_image = PhotoImage(file="jungle_small.gif")
        self.hut_image = PhotoImage(file="hut_small.gif")
        self.hut_width = 40
        self.hut_height = 56
        self.container = parent
        self.huts = []
        self.result = ""
        self.occupy_huts()
        self.setup()

    def occupy_huts(self):
        """Randomly occupy the huts: enemy or friend or keep unoccupied"""
        occupants = ['enemy', 'friend', 'unoccupied']
        while len(self.huts) < 5:
            self.huts = [random.choice(occupants) for _ in range(5)]
        print("Hut occupants are: {0}".format(', '.join(self.huts)))

    def enter_hut(self, hut_number):
        """Enter the selected hut and determine the winner

        This method checks the hut occupant stored in self.huts for the
        given hut_number. Depending on the occupant the winner is 'announced'.

        :param hut_number: the number assigned to the selected hut

        .. seealso:: :py:meth: `occupy_huts`
        .. seealso:: the equivalent method in fiel hutgame_mvc.py
        """
        print("Entering hut #: {0}".format(hut_number))
        hut_occupant = self.huts[hut_number-1]
        print("Hut occupant is: {0}".format(hut_occupant))

        if hut_occupant == 'enemy':
            self.result = "Enemy sighted in Hut # {0}\n\n".format(hut_number)
            self.result += "YOU LOSE :( Luck next time!"
        elif hut_occupant == 'unoccupied':
            self.result = "Hut # {0} is unoccupied!\n\n".format(hut_number)
            self.result += "Congratulations! YOU WIN!!!"
        else:
            self.result = "Friend sighted in Hut # {0}\n\n".format(hut_number)
            self.result += "Congratulations! YOU WIN!!!"

        # Announce the winner!
        self.announce_winner(self.result)

    def create_widgets(self):
        """Create various widges in the tkinter main window."""
        self.var = IntVar()
        self.background_label = Label(self.container, image=self.village_image)
        txt = "Select a hut to enter. You win if:\n"
        txt += "The hut is unoccupie or the occupant is a friend!"
        self.info_label = Label(self.container, text=txt, bg='yellow')

        # Create a dictionary for radio button config options.
        r_btn_config = {'variable': self.var,
                        'bg': '#A8884C',
                        'activebackground': 'yellow',
                        'image': self.hut_image,
                        'height': self.hut_height,
                        'width': self.hut_width,
                        'command': self.radio_btn_pressed}

        self.r1 = Radiobutton(self.container, r_btn_config, value=1)
        self.r2 = Radiobutton(self.container, r_btn_config, value=2)
        self.r3 = Radiobutton(self.container, r_btn_config, value=3)
        self.r4 = Radiobutton(self.container, r_btn_config, value=4)
        self.r5 = Radiobutton(self.container, r_btn_config, value=5)

    def setup(self):
        """Calls methods to setup the user interface."""
        self.create_widgets()
        self.setup_layout()

    def setup_layout(self):
        """Use the grid geometry manager to place widgets."""
        self.container.grid_rowconfigure(1, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(4, weight=1)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.info_label.grid(row=0, column=0, columnspan=5, sticky='nsew')
        self.r1.grid(row=1, column=0)
        self.r2.grid(row=1, column=4)
        self.r3.grid(row=2, column=3)
        self.r4.grid(row=3, column=0)
        self.r5.grid(row=4, column=4)

    def announce_winner(self, data):
        """Declare the winner by displaying a tkinter messagebox.

        :param data: the data to be 'published'. This could be any object.
        """
        messagebox.showinfo("Winner Announcement", message=data)

    # Handle Events
    def radio_btn_pressed(self):
        """Command callback when radio button is pressed.

        .. seealso:: :py:meth: `create_widgets`
        """
        self.enter_hut(self.var.get())
예제 #21
0
    def __init__(self, parent, bondForceParams, atoms_def):
        self.parent = parent
        self.main = Toplevel(self.parent)
        self.bondForceParams = bondForceParams
        self.atoms_def = atoms_def
        self.main.title('PyFepRestr')
        self.validated_values = []

        if platform == "darwin":
            self.button_font = self.label_font = self.radiobutton_font = Font(
                family='Arial', size=15)
        else:
            self.radiobutton_font = Font(font=Radiobutton()["font"])
            self.label_font = Font(font=Label()["font"])
            self.button_font = Font(font=Button()["font"])

        self.r_var = BooleanVar()
        self.r_var.set(1)
        rj1 = Radiobutton(self.main,
                          text='kJ',
                          variable=self.r_var,
                          value=0,
                          command=self.refresh,
                          font=self.radiobutton_font)
        rcal1 = Radiobutton(self.main,
                            text="kCal",
                            variable=self.r_var,
                            value=1,
                            command=self.refresh,
                            font=self.radiobutton_font)
        rj1.grid(row=0, column=0, padx=5, pady=5)
        rcal1.grid(row=0, column=1, padx=5, pady=5)

        labels = [
            'Temp', 'K raA', u'K \u03b8a', u'K \u03b8A', u'K \u03c6ba',
            u'K \u03c6aA', u'K \u03c6AB'
        ]

        label_all = []
        self.entry_all = []
        self.entry_all_get = []
        self.dimen_all = []
        for lab in labels:
            label_answer = Label(self.main,
                                 text=lab,
                                 anchor=W,
                                 font=self.label_font)
            label_all.append(label_answer)
            entry = Entry(self.main)
            self.entry_all.append(entry)
            self.entry_all_get.append(entry.get)
            dimen = Label(self.main, anchor=W, font=self.label_font)
            self.dimen_all.append(dimen)

        for i, (label, entry, dimen) in enumerate(
                zip(label_all, self.entry_all, self.dimen_all)):
            label.grid(row=i + 1, column=1, padx=5, pady=5, sticky=W)
            entry.grid(row=i + 1, column=2, padx=5, pady=5, sticky=W)
            dimen.grid(row=i + 1, column=3, padx=10, pady=5, sticky=W)

        self.dimen_all[0]['text'] = 'Kelvin'
        self.refresh()

        self.button_res = Button(self.main,
                                 text="Next -> ",
                                 command=self.validate,
                                 font=self.button_font)
        self.button_res.grid(row=11, column=2, padx=5, pady=5)

        self.destroyProgr = Button(self.main,
                                   text='Exit',
                                   bg='red',
                                   command=self.main.destroy,
                                   font=self.button_font)
        self.destroyProgr.grid(row=0, column=3, padx=5, pady=5)

        self.helpProgr = Button(self.main,
                                text=' ? ',
                                bg='#ffb3fe',
                                command=self.getHelp,
                                font=self.button_font)
        self.helpProgr.grid(row=12, column=0, padx=5, pady=5)

        self.select_atoms = StringVar()
        self.select_atoms.set("Select 6 atoms")
        atoms_list = ["Select 6 atoms", "Select 2 atoms"]
        menu = OptionMenu(self.main, self.select_atoms, *atoms_list)
        menu.grid(row=11, column=3, padx=5, pady=5)
예제 #22
0
class DATAin:
    def __init__(self, maestro):
        # Atributo de conteo'''
        self.botonClics = 0
        self.bandDATA = 3
        self.operacion=""
        self.cliente = ''
        self.Producto = ''
        self.alturaDATA = 0
        self.anchoDATA = 0
        self.largoDATA = 0
        self.Datos = []
        for i in range (7):
            self.Datos.append('')
            
        self.consoleSQL = PSQLmerma1()
        #gg = Tkk.Notebook(maestro)
        self.top = Toplevel(maestro)
        self.top.title('Introduce medidas de la caja')
        self.top.update_idletasks()
#        w = self.top.winfo_screenwidth()
#        h = self.top.winfo_screenheight()
#        size = tuple(int(_) for _ in self.top.geometry().split('+')[0].split('x'))
#        x = w/2 - size[0]/2
#        y = h/2 - size[1]/2
#        print size + (x, y)
#        
        self.top.geometry("+150+60")
        #self.top.iconbitmap('/home/pi/Desktop/ProgGUI/GUI/resources/ICO/IconoBCT.ico')
        
        #MARCO3 ESEL LINEZO DONDE SE DIBUJAN LAS PESTAÑAS
        self.marco3 = TTK.Notebook(self.top)

        # CREAMOS EL MARCO PARA CADA UNA DE LAS PESTAÑAS
        self.page1 = TTK.Frame(self.marco3)
        self.page2 = TTK.Frame(self.marco3)
        self.page3 = TTK.Frame(self.marco3)
        self.page4 = TTK.Frame(self.marco3)
        self.page5 = TTK.Frame(self.marco3)
       
        # AGREGAMOS EL MARCO A LAS PESTAÑAS Y SU NOMBRE
        self.marco3.add(self.page1, text='Dimensiones de la caja')
        self.marco3.add(self.page2, text='Descripción de la caja')
        self.marco3.add(self.page3, text='Descripción de la prueba')
        self.marco3.add(self.page4, text='Datos del cliente')
        self.marco3.add(self.page5, text='Resumen de datos')
        self.marco3.grid()
        
        # AGREGAGOS CONTENIDO A PESTAÑA 1
        self.IMGcaja = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/caja.png')
        self.IMGancho= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/anchoSelect.png')
        self.IMGlargo= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/largoSelect.png')
        self.IMGalto = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/altoSelect.png')
        
        self.cajaLB = Label(self.page1, image = self.IMGcaja)
        self.cajaLB.grid(row = 0, column = 4, rowspan = 5, columnspan = 3)
        
        self.txtLB = 'Seleccione un botón e ingrese \n las medidas en cm'
        self.LB = Label(self.page1, font =('Helvetica', 15), text = self.txtLB)
        self.LB.grid(row = 0, column = 0, columnspan = 4)
        
        self.CBdata = Text(self.page1, state="disabled", width=40, height=2, font=("Helvetica",15))
        self.CBdata.grid(row = 1, column = 0, columnspan = 4)
        
        self.anchoL = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.anchoL.grid(row =4, column = 4, sticky = 's')
        self.BTNancho = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Ancho', command =lambda: self.selectCB('an'))
        self.BTNancho.grid(row = 5, column = 4)
        self.largoL = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.largoL.grid(row =4, column = 5, sticky = 's')
        self.BTNlargo = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Largo', command =lambda: self.selectCB('la'))
        self.BTNlargo.grid(row = 5, column = 5)
        self.altoL  = Label(self.page1, 
                            font =('Helvetica', 15), 
                            text = "")
        self.altoL.grid(row =4, column = 6, sticky = 's')
        self.BTNalto = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Alto', command =lambda: self.selectCB('al'))
        self.BTNalto.grid(row = 5, column = 6)
        
        boton1 = self.crearBoton(1)
        boton2 = self.crearBoton(2)
        boton3 = self.crearBoton(3)
        boton4 = self.crearBoton(4)
        boton5 = self.crearBoton(5)
        boton6 = self.crearBoton(6)
        boton7 = self.crearBoton(7)
        boton8 = self.crearBoton(8)
        boton9 = self.crearBoton(9)
        boton0 = self.crearBoton(0,ancho=7)
        botonErase = self.crearBoton(u"\u232B",escribir=False)
        botonErase['background'] = "red"
        botonErase.grid(row = 2, column = 3)
        botonEnter = self.crearBoton(u"\u21B5",escribir=False)
        botonEnter['background'] = "green"
        botonEnter.grid(row = 3, column = 3)
        botondot = self.crearBoton('.')
        
        #Ubicación de los botones
        botones=[boton7, boton8, boton9,
                 boton4, boton5, boton6,
                 boton1, boton2, boton3,
                 boton0]
        contador=0
        for fila in range(2,5):
            for columna in range(3):
                botones[contador].grid(row=fila,column=columna)
                contador+=1
        #Ubicar el último botón al final
        botones[contador].grid(row=5,column=0,columnspan=2)
        botondot.grid(row = 5, column = 2)
        
        # AGREGAGOS CONTENIDO A PESTAÑA 2
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Seleccione:')\
              .grid(row = 0, column = 0,columnspan = 5)
              
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Estilo de caja')\
              .grid(row = 1, column = 0)
              
        self.listCaja = Combobox(self.page2,
                                 state="readonly",
                                 values = ["Caja troquelada", "Caja est" + u"\xe1" + "ndar"],
                                 font =('Helvetica', 15))
        self.listCaja.grid(row = 2, column = 0)
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 2, column = 1)
        
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Tipo de flauta')\
              .grid(row = 1, column = 2)
        self.listFlauta = Combobox(self.page2,
                                   state="readonly",
                                   values = ["Corrugado sencillo B", "Corrugado sencillo C", "Corrugado sencillo E", "Doble corrugado BC", "Doble corrugado EB"],
                                   font =('Helvetica', 15))
        self.listFlauta.grid(row = 2, column = 2)
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 2, column = 3)
              
              
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Dirección de la flauta')\
              .grid(row = 1, column = 4)
        self.listFlautaD= Combobox(self.page2,
                                   state="readonly",
                                   values = ["Horizontal", "Vertical"],
                                   font =('Helvetica', 15))
        self.listFlautaD.grid(row = 2, column = 4)
                                   
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 3, column = 0, columnspan = 3)
        
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Grado del material')\
              .grid(row = 4, column = 0)
        self.listGradoM= Combobox(self.page2,
                                   state="readonly",
                                   values = ["No aplica", "20 ECT", "21 ECT", "23 ECT", "26 ECT", "29 ECT", "32 ECT", "44 ECT", "48 ECT", "50 ECT", "61 ECT", "71 ECT"],
                                   font =('Helvetica', 15))
        self.listGradoM.grid(row = 5, column = 0)
                                   
        Label(self.page2, 
              font =('Helvetica', 15), 
              text = 'Tipo de unión')\
              .grid(row = 4, column = 2)
        self.listUnion= Combobox(self.page2,
                                   state="readonly",
                                   values = ["Pegado", "Grapado", "Armado automático"],
                                   font =('Helvetica', 15))
        self.listUnion.grid(row = 5, column = 2)
        
        # AGREGAMOS CONTEIDO A PAGE3
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = 'Método de cierre')\
              .grid(row = 0, column = 0)
        self.listCierre= Combobox(self.page3,
                                   state="readonly",
                                   values = ["Conforme a la TAPPI T 804", "Otro", "No aplica"],
                                   font =('Helvetica', 15))
        self.listCierre.grid(row = 1, column = 0)
                                   
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = '             ')\
              .grid(row = 0, column = 1)
              
        Label(self.page3, 
              font =('Helvetica', 15), 
              text = 'Orientación de la prueba')\
              .grid(row = 0, column = 2)
        self.listOrientaC= Combobox(self.page3,
                                   state="readonly",
                                   values = ["Arriba a abajo", "Extremo a extremo", "Lado a lado"],
                                   font =('Helvetica', 15))
        self.listOrientaC.grid(row = 1, column = 2)
        
        self.IMGbct = Image.open(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/CajaBIedit.png')
        
        self.cajaBCT = Label(self.page3, image = self.IMGbct)
        self.cajaBCT.grid(row = 2, column = 0, columnspan = 3)
        
        # AGREGAMOS CONTENIDO A PAGE 4
        self.txtLB = 'Ingresar datos o buscar por número de pedido'
        self.state = TTK.Label(self.page4, font =('Helvetica', 15), text = self.txtLB)
        self.state.grid(row = 0, column = 0, columnspan = 12)
        
        boton1 = self.crearBotonP4(1)
        boton2 = self.crearBotonP4(2)
        boton3 = self.crearBotonP4(3)
        boton4 = self.crearBotonP4(4)
        boton5 = self.crearBotonP4(5)
        boton6 = self.crearBotonP4(6)
        boton7 = self.crearBotonP4(7)
        boton8 = self.crearBotonP4(8)
        boton9 = self.crearBotonP4(9)
        boton0 = self.crearBotonP4(0)
        
        botonQ = self.crearBotonP4('Q')
        botonW = self.crearBotonP4('W')
        botonE = self.crearBotonP4('E')
        botonR = self.crearBotonP4('R')
        botonT = self.crearBotonP4('T')
        botonY = self.crearBotonP4('Y')
        botonU = self.crearBotonP4('U')
        botonI = self.crearBotonP4('I')
        botonO = self.crearBotonP4('O')
        botonP = self.crearBotonP4('P')
        botonA = self.crearBotonP4('A')
        botonS = self.crearBotonP4('S')
        botonD = self.crearBotonP4('D')
        botonF = self.crearBotonP4('F')
        botonG = self.crearBotonP4('G')
        botonH = self.crearBotonP4('H')
        botonJ = self.crearBotonP4('J')
        botonK = self.crearBotonP4('K')
        botonL = self.crearBotonP4('L')
        botonNN= self.crearBotonP4('Ñ')
        botonZ = self.crearBotonP4('Z')
        botonX = self.crearBotonP4('X')
        botonC = self.crearBotonP4('C')
        botonV = self.crearBotonP4('V')
        botonB = self.crearBotonP4('B')
        botonN = self.crearBotonP4('N')
        botonM = self.crearBotonP4('M')
        botondot = self.crearBotonP4('.')
        botonguion = self.crearBotonP4('-')
        botonguionb = self.crearBotonP4(',')
        botonErase = self.crearBotonP4(u"\u232B",escribir=False)
        botonErase['background'] = "red"
        botonErase.grid(row = 3, column = 11)
        botonEnter = self.crearBotonP4(u"\u21B5",escribir=False,alto=2)
        botonEnter['background'] = "green"
        botonEnter.grid(row = 1, column = 11, rowspan = 2, sticky = 's')
        botonSpace = Button(self.page4, text=u"\u2423", width=5, height=1, font=("Helvetica",15), command=lambda:self.clickP4(' ',True))
        botonSpace.grid(row = 4, column = 11)
        
        #Ubicación de los botones
        botones= [boton1, boton2, boton3, boton4, boton5, boton6, boton7, boton8, boton9, boton0,
                  botonQ, botonW, botonE, botonR, botonT, botonY, botonU, botonI, botonO, botonP, 
                  botonA, botonS, botonD, botonF, botonG, botonH, botonJ, botonK, botonL, botonNN, 
                  botonZ, botonX, botonC, botonV, botonB, botonN, botonM, botondot, botonguion, botonguionb]
        contador=0
        for fila in range(1,5):
            for columna in range(10):
                botones[contador].grid(row=fila,column=columna)
                contador+=1
        
        self.ChkSe = IntVar()
        self.RBCliente = Radiobutton(self.page4, text = 'Cliente',font =('Helvetica', 15), variable = self.ChkSe, value = 1)
        self.RBCliente.grid(row = 5, column = 2, columnspan = 2, sticky = 'w')
        
        self.RBProducto = Radiobutton(self.page4, text = 'Producto',font =('Helvetica', 15), variable = self.ChkSe, value = 2)
        self.RBProducto.grid(row = 5, column = 4, columnspan = 2, sticky = 'w')
        
        self.RBBuscar = Radiobutton(self.page4, text = 'Buscar por pedido',font =('Helvetica', 15), variable = self.ChkSe, value = 3)
        self.RBBuscar.grid(row = 5, column = 6, columnspan = 3, sticky = 'w')
        
        self.CBdata2 = Text(self.page4, state="disabled", width=40, height=1, font=("Helvetica",15))
        self.CBdata2.grid(row = 6, column = 0, columnspan = 12)
                
        self.clienteL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Cliente:')
        self.clienteL.grid(row = 7, column = 0, columnspan = 11, sticky = 'w')
        
        self.ProductoL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Producto:')
        self.ProductoL.grid(row = 8, column = 0, columnspan = 11, sticky = 'w')
        
        # AGREGAMOS CONTENIDO A PAGE 5
        Label(self.page5, 
              font =('Helvetica', 15), 
              text = '*                                                                                                                                                *').grid(row = 0,
#              text = '123456789_123456789_123456789_123465789_123456789_123456789_123456789_123456789_12',
              #text = '____________________________').grid(row = 0,
                                                                     column = 0,
                                                                     columnspan = 3)
        Label(self.page5, 
              font =('Helvetica', 15),
              text = '_________________________________________').grid(row = 0,
                                                                     column = 0,)
        
        Label(self.page5, 
              font =('Helvetica', 15),
              text = '_________________________________________').grid(row = 0,
                                                                     column = 1)
#        Label(self.page5, 
#              font =('Helvetica', 15),
#              text = '___________________________').grid(row = 0,
#                                                                     column = 2)
        Label(self.page5, 
              font =('Helvetica', 15), 
              text = 'Verifique los datos ingresado:').grid(row = 0,
                                                                     column = 0,
                                                                     columnspan = 2)
        self.StxtCliente = StringVar(value = '*')
        self.txtCliente = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Cliente:')
        self.txtCliente.grid(row = 1, column = 0, sticky = 'w')
        self.txtClienteL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtCliente)
        self.txtClienteL.place(x = 79, y = 28)
        
        self.StxtProducto = StringVar(value = '*')
        self.txtProducto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Producto: ')
        self.txtProducto.grid(row = 2, column = 0, columnspan = 2, sticky = "w")
        self.txtProductoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtProducto)
        self.txtProductoL.place(x = 99, y = 56)
        
        self.StxtLargo = StringVar(value = '*')
        self.txtLargo = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Largo:')
        self.txtLargo.grid(row = 3, column = 0, sticky = "w")
        self.txtLargoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtLargo)
        self.txtLargoL.place(x= 69, y = 84)
        
        self.StxtAlto = StringVar(value = '*')
        self.txtAlto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Alto:')
        self.txtAlto.place(x = 310, y = 84)
        self.txtAltoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAlto)
        self.txtAltoL.place(x = 363, y = 84)
        
        self.StxtAncho = StringVar(value = '*')
        self.txtAncho = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Ancho: ')
        self.txtAncho.place(x= 590, y = 84)
        self.txtAnchoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAncho)
        self.txtAnchoL.place(x= 666, y = 84)
        
        self.StxtStlCj = StringVar(value = '*')
        self.txtStlCj = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Estilo caja:')
        self.txtStlCj.grid(row = 4, column = 0, sticky = "w")
        self.txtStlCjL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtStlCj)
        self.txtStlCjL.place(x= 110, y = 112)
        
        self.StxtTpFlt = StringVar(value = '*')
        self.txtTpFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de flauta:')
        self.txtTpFlt.grid(row = 4, column = 1, sticky = "w")
        self.txtTpFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpFlt)
        self.txtTpFltL.place(x= 594, y = 112)
        
        self.StxtDrccnFlt = StringVar(value = '*')
        self.txtDrccnFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Dirección de la flauta: ')
        self.txtDrccnFlt.grid(row = 5, column = 0, sticky = "w")
        self.txtDrccnFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtDrccnFlt)
        self.txtDrccnFltL.place(x= 216, y = 140)
        
        self.StxtGrdMtrl = StringVar(value = '*')
        self.txtGrdMtrl = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Grado del material: ')
        self.txtGrdMtrl.grid(row = 5, column = 1, sticky = "w")
        self.txtGrdMtrlL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtGrdMtrl)
        self.txtGrdMtrlL.place(x= 640, y = 140)
        
        
        self.StxtTpUnn = StringVar(value = '*')
        self.txtTpUnn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de unión: ')
        self.txtTpUnn.grid(row = 6, column = 0, sticky = "w")
        self.txtTpUnnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpUnn)
        self.txtTpUnnL.place(x= 138, y = 168)
        
        self.StxtMtdCrr = StringVar(value = '*')
        self.txtMtdCrr = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Método de cierre: ')
        self.txtMtdCrr.grid(row = 6, column = 1, sticky = "w")
        self.txtMtdCrrL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtMtdCrr)
        self.txtMtdCrrL.place(x= 623, y = 168)
        
        self.StxtOrntcn = StringVar(value = '*')
        self.txtOrntcn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Orientación de la prueba: ')
        self.txtOrntcn.grid(row = 7, column = 0, sticky = "w")
        self.txtOrntcnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtOrntcn)
        self.txtOrntcnL.place(x= 243, y = 197)
        
        cc = Button(self.page5, font = ('Helvetica', 15, "bold"), text = 'Cerrar', bg = "red", command = self.cerrarB)#.place(x = 20, y = 20)
        cc.grid(row = 8, column = 0, columnspan = 2)
        
        # OBTENER LO QUE CONTIENEN CADA LISTA
        self.listCaja.bind("<<ComboboxSelected>>", self.getList)
        self.listCierre.bind("<<ComboboxSelected>>", self.getList)
        self.listFlauta.bind("<<ComboboxSelected>>", self.getList)
        self.listFlautaD.bind("<<ComboboxSelected>>", self.getList)
        self.listGradoM.bind("<<ComboboxSelected>>", self.getList)
        self.listOrientaC.bind("<<ComboboxSelected>>", self.getList)
        self.listUnion.bind("<<ComboboxSelected>>", self.getList)
        
        self.top.protocol("WM_DELETE_WINDOW", self.cerrar)
        
    def motion(self, event):
        self.posy.set(event.y)
        self.posx.set(event.x)
        
    def selectCB(self,selecc):
        if selecc == 'al':
            self.LB['text'] = 'Usted selecciono alto'
            self.cajaLB['image'] = self.IMGalto
            self.bandDATA = 0
        elif selecc == 'an':
            self.LB['text'] = 'Usted selecciono ancho'
            self.cajaLB['image'] = self.IMGancho
            self.bandDATA = 1
        elif selecc == 'la':
            self.LB['text'] = 'Usted selecciono largo'
            self.cajaLB['image'] = self.IMGlargo
            self.bandDATA = 2
        
    def crearBoton(self, valor, escribir=True, ancho=5, alto=1):
        return Button(self.page1, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.click(valor,escribir))
        
    def crearBotonP4(self, valor, escribir=True, ancho=5, alto=1):
        return Button(self.page4, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.clickP4(valor,escribir))
        
    def conteo(self):
        self.botonClics += 1
        self.btnCLK['text'] = 'Clics totales = ' + str(self.botonClics)
        
        
    def click(self, texto, escribir):
        if not escribir:
            if texto==u"\u21B5" and self.operacion!="" and self.bandDATA != 3:
                if self.bandDATA == 0:
                    try:
                        self.alturaDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.alturaDATA) + 'cm en altura'
                        self.altoL['text'] = str(self.alturaDATA) + 'cm'
                        self.StxtAlto.set(str(self.alturaDATA) + 'cm')
                        self.changeTXT(self.StxtAlto, str(self.alturaDATA) + 'cm', self.txtAlto, 'Alto:')
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                        
                elif self.bandDATA == 1:
                    try:
                        self.anchoDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.anchoDATA) + 'cm en ancho'
                        self.changeTXT(self.StxtAncho, str(self.anchoDATA) + 'cm', self.txtAncho, 'Ancho:')
                        self.anchoL['text'] = str(self.anchoDATA) + 'cm'
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                elif self.bandDATA == 2:
                    try:
                        self.largoDATA = float(self.operacion)
                        self.LB['text'] = 'Usted ingreso ' + str(self.largoDATA ) + 'cm en largo'
                        self.changeTXT(self.StxtLargo, str(self.largoDATA ) + 'cm', self.txtLargo, 'Largo:')
                        self.largoL['text'] = str(self.largoDATA ) + 'cm'
                    except ValueError:
                        self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar'
                print 'Hola desde borrar'
                self.operacion = ''
                self.limpiarPantalla()
            elif texto==u"\u232B":
                self.operacion=""
                self.limpiarPantalla()
        #Mostrar texto
        else:
            self.operacion+=str(texto)
            self.mostrarEnPantalla(texto)
        return
    
    def clickP4(self, texto, escribir):
        self.ChkSel = int(self.ChkSe.get())
        print self.ChkSel
        if not escribir:
            if texto==u"\u21B5" and self.operacion!="" and self.ChkSel != 0:
                print 'gg'
                if self.ChkSel == 1:
                    self.cliente = self.operacion
                    self.clienteL['text'] = 'Cliente: ' + str(self.cliente)
                    self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:')
                elif self.ChkSel == 2:
                    self.Producto = self.operacion
                    self.ProductoL['text'] = 'Producto: ' + str(self.Producto)
                    self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:')
                elif self.ChkSel == 3:
                    self.top.iconify()
                    self.consoleSQL.consulta('pedido', str(self.operacion))
                    try:
                        self.cliente = self.consoleSQL.cliente
                        self.clienteL['text'] = 'Cliente: ' + str(self.cliente)
                        self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:')
                        self.Producto = self.consoleSQL.producto
                        self.ProductoL['text'] = 'Producto: ' + str(self.Producto)
                        self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:')
                    except:
                        tkMessageBox.showerror('Atención','No se encontró el pedido favor de verificar')
                self.operacion = ''
                self.limpiarPantalla(2)
            elif texto==u"\u232B":
                self.operacion=""
                self.limpiarPantalla(2)
            elif self.ChkSel == 0:
                self.top.iconify()
                tkMessageBox.showerror("Atención", 'Debe seleccionar una opción')
        #Mostrar texto
        else:
            self.operacion+=str(texto)
            self.mostrarEnPantalla(texto, 2)
        self.top.deiconify()
        return
    
    def changeTXT(self, StringVarTXT, setStr, LabelTXT, txtLabel):
        StringVarTXT.set(setStr)
        LabelTXT['text'] = txtLabel
        LabelTXT['font'] = ('Helvetica', 15, "bold")
        
    def limpiarPantalla(self, cb = 1):
        if cb ==2:
            self.CBdata2.configure(state="normal")
            self.CBdata2.delete("1.0", END)
            self.CBdata2.configure(state="disabled")
        else:
            self.CBdata.configure(state="normal")
            self.CBdata.delete("1.0", END)
            self.CBdata.configure(state="disabled")
        return
    

    def mostrarEnPantalla(self, valor, cb = 1):
        if cb == 2:
            self.CBdata2.configure(state="normal")
            self.CBdata2.insert(END, valor)
            self.CBdata2.configure(state="disabled")
        else:
            self.CBdata.configure(state="normal")
            self.CBdata.insert(END, valor)
            self.CBdata.configure(state="disabled")
        return
    
    def getList(self, event):
        self.CheckList(self.listCaja, 0, self.StxtStlCj, 'Estilo caja: ', self.txtStlCj)
        self.CheckList(self.listFlauta, 1, self.StxtTpFlt, 'Tipo de flauta: ', self.txtTpFlt)
        self.CheckList(self.listFlautaD, 2, self.StxtDrccnFlt, 'Dirección de  la flauta: ', self.txtDrccnFlt)
        self.CheckList(self.listGradoM, 3, self.StxtGrdMtrl, 'Grado del material: ', self.txtGrdMtrl)
        self.CheckList(self.listUnion, 4, self.StxtTpUnn, 'Tipo de unión: ', self.txtTpUnn)
        self.CheckList(self.listCierre, 5, self.StxtMtdCrr, 'Método de cierre: ', self.txtMtdCrr)
        self.CheckList(self.listOrientaC, 6, self.StxtOrntcn, 'Orientación de la prueba: ', self.txtOrntcn)
        #hola
        
    def CheckList(self, lista, num_list, StrVarL, txt, labelTXT,):
        gg = lista.get()
        print gg
        if gg != '':
            self.Datos[num_list] = lista.get()
            if num_list == 0:
                if self.Datos[0] == (u'Caja est\xe1ndar'):
                    self.Datos[0] = str('Caja estándar')
            elif num_list == 4:
                if self.Datos[4] == (u'Armado autom\xe1tico'):
                    self.Datos[4] = ('Armado automático')
            StrVarL.set(self.Datos[num_list])
            labelTXT['text'] = txt
            labelTXT['font'] = ('Helvetica', 15, "bold")
            
        
    def cerrar(self):
        self.top.iconify()
        tkMessageBox.showinfo("Atención", "Si desea salir, debe hacerlo desde el botón ubicado en la pestaña de Resumen de datos.")
        self.top.deiconify()
        
    def cerrarB(self):
        self.top.iconify()
        respuesta=tkMessageBox.askyesno("Atención", "Usted esta a punto de salir, ¿Los datos ingresados son los correctos?")
        if respuesta==True:
            self.top.destroy()
        try:
            self.top.deiconify()
        except:
            print "Ventana cerrada"
            
#ventana = Tk()
#final = DATAin(ventana)
#ventana.mainloop()
예제 #23
0
class PAGUI(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Parameter Analyzer Control")
        self.style = Style()
        self.style.theme_use("clam")
        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)

        #set up instance variables
        self.directory = StringVar()
        self.fname = StringVar()
        self.fname_final=StringVar()
        self.device = StringVar()
        self.chip = StringVar()
        self.run = StringVar()


        self.toplabel = Label(self, text="Dummy label at the top of the widget",justify="center")
        self.bottomlabel = Label(self, text="for help/info see github.com/leobrowning92/pa-control",justify="center",font="arial 11 italic")


        self.directory_btn = Button(self, text="Directory", command=self.askdirectory)

        self.filename_btn = Button(self, text="Filename", command=self.askfile)

        # self.exit_btn = Button(self, text="Exit", command=self.quit)
        # self.exit_btn.grid(row=5, column=0, padx=5)

        self.update_btn = Button(self, text="Update", command=self.runUpdate)

        self.iterdevice_btn = Button(self, text="Iterate [device]", command=self.newDevice)

        self.iterchip_btn = Button(self, text="Iterate [chip]", command=self.newChip)
        self.iterrun_btn = Button(self, text="Iterate [run]", command=self.newRun)

        self.chip.set("001")
        self.chipnum_entry = Entry(self, textvariable=self.chip,width=5)

        self.device.set("01")
        self.devicenum_entry = Entry(self, textvariable=self.device,width=5)

        self.run.set("001")
        self.runnum_entry = Entry(self, textvariable=self.run,width=5)

        self.directory_entry = Entry(self, textvariable=self.directory)

        self.fname.set('Chip[chip]_[device]_run[run]_somenotes_[INFO]_[time].csv')
        self.fname_final.set(make_fname_final(self.fname.get(),
                            self.chip.get(),self.device.get(),self.run.get()))

        self.fname_entry = Entry(self, textvariable=self.fname)

        self.fname_final_label = Label(self, textvariable=self.fname_final,
                          justify="center", font="arial 11 italic")


        # this button runs pulldata with parameter set by
        # self.datatype, which stores the value of self.radbtn
        self.pulldata_btn = Button(self, text="Pull Data", command=self.pulldata)

        self.datarun_btn = Button(self, text="Run Data sweep", command=self.datarun)


        #datatype=1 => diode, datatype=2 => FET
        self.datatype = IntVar()
        self.datatype1_radiobutton = Radiobutton(
            self, text='Diode (VF, IF)',
            variable=self.datatype, value=1)
        self.datatype2_radiobutton = Radiobutton(
            self, text='FET (VG, VDS, ID, IG)',
            variable=self.datatype, value=2)

        #grid alignments of all widgets
        self.toplabel.grid(column=0,columnspan=3, sticky=W, pady=4, padx=5)

        self.directory_btn.grid(row=1, column=0)
        self.directory_entry.grid(row=1, column=1, columnspan=2,
                         padx=5, sticky=E + W)

        self.filename_btn.grid(row=2, column=0)
        self.fname_entry.grid(row=2, column=1, columnspan=2,
                         padx=5, sticky=E + W)
        self.fname_final_label.grid(row=3,column=1,  columnspan=2,
                       sticky=N + E + W, pady=4, padx=5)

        self.iterchip_btn.grid(row=4, column=0, sticky=N)
        self.chipnum_entry.grid(row=4, column=1,padx=5, sticky=W)

        self.iterdevice_btn.grid(row=5, column=0, sticky=N)
        self.devicenum_entry.grid(row=5, column=1,padx=5, sticky=W)

        self.iterrun_btn.grid(row=6, column=0, sticky=N)
        self.runnum_entry.grid(row=6, column=1,padx=5, sticky=W)

        self.update_btn.grid(row=7, column=0, padx=5)
        self.pulldata_btn.grid(row=7, column=3, padx=5,sticky=E)
        self.datarun_btn.grid(row=6, column=3, padx=5,sticky=E)

        self.datatype1_radiobutton.grid(row=7,column=1,padx=5,sticky=N + E + S)
        self.datatype2_radiobutton.grid(row=7,column=2,padx=5,sticky=N + W + S)
        self.bottomlabel.grid(row=8,column=0,columnspan=3, sticky=W, pady=4, padx=5)


#action funcctions for the various buttons
    def newChip(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.chip.set(str((int(self.chip.get())+1)).zfill(3))
                self.device.set(str(1).zfill(2))
            except Exception as e:
                print(e)
            self.runUpdate()
    def newRun(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.run.set(str((int(self.run.get())+1)).zfill(3))
            except Exception as e:
                print(e)
            self.runUpdate()



    def newDevice(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.device.set(str((int(self.device.get())+1)).zfill(2))
            except Exception as e:
                print(e)
            self.runUpdate()

    def runUpdate(self):
        self.fname_final.set(make_fname_final(self.fname.get(),
                            self.chip.get(),self.device.get(),self.run.get()))


    def askdirectory(self):
        """Returns a selected directoryname."""
        self.directory.set( tkFileDialog.askdirectory())

    def askfile(self):
        fullpath = tkFileDialog.askopenfilename()
        if "/" in fullpath:
            i = fullpath.rfind("/")
        if "\\" in fullpath:
            i = fullpath.rfind("\\")
        # self.fname_final.set(fullpath[i + 1:])
        self.fname.set(fullpath[i + 1:])

    def pulldata(self):
        self.runUpdate()
        if self.datatype.get() == 1:
            download_data(['VF', 'IF'], self.fname_final.get(), self.directory.get())
        elif self.datatype.get() == 2:
            download_data(['VG', 'VDS', 'ID', 'IG'], self.fname_final.get(), self.directory.get())
    def datarun(self):
        self.runUpdate()
        if self.datatype.get() ==1:
            print("oh no we havent written a script for that yet!")
        elif self.datatype.get() == 2:
            run_FET_series(self.fname_final.get(),self.directory.get())
예제 #24
0
p_label = Label(root, text=names[3])
p_value = IntVar(); p_value.set(p_default)
p_entry = Entry(root, textvariable=p_value)
fbL_label = Label(root, text=names[4])
fbL_value = DoubleVar(); fbL_value.set(fbL_default)
fbL_entry = Entry(root, textvariable=fbL_value)
fbH_label = Label(root, text=names[5])
fbH_value = DoubleVar(); fbH_value.set(fbH_default)
fbH_entry = Entry(root, textvariable=fbH_value)
binchoice_label = Label(root, text=names[6])
binchoice_frame = Frame(root)
binchoice_value = StringVar()
equal = Radiobutton(binchoice_frame,text='equal',variable=binchoice_value,value='equal',command=check_binchoice)
equal.select()
adaptive = Radiobutton(binchoice_frame,text='adaptive',variable=binchoice_value,value='adaptive',command=check_binchoice)
equal.grid(row=0,column=0)
adaptive.grid(row=0,column=1)
binchoice_frame.grid()
fitType_label = Label(root, text=names[7])
fitType_frame = Frame(root)
fitType_value = StringVar()
linear = Radiobutton(fitType_frame,text='linear',variable=fitType_value,value='linear')
cubic = Radiobutton(fitType_frame,text='cubic',variable=fitType_value,value='cubic')
cubic.select()
linear.grid(row=0,column=0)
cubic.grid(row=0,column=1)
fitType_frame.grid()
fQ_label = Label(root, text=names[8])
fQ_value = DoubleVar(); fQ_value.set(fQ_default)
fQ_entry = Entry(root, textvariable=fQ_value)
niter_label = Label(root, text=names[9])
예제 #25
0
    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()
예제 #26
0
class PaymentWindow(Frame):

	def __init__(self,parent,graphics):
		Frame.__init__(self)
		self.parent = parent
		self.graphics = graphics
		self.config(bg=self.graphics.mainColor)
		self.selected = ""
		self.font = tkFont.Font(family="Courier", size=12)
		#self.color = '#FFFFFF'

		#Title Label
		self.outputLabel = Label(self, text="", bg=self.graphics.mainColor)
		self.outputLabel.grid(row=0,column=0,sticky='ns',padx=6,pady=5)

		v = IntVar()

		self.b1 = Radiobutton(self, text="Cash", variable=v, value=1, bg=self.graphics.mainColor, command=lambda: self.cash())
		self.b1.grid(row=1,column=0)
		self.b2 = Radiobutton(self, text="Credit", variable=v, value=2, bg=self.graphics.mainColor, command=lambda: self.credit())
		self.b2.grid(row=1,column=1)

		#Title Label
		self.creditCardNumberLabel = Label(self, text="Credit Card Number", bg=self.graphics.mainColor)
		self.creditCardNumberLabel.grid(row=2,column=0,sticky='ns',padx=6,pady=5)

		#Manual Enter Output
		self.creditCardNumber = Entry(self,width=20)
		self.creditCardNumber.grid(row=2,column=1,sticky='ns',padx=6)

		#Title Label
		self.nameLabel = Label(self, text="Enter Name", bg=self.graphics.mainColor)
		self.nameLabel.grid(row=3,column=0,sticky='ns',padx=6,pady=5)

		#Manual Enter Output
		self.name = Entry(self,width=20)
		self.name.grid(row=3,column=1,sticky='ns',padx=6)

		self.submitButton = Button(self, text="Submit", width=15, command=lambda: self.submit())
		self.submitButton.grid(row=4,column=0)

		self.cancelButton = Button(self, text="Cancel", width=15, command=lambda: self.cancel())
		self.cancelButton.grid(row=4,column=1)
	

#		Style().configure('green/black.TButton', foreground='black', background='black')
#		
#		self.L1 = Entry(self,state = DISABLED, disabledforeground = parent.cget('bg'))
#		self.L1.pack()#

#		self.B1 = Button(self, text = "Are You Alive???", command = self.hello)
#		self.B1.pack()#

#		self.B2 = Button(self, text = "DISSAPEAR???", command = self.goodbye)
#		self.B2.pack()
	
	def cancel(self):
		self.graphics.liftLayer("transaction")

	def submit(self):
		self.creditCardNumber.config(text="f")
		self.name.config(text="f")
		if self.selected == "credit":
			number = self.creditCardNumber.get()
			name = self.name.get()
			payment = Payment(self.selected,number)
		else:
			payment = Payment(self.selected)

		self.graphics.POS.getCurrentTransaction().setPayment(payment)
		self.complete()


	def credit(self):
		print "credit"
		self.selected = "credit"
		self.creditCardNumberLabel.config(state="active", bg=self.graphics.mainColor)
		self.creditCardNumber.config(state="active")
		self.nameLabel.config(state="active", bg=self.graphics.mainColor)
		self.name.config(state="active")

	def cash(self):
		print "cash"
		self.selected = "cash"
		self.creditCardNumberLabel.config(state="disabled", bg=self.graphics.mainColor)
		self.creditCardNumber.config(state="disabled")
		self.nameLabel.config(state="disabled", bg=self.graphics.mainColor)
		self.name.config(state="disabled")	

	def complete(self):
		self.creditCardNumber.config(text="")
		self.name.config(text="")
		self.outputLabel.config(text=" ")
		
		print "completing transaction"

		#color = "#D1D1D1"
		color = "#e8e8e8"
		width=35

		# Create progress bar pop-up window
		receiptWindow = Toplevel(self)
		receiptWindow.configure(bg=color)
		#Should be 7.35 x width
		receiptWindow.geometry("500"+"x"+str(int(13.05*(len(self.graphics.POS.getTransactionReceipt().split('\n'))+5)+100))+"+150+50")

		# Text Field Object, used in the submission function
		receiptText = Label(receiptWindow, text=self.graphics.POS.getTransactionReceipt(), bg='white', font=self.font)#self.graphics.POS.getTransactionReceipt()
		self.graphics.POS.completeStuff()
		receiptText.pack(side="top")
		#self.itemIDField.delete(0, 'end')
		self.graphics.liftLayer("main")
예제 #27
0
class SkyglowEstimationToolbox:
    """Main class that establishes GUI."""
    def __init__(self, root):
        self.root = root

        # Radio action buttons
        self.action = None
        self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None

        self.file_log_var = StringVar()
        self.csv_file_var = StringVar()
        self.krn_folder_var = StringVar()
        self.output_folder_var = StringVar()
        self.sgmap_folder_var = StringVar()

        self.krn_ent_var = StringVar()
        self.krn_var, self.hem_var = IntVar(), IntVar()
        self.img, self.cdiag = None, None
        self.lat_lbl, self.lat_entry = None, None
        self.k_lbl, self.k_entry = None, None
        self.zen_lbl, self.zen_entry = None, None
        self.azi_lbl, self.azi_entry = None, None
        self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None
        self.txt_redir, self.prg_log = None, None
        self.map_btn, self.gen_krn_btn = None, None

        # Sets window title, size, and icon on screen.
        self.root.title("Skyglow Estimation Toolbox (SET)")
        self.root.geometry('%dx%d+%d+%d' %
                           (constants.SW * 0.75, constants.SH * 0.75, 25, 25))
        self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO))
        self.root.resizable(False, False)
        self.root.update_idletasks()

        # Creates three paned windows for the main screen.
        base = PanedWindow()
        base.pack(fill=BOTH, expand=1)
        sub1 = PanedWindow(base,
                           orient=VERTICAL,
                           height=self.root.winfo_height() * 3 / 4)
        base.add(sub1)
        sub2 = PanedWindow(sub1,
                           orient=HORIZONTAL,
                           height=self.root.winfo_height() / 5)
        sub1.add(sub2)

        # Creates frame for holding inputs.
        self.input_frame = Frame(sub2)
        sub2.add(self.input_frame)

        # Creates frame for bottom half of main screen.
        self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken")
        sub1.add(self.img_frame)

        # Creates canvas for displaying images.
        self.img_canvas = Canvas(self.img_frame,
                                 bd=2,
                                 relief="groove",
                                 width=constants.SW * 0.6,
                                 height=self.root.winfo_height() * 3 / 4 * 0.9)
        self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER)

        # Creates help button for link to documentation, instructions, and about.
        self.help_btn = Menubutton(self.input_frame,
                                   text="Help",
                                   relief="raised",
                                   bd=2,
                                   width=8,
                                   pady=1)
        #self.help_btn.place(relx=1, rely=0, anchor=NE)
        self.help_btn.grid(column=4, columnspan=1, row=0)
        self.help_btn_menu = Menu(self.help_btn, tearoff=0)
        doc = 'https://github.com/NASA-DEVELOP'
        self.help_btn_menu.add_command(label="Documentation",
                                       command=lambda: self.open_url(doc))
        self.help_btn_menu.add_command(label="Instructions",
                                       command=self.instructions)
        self.help_btn_menu.add_separator()
        self.help_btn_menu.add_command(label="About", command=self.about)
        self.help_btn["menu"] = self.help_btn_menu

    def main_screen(self):
        """Set up input GUI and image display screen."""
        self.action = IntVar()

        btn_width = int(constants.SW / 60)
        file_width = int(constants.SW / 18)
        lbl_width = int(constants.SW / 60)
        gen_width = int(constants.SW / 42)
        radio_font = Font(family='TkDefaultFont', size=12)
        self.sgmap_single_btn = Radiobutton(
            self.input_frame,
            text="Generate Artificial Skyglow Map",
            font=radio_font,
            width=btn_width,
            variable=self.action,
            value='sng',
            command=self.sng_popup)
        self.krn_lib_btn = Radiobutton(self.input_frame,
                                       text="Generate Kernel Library",
                                       font=radio_font,
                                       width=btn_width,
                                       variable=self.action,
                                       value='krn',
                                       command=self.krn_popup)
        self.multi_map_btn = Radiobutton(
            self.input_frame,
            text="Generate Maps from Multiple Kernels",
            font=radio_font,
            width=btn_width,
            variable=self.action,
            value='mul',
            command=self.mul_popup)
        self.hem_map_btn = Radiobutton(
            self.input_frame,
            text="Generate Hemispherical Visualization",
            font=radio_font,
            width=btn_width,
            variable=self.action,
            value='hem',
            command=self.hem_popup)
        #Place widget
        self.sgmap_single_btn.grid(column=0, columnspan=1, row=0)
        self.krn_lib_btn.grid(column=1, columnspan=1, row=0)
        self.multi_map_btn.grid(column=2, columnspan=1, row=0)
        self.hem_map_btn.grid(column=3, columnspan=1, row=0)

        # VIIRS Image Reference File
        self.file_lbl = Label(self.input_frame,
                              text="Image File:",
                              width=lbl_width,
                              anchor=E)
        self.file_log = Entry(self.input_frame,
                              width=file_width,
                              bd=2,
                              relief="sunken",
                              textvariable=self.file_log_var)
        self.browse_btn = Button(self.input_frame,
                                 text="Browse",
                                 command=self.import_viirs)

        # Angles CSV File
        self.csv_file_lbl = Label(self.input_frame,
                                  text="Angles CSV File:",
                                  width=lbl_width,
                                  anchor=E)
        self.csv_file_log = Entry(self.input_frame,
                                  width=file_width,
                                  bd=2,
                                  relief="sunken",
                                  textvariable=self.csv_file_var)
        self.csv_browse_btn = Button(self.input_frame,
                                     text="Browse",
                                     command=self.import_csv)

        # Multiple Maps form Kernel library
        self.mul_file_lbl = Label(self.input_frame,
                                  text="Kernel Folder:",
                                  width=lbl_width,
                                  anchor=E)
        self.mul_file_log = Entry(self.input_frame,
                                  width=file_width,
                                  bd=2,
                                  relief="sunken",
                                  textvariable=self.krn_folder_var)
        self.mul_browse_btn = Button(self.input_frame,
                                     text="Browse",
                                     command=self.import_krn_folder)

        # MultiKrn Map Output Location
        self.output_lbl = Label(self.input_frame,
                                text="Output Location:",
                                width=lbl_width,
                                anchor=E)
        self.output_log = Entry(self.input_frame,
                                width=file_width,
                                bd=2,
                                relief="sunken",
                                textvariable=self.output_folder_var)
        self.output_btn = Button(self.input_frame,
                                 text="Browse",
                                 command=self.import_out_folder)

        # Hemisphere Output Location
        self.sgmap_folder_lbl = Label(self.input_frame,
                                      text="Skyglow Map Location:",
                                      width=lbl_width,
                                      anchor=E)
        self.sgmap_folder_log = Entry(self.input_frame,
                                      width=file_width,
                                      bd=2,
                                      relief="sunken",
                                      textvariable=self.sgmap_folder_var)
        self.sgmap_folder_btn = Button(self.input_frame,
                                       text="Browse",
                                       command=self.import_sgmap_folder)

        # Import Kernel Checkbutton
        self.check_lbl = Label(self.input_frame,
                               text="Import Kernel:",
                               width=lbl_width,
                               anchor=E)

        self.krn_chk = Checkbutton(self.input_frame,
                                   anchor=W,
                                   variable=self.krn_var,
                                   command=self.checkbtn_val)

        self.hem_chk_lbl = Label(self.input_frame,
                                 text="Generate kernels for hemisphere:",
                                 width=lbl_width,
                                 anchor=E)

        self.hem_chk = Checkbutton(self.input_frame,
                                   anchor=W,
                                   variable=self.hem_var)

        # Region Latitude (deg), Grand Teton National park = 43.7904 degrees N
        self.lat_lbl = Label(self.input_frame,
                             text="Latitude (deg):",
                             width=lbl_width,
                             anchor=E)
        self.lat_entry = Entry(self.input_frame,
                               width=btn_width,
                               bd=2,
                               relief="sunken")
        self.lon_lbl = Label(self.input_frame,
                             text="Longitude (deg):",
                             width=lbl_width,
                             anchor=E)
        self.lon_entry = Entry(self.input_frame,
                               width=btn_width,
                               bd=2,
                               relief="sunken")

        # Atmospheric Clarity Parameter, REF 2, Eq. 12, p. 645
        self.k_lbl = Label(self.input_frame,
                           text="Atmospheric Clarity Parameter:",
                           width=btn_width,
                           anchor=E)
        self.k_entry = Entry(self.input_frame,
                             width=btn_width,
                             bd=2,
                             relief="sunken")

        # Zenith angle (deg), z, REF 2, Fig. 6, p.648
        self.zen_lbl = Label(self.input_frame,
                             text="Zenith Angle (deg):",
                             width=lbl_width,
                             anchor=E)
        self.zen_entry = Entry(self.input_frame,
                               width=btn_width,
                               bd=2,
                               relief="sunken")

        # Azimuth angle (deg)
        self.azi_lbl = Label(self.input_frame,
                             text="Azimuth Angle (deg):",
                             width=lbl_width,
                             anchor=E)
        self.azi_entry = Entry(self.input_frame,
                               width=btn_width,
                               bd=2,
                               relief="sunken")

        self.krn_lbl = Label(self.input_frame,
                             text="Kernel File:",
                             width=lbl_width,
                             anchor=E)
        self.krn_ent = Entry(self.input_frame,
                             width=file_width,
                             bd=2,
                             relief="sunken",
                             textvariable=self.krn_ent_var)
        self.krn_btn = Button(self.input_frame,
                              text="Browse",
                              command=self.import_krn)

        # Generate Artificial Skyglow Map Button
        self.map_btn = Button(self.input_frame,
                              text="Generate Artificial Skyglow Map",
                              width=gen_width,
                              command=self.generate_map)
        # Generate Kernal library button for SET
        self.gen_krn_btn = Button(self.input_frame,
                                  text="Generate Kernel Library",
                                  width=gen_width,
                                  command=self.generate_krn)
        # Generate Map of Multiple Kernals(word better later on)
        self.mul_map_btn = Button(self.input_frame,
                                  text="Generate Maps from Multiple Kernels",
                                  width=gen_width,
                                  command=self.generate_mmap)
        # Generate Hemispherical Visualization Display of Skyglow
        self.hem_gen_btn = Button(self.input_frame,
                                  text="Generate Hemisphere",
                                  width=gen_width,
                                  command=self.generate_hem)

    def import_viirs(self):
        """Import a VIIRS DNB file."""
        # Allows user to search through his directory for VIIRS Image file.
        file_types = [('TIFF Files', '*.tif'), ('All files', '*')]
        file_name = filedialog.askopenfilename(initialdir='/',
                                               title="Select file",
                                               filetypes=file_types)
        self.file_log_var.set(file_name)

        # Checks to see if file is empty. If not, displays image on canvas.
        if file_name != '':
            pilimg = Image.open(file_name)
            pilimg_width, pilimg_height = pilimg.size
            pilimg.tile = [
                t for t in pilimg.tile
                if t[1][2] < pilimg_width and t[1][3] < pilimg_height
            ]
            canvas_size = (self.img_canvas.winfo_width(),
                           self.img_canvas.winfo_height())
            pilimg_r = pilimg.resize(canvas_size, Image.ANTIALIAS)
            pilimg_col = ImageOps.colorize(ImageOps.grayscale(pilimg_r),
                                           (0, 0, 0), (255, 255, 255))
            pilimg_cont = ImageOps.autocontrast(pilimg_col,
                                                cutoff=.4,
                                                ignore=None)
            self.img = ImageTk.PhotoImage(pilimg_cont)
            self.img_canvas.create_image(canvas_size[0] / 2,
                                         canvas_size[1] / 2,
                                         image=self.img)
        else:
            print('File is empty.')

    def import_csv(self):
        """Import CSV file."""
        file_types = [('CSV Files', '*.csv'), ('All files', '*')]
        file_name = filedialog.askopenfilename(initialdir='/',
                                               title="Select file",
                                               filetypes=file_types)
        self.csv_file_var.set(file_name)

        if file_name is '':
            print('File is empty.')

    def import_krn_folder(self):
        """Import kernel folder."""
        krn_dir = filedialog.askdirectory(initialdir='/',
                                          title="Select kernel folder")
        self.krn_folder_var.set(krn_dir)

        if krn_dir is '':
            print('Directory is empty.')

    def import_out_folder(self):
        """Import skyglow output folder."""
        output_dir = filedialog.askdirectory(initialdir='/',
                                             title="Select output folder")
        self.output_folder_var.set(output_dir)

        if output_dir is '':
            print('Directory is empty.')

    def import_krn(self):
        """Import existing kernel tif."""
        file_types = [('TIFF Files', '*.tif'), ('All files', '*')]
        file_name = filedialog.askopenfilename(initialdir='/',
                                               title="Select file",
                                               filetypes=file_types)
        self.krn_ent_var.set(file_name)

    def import_sgmap_folder(self):
        """Import skyglow map folder for hemisphere building."""
        sgmap_dir = filedialog.askdirectory(initialdir='/',
                                            title="Select skyglow map folder")
        self.sgmap_folder_var.set(sgmap_dir)

        if sgmap_dir is '':
            print('Directory is empty.')

    def sng_popup(self):
        """Single map tab."""
        self.remove_all()

        self.check_lbl.grid(column=0, row=2)
        self.krn_chk.place(relx=.22, rely=.41, anchor=CENTER)

        self.file_lbl.grid(column=0, row=1)
        self.file_log.grid(column=1, columnspan=3, row=1)
        self.browse_btn.grid(column=4, row=1, sticky=W, padx=3)

        self.lat_lbl.grid(column=0, row=3)
        self.lat_entry.grid(column=1, row=3)

        self.k_lbl.grid(column=2, row=3)
        self.k_entry.grid(column=3, row=3)

        self.zen_lbl.grid(column=0, row=4)
        self.zen_entry.grid(column=1, row=4)

        self.azi_lbl.grid(column=2, row=4)
        self.azi_entry.grid(column=3, row=4)

        self.map_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W)

    def krn_popup(self):
        """Kernel lib tab."""
        self.remove_all()

        # latitude
        self.lat_lbl.grid(column=0, row=3)
        self.lat_entry.grid(column=1, row=3)

        # atmospheric clarity
        self.k_lbl.grid(column=2, row=3)
        self.k_entry.grid(column=3, row=3)

        # angles file
        self.csv_file_lbl.grid(column=0, row=1)
        self.csv_file_log.grid(column=1, columnspan=3, row=1)
        self.csv_browse_btn.grid(column=4, row=1, sticky=W, padx=3)

        # input VIIRS image
        self.file_lbl.grid(column=0, row=2)
        self.file_log.grid(column=1, columnspan=3, row=2)
        self.browse_btn.grid(column=4, row=2, sticky=W, padx=3)

        self.hem_chk_lbl.grid(column=0, row=4)
        self.hem_chk.place(relx=.21, rely=.69)

        self.gen_krn_btn.grid(column=1,
                              columnspan=3,
                              row=5,
                              sticky=N + S + E + W)

    def mul_popup(self):
        """Multiple maps tab."""
        self.remove_all()

        # Kernel folder location
        self.mul_file_lbl.grid(column=0, row=1)
        self.mul_file_log.grid(column=1, columnspan=3, row=1)
        self.mul_browse_btn.grid(column=4, row=1, sticky=W, padx=3)

        # input VIIRS image
        self.file_lbl.grid(column=0, row=2)
        self.file_log.grid(column=1, columnspan=3, row=2)
        self.browse_btn.grid(column=4, row=2, sticky=W, padx=3)

        # Choose output location
        self.output_lbl.grid(column=0, row=3)
        self.output_log.grid(column=1, columnspan=3, row=3)
        self.output_btn.grid(column=4, row=3, sticky=W, padx=3)

        # Generate map from kernel folder
        self.mul_map_btn.grid(column=1,
                              columnspan=3,
                              row=4,
                              sticky=N + S + E + W)

    def hem_popup(self):
        """Hemisphere tab."""
        self.remove_all()

        # Skyglow Map Folder
        self.sgmap_folder_lbl.grid(column=0, row=1)
        self.sgmap_folder_log.grid(column=1, columnspan=3, row=1)
        self.sgmap_folder_btn.grid(column=4, row=1, sticky=W, padx=3)

        # Latitude entry
        self.lat_lbl.grid(column=0, row=3)
        self.lat_entry.grid(column=1, row=3)

        # Longitude entry
        self.lon_lbl.grid(column=2, row=3)
        self.lon_entry.grid(column=3, row=3)

        # Generate Hemispherical Visualization button
        self.hem_gen_btn.grid(column=1,
                              columnspan=3,
                              row=4,
                              sticky=N + S + E + W)

    def remove_all(self):
        """Remove all existing GUI elements before opening new tab."""
        self.check_lbl.grid_remove()
        self.krn_chk.place_forget()
        self.hem_chk.place_forget()
        self.hem_chk_lbl.grid_remove()
        self.file_lbl.grid_remove()
        self.file_log.grid_remove()
        self.browse_btn.grid_remove()
        self.krn_lbl.grid_remove()
        self.krn_ent.grid_remove()
        self.krn_btn.grid_remove()
        self.lat_lbl.grid_remove()
        self.lat_entry.grid_remove()
        self.k_lbl.grid_remove()
        self.k_entry.grid_remove()
        self.zen_lbl.grid_remove()
        self.zen_entry.grid_remove()
        self.azi_lbl.grid_remove()
        self.azi_entry.grid_remove()
        self.map_btn.grid_remove()
        self.gen_krn_btn.grid_remove()
        self.mul_map_btn.grid_remove()
        self.csv_file_lbl.grid_remove()
        self.csv_file_log.grid_remove()
        self.csv_browse_btn.grid_remove()
        self.mul_file_lbl.grid_remove()
        self.mul_file_log.grid_remove()
        self.mul_browse_btn.grid_remove()
        self.output_lbl.grid_remove()
        self.output_log.grid_remove()
        self.output_btn.grid_remove()
        self.hem_gen_btn.grid_remove()
        self.lat_lbl.grid_remove()
        self.lat_entry.grid_remove()
        self.lon_lbl.grid_remove()
        self.lon_entry.grid_remove()
        self.sgmap_folder_lbl.grid_remove()
        self.sgmap_folder_log.grid_remove()
        self.sgmap_folder_btn.grid_remove()

    def checkbtn_val(self):
        """Change interface based on if Import Kernel button is checked."""
        # Import Kernel File widgets when Kernel Checkbutton is marked.
        if self.krn_var.get():
            self.lat_lbl.grid_remove()
            self.lat_entry.grid_remove()
            self.k_lbl.grid_remove()
            self.k_entry.grid_remove()
            self.zen_lbl.grid_remove()
            self.zen_entry.grid_remove()
            self.azi_lbl.grid_remove()
            self.azi_entry.grid_remove()
            self.krn_lbl.grid(column=0, row=2)
            self.krn_ent.grid(column=1, columnspan=3, row=2)
            self.krn_btn.grid(column=4, row=2, sticky=W, padx=3)
            self.krn_chk.place_forget()
            self.krn_chk.place(relx=0.19, rely=.5)
        # Input parameter widgets when Kernel Checkbuttton is unmarked
        else:
            self.krn_lbl.grid_remove()
            self.krn_ent.grid_remove()
            self.krn_btn.grid_remove()
            self.lat_lbl.grid(column=0, row=3)
            self.lat_entry.grid(column=1, row=3)
            self.k_lbl.grid(column=2, row=3)
            self.k_entry.grid(column=3, row=3)
            self.zen_lbl.grid(column=0, row=4)
            self.zen_entry.grid(column=1, row=4)
            self.azi_lbl.grid(column=2, row=4)
            self.azi_entry.grid(column=3, row=4)
            self.krn_chk.place_forget()
            self.krn_chk.place(relx=0.22, rely=.41, anchor=CENTER)

    @staticmethod
    def open_url(url):
        """"Open a url"""
        webbrowser.open_new(url)

    def instructions(self):
        """Open instructions window."""
        # Instantiates separate Toplevel instruction window.
        instr_window = Toplevel(self.root)
        instr_window.geometry('550x575+25+25')
        instr_window.title('Instructions')
        instr_window.wm_iconbitmap(constants.ICO)
        instr_window.resizable(False, False)

        # Creatse Scrollbar and Frame for containing other widgets.
        instr_scroll = Scrollbar(instr_window)
        instr_scroll.pack(fill=Y, side="right")
        instr_frame = Frame(instr_window, bg='white')
        instr_frame.pack(fill=BOTH, side="left")

        # Adds instruction text from constants and adds image of Cinzano's diagram.
        instr = Text(instr_frame,
                     width=65,
                     height=40,
                     padx=10,
                     pady=5,
                     bd=0,
                     wrap="word")
        instr.insert("end", constants.INSTR)
        cdiagram_file = Image.open("./static/cinzano_diagram.PNG")
        cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS)
        self.cdiag = ImageTk.PhotoImage(cdiagram_file)
        instr.image_create("end", image=self.cdiag)
        instr.tag_add("top", "1.0", "4.10")
        instr.tag_config("top", font='Times 12 bold')
        instr.tag_add("body", "5.0", "19.20")
        instr.tag_config("body", font='Times 12')
        instr.insert("end", constants.CDIAG)
        instr.pack()
        instr_scroll.config(command=instr.yview)

    def about(self):
        """Open an about window.

        Window gives authors, SET version number, and icon credit.
        """
        # Instantiates a new Toplevel about window.
        about_window = Toplevel(self.root)
        about_window.geometry('350x335+25+25')
        about_window.title('About')
        about_window.wm_iconbitmap(constants.ICO)
        about_window.resizable(False, False)

        # Adds text to about window.
        about = Text(about_window, width=50, height=30, padx=10, pady=3)
        about.insert("end", constants.ABOUT)
        about.tag_add("abt", "1.0", "21.30")
        about.tag_config("abt", font='Times 10 bold', justify=CENTER)
        about.pack()

    def progress(self):
        """Construct a progress window to monitor darksky."""
        # Instantiates a new Toplevel window and frame for progress bar and loading log.
        self.prg_window = Toplevel(self.root)
        self.prg_window.geometry('650x325+250+250')
        self.prg_window.title('Generating Artificial Skyglow Map...')
        self.prg_window.iconbitmap(constants.ICO)
        self.prg_window.resizable(False, False)
        prg_frame = Frame(self.prg_window)
        prg_frame.pack(fill=BOTH)

        # Creates Scrollbar, Progressbar, and Label for checking progress..
        prg_scroll = Scrollbar(prg_frame)
        prg_scroll.pack(fill=Y, side="right")
        self.prg_bar = ttk.Progressbar(prg_frame,
                                       orient=HORIZONTAL,
                                       length=750,
                                       mode='indeterminate')
        self.prg_bar.pack()
        self.prg_bar.start()
        prg_lbl_txt = StringVar()
        prg_lbl = Label(prg_frame, textvariable=prg_lbl_txt)
        prg_lbl.pack()

        # Displays message log that prints from log file and starts darkskypy.
        self.prg_log = Text(prg_frame,
                            width=90,
                            padx=5,
                            pady=5,
                            relief="sunken")
        self.prg_log.pack()
        self.prg_log.insert(
            "end", "*****Progress Log*****\n=======================\n")
        self.prg_log.tag_add("abt", "1.0", "3.0")
        self.prg_log.tag_config("abt", font='Courier 12 bold', justify=CENTER)
        self.txt_redir = LogRedirector(self.prg_log)
        logger.addHandler(self.txt_redir)
        sys.stderr = StderrRedirector(self.prg_log)
        prg_lbl_txt.set("Start time: " + str(time.asctime()))

        self.no_progress = 0

    def update_progress(self):
        """Update progress window to prevent it from freezing."""
        self.prg_log.update()
        # if only one thread exists, stop progress bar and close window
        if len(threading.enumerate()) == 1:
            self.prg_bar.stop()
            self.no_progress += 1
            if self.no_progress == 3:
                self.prg_window.withdraw()
        else:
            self.prg_bar.start()
        self.root.after(1000, self.update_progress)

    def generate_map(self):
        """Call darksky.sgmapper in background thread."""
        # Acquires input arguments.
        lat_in, k_in, zen_in, azi_in, file_in, krn_file_in = 0, 0, 0, 0, '', ''
        if self.krn_var.get():
            krn_file_in = self.krn_ent_var.get()
        else:
            lat_in = float(self.lat_entry.get())
            k_in = float(self.k_entry.get())
            zen_in = float(self.zen_entry.get())
            azi_in = float(self.azi_entry.get())
        file_in = self.file_log_var.get()

        self.progress()

        # Create new threads to run light propagation model simultaneously.
        p_thread = threading.Thread(target=self.update_progress())
        t_thread = threading.Thread(target=darksky.sgmapper,
                                    args=(lat_in, k_in, zen_in, azi_in,
                                          file_in, krn_file_in))
        t_thread.setDaemon(True)
        p_thread.start()
        t_thread.start()

    def generate_krn(self):
        """Start kernel generation in background threads."""
        # Acquires input arguments
        csv_in, file_in, lat_in, k_in, hem = '', '', 0, 0, False
        csv_in = self.csv_file_var.get()
        file_in = self.file_log_var.get()
        lat_in = float(self.lat_entry.get())
        k_in = float(self.k_entry.get())
        hem = self.hem_var.get()

        self.progress()

        # Create new threads to run light propagation model simultaneously.
        p_thread = threading.Thread(target=self.update_progress())
        with open(csv_in, "rb") as f:
            angle_list = loadtxt(f, delimiter=",", skiprows=1)
        p_thread.start()
        for angle_set in angle_list:
            t_thread = threading.Thread(target=darksky.generate_krn,
                                        args=(lat_in, k_in, angle_set[0],
                                              angle_set[1], file_in, hem))
            t_thread.setDaemon(True)

            t_thread.start()

    def generate_mmap(self):
        """Start brightness map creation from kernels."""
        # Acquires input arguments
        krn_folder_in, file_in, output_in, = '', '', ''
        krn_folder_in = self.krn_folder_var.get()
        file_in = self.file_log_var.get()
        output_in = self.output_folder_var.get()

        self.progress()

        # Create new threads to run light propagation model simultaneously.
        p_thread = threading.Thread(target=self.update_progress())
        t_thread = threading.Thread(target=darksky.multisgmapper,
                                    args=(file_in, krn_folder_in, output_in))
        t_thread.setDaemon(True)
        p_thread.start()
        t_thread.start()

    def generate_hem(self):
        """Generate hemisphere."""
        sgmap_folder_in, lat_in, lon_in, = '', 0, 0
        sgmap_folder_in = self.sgmap_folder_var.get()
        lat_in = float(self.lat_entry.get())
        lon_in = float(self.lon_entry.get())
        darksky.generate_hem(lat_in, lon_in, sgmap_folder_in)
예제 #28
0
    def __init__(self, main, bondForceParams, atoms_def):
        self.bondForceParams = bondForceParams
        self.dG_off_kJ = calc_dG(
            bondForceParams['T'], bondForceParams['r_aA'],
            bondForceParams['th_a'], bondForceParams['th_A'],
            bondForceParams['K_r_aA'], bondForceParams['K_th_a'],
            bondForceParams['K_th_A'], bondForceParams['K_phi_ba'],
            bondForceParams['K_phi_aA'], bondForceParams['K_phi_AB'])
        self.dG_on_kJ = -self.dG_off_kJ
        self.dG_off_kCal = kJ_to_kCal(self.dG_off_kJ)
        self.dG_on_kCal = kJ_to_kCal(self.dG_on_kJ)
        self.atoms_def = atoms_def
        self.main = main
        self.main.title('PyFepRestr')

        if platform == "darwin":
            self.button_font = self.label_font = self.radiobutton_font = Font(
                family='Arial', size=15)
        else:
            self.radiobutton_font = Font(font=Radiobutton()["font"])
            self.label_font = Font(font=Label()["font"])
            self.button_font = Font(font=Button()["font"])

        self.r_var = BooleanVar()
        self.r_var.set(0)
        rj1 = Radiobutton(self.main,
                          text='kJ',
                          variable=self.r_var,
                          value=0,
                          command=self.refresh,
                          font=self.radiobutton_font)
        rcal1 = Radiobutton(self.main,
                            text="kCal",
                            variable=self.r_var,
                            value=1,
                            command=self.refresh,
                            font=self.radiobutton_font)
        rj1.grid(row=0, column=0, padx=5, pady=5)
        rcal1.grid(row=0, column=1, padx=5, pady=5)

        name0 = Label(self.main, text=u'\u0394G_off = ', font=self.label_font)
        name1 = Label(self.main, text=u'\u0394G_on = ', font=self.label_font)
        name0.grid(row=1, column=0, padx=5, pady=5)
        name1.grid(row=2, column=0, padx=5, pady=5)

        self.answer0 = Label(self.main, font=self.label_font)
        self.answer1 = Label(self.main, font=self.label_font)
        self.answer0.grid(row=1, column=1, padx=5, pady=5)
        self.answer1.grid(row=2, column=1, padx=5, pady=5)

        self.dimen0 = Label(self.main, font=self.label_font)
        self.dimen1 = Label(self.main, font=self.label_font)
        self.dimen0.grid(row=1, column=2, padx=5, pady=5)
        self.dimen1.grid(row=2, column=2, padx=5, pady=5)
        self.refresh()

        destroyProgr = Button(self.main,
                              text='Exit',
                              bg='red',
                              command=self.main.destroy,
                              font=self.button_font)
        destroyProgr.grid(row=0, column=3, padx=5, pady=5)

        helpProgr = Button(self.main,
                           text=' ? ',
                           bg='#ffb3fe',
                           command=self.getHelp,
                           font=self.button_font)
        helpProgr.grid(row=4, column=0, padx=5, pady=5)

        self.select_prog = StringVar()
        self.select_prog.set("Gromacs topology file")
        prog_list = ["Gromacs topology file", "NAMD Colvars"]
        menu = OptionMenu(self.main, self.select_prog, *prog_list)
        menu.grid(row=3, column=0, padx=5, pady=5)

        previewButton = Button(self.main,
                               text='Preview',
                               bg='gray',
                               command=self.ViewRestr,
                               font=self.button_font)
        previewButton.grid(row=3, column=2, padx=5, pady=5)

        saveFileButton = Button(self.main,
                                text='Save',
                                bg='gray',
                                command=self.writeFile,
                                font=self.button_font)
        saveFileButton.grid(row=3, column=3, padx=5, pady=5)
예제 #29
0
	else:
		print 'equal'

nobinning_label = Label(root, text='No binning')
nobinning_value = IntVar(); nobinning_value.set(1)
nobinning_check = Checkbutton(root, variable=nobinning_value, onvalue=1, offvalue=0, command=check_binning)
p_label = Label(root, text='num_bins')
p_value = IntVar(); p_value.set(20)
p_entry = Entry(root, textvariable=p_value)
binchoice_label = Label(root, text='binchoice')
binchoice_frame = Frame(root)
binchoice_value = StringVar()
equal = Radiobutton(binchoice_frame,text='equal',variable=binchoice_value,value='equal')
equal.select()
adaptive = Radiobutton(binchoice_frame,text='adaptive',variable=binchoice_value,value='adaptive',command=check_binchoice)
equal.grid(row=0,column=0)
adaptive.grid(row=0,column=1)
binchoice_frame.grid()
check_binning()
check_binchoice()
submit_button = Button(root, text='RUN', command=run_glee)

nobinning_label.grid(row=0,column=0)
nobinning_check.grid(row=0,column=1)
p_label.grid(row=1,column=0, padx=5,pady=5)
p_entry.grid(row=1,column=1, padx=5,pady=5)
binchoice_label.grid(row=2,column=0, padx=5,pady=5)
binchoice_frame.grid(row=2,column=1, padx=5,pady=5)
submit_button.grid(row=3,column=0, padx=5,pady=5, columnspan=2, sticky='nsew')

root.grid()
예제 #30
0
파일: main.py 프로젝트: tdengg/pylastic
 def _create_setup_tab(self, nb):
     
     frame = Frame(nb, name='setup')
     
     self.e1 = Entry(frame, width=7)
     self.e1.bind()
     self.e1.grid(row=0, column=1)
     self.e1.delete(0, END)
     self.e1.insert(0, '21')
     
     self.label1 = Label(frame, text='Number of points:')
     self.label1.grid(row=0, column=0, sticky=W)
     
     self.e2 = Entry(frame, width=7)
     self.e2.bind()
     self.e2.grid(row=1, column=1)
     self.e2.delete(0, END)
     self.e2.insert(0, '0.05')
     
     self.label2 = Label(frame, text='Max. Lagrangian strain:')
     self.label2.grid(row=1, column=0, sticky=W)
     
     #Choose inputfile (Button)
     b2 = Button(frame, text="Inputfile", width=15, command=self.select_file)
     b2.grid(row=3, column=0, columnspan=2)
     
     b = Button(frame, text="set values", width=15, command=self.read_val)
     b.grid(row=4, column=0, columnspan=2)
     
     #Read structure (Button)
     b1 = Button(frame, text="Read structure", width=15, command=self.read_POS)
     b1.grid(row=5, column=0, columnspan=2)
     
     #Write structures (Button)
     b3 = Button(frame, text="Setup calculation", width=15, command=self.setup_calc)
     b3.grid(row=6, column=0, columnspan=2)
     
     #Strart calculations
     b4 = Button(frame, text="Calculation status", width=15, command=self.check_calc)
     b4.grid(row=7, column=0, columnspan=2)
     
     
     v = IntVar()
     r11 = Radiobutton(frame, text="Energy", variable=v, value=1)
     r12 = Radiobutton(frame, text="Strain", variable=v, value=2, state=DISABLED)
     r11.select()
     r11.grid(row=8, column=0, sticky=W)
     r12.grid(row=9, column=0, sticky=W)
     
     
     w = IntVar()
     r21 = Radiobutton(frame, text="2nd", variable=w, value=1)
     r22 = Radiobutton(frame, text="3rd", variable=w, value=2)
     r21.select()
     r21.grid(row=10, column=0, sticky=W)
     r22.grid(row=11, column=0, sticky=W)
     
     
     nb.add(frame, text='Setup', underline=0, padding=2)
     
     return
예제 #31
0
class Tool_Path_Generator:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#e6e6e6'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        font11 = "-size 15 -weight normal -slant roman "  \
            "-underline 0 -overstrike 0"

        self.axial_length = DoubleVar()
        self.printbed_diameter = DoubleVar()
        self.final_diameter = DoubleVar()
        self.filament_width_og = DoubleVar()
        self.helix_angle = DoubleVar()
        self.smear_factor = DoubleVar()
        self.flow_rate = DoubleVar()
        self.uv_offset = DoubleVar()
        self.use_strong_pattern = BooleanVar()

        self.axial_length.set(200.0)
        self.printbed_diameter.set(10.0)
        self.final_diameter.set(15.0)
        self.filament_width_og.set(0.41)
        self.helix_angle.set(45.0)
        self.smear_factor.set(100.0)
        self.flow_rate.set(0.0015)
        self.uv_offset.set(32.5)
        self.use_strong_pattern.set(True)

        top.geometry("700x550")
        top.title("SkelePrint Tool Path Generator")
        top.configure(background="#e6e6e6")
        top.configure(highlightbackground="#e6e6e6")
        top.configure(highlightcolor="black")

        self.Label7 = Label(top)
        self.Label7.grid(row=0, column=0, sticky=W)
        self.Label7.configure(background="#e6e6e6")
        self.Label7.configure(font=font11)
        self.Label7.configure(foreground="#000000")
        self.Label7.configure(text='''SkelePrint Tool Path Generator''')

        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.grid(row=1, column=0, sticky=N+S)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Dimensions''')
        self.Labelframe1.configure(background="#e6e6e6")
        self.Labelframe1.configure(highlightbackground="#e6e6e6")
        self.Labelframe1.configure(highlightcolor="black")

        self.axial_length_entry = Entry(self.Labelframe1)
        self.axial_length_entry.grid(row=0, column=1)
        self.axial_length_entry.configure(background="white")
        self.axial_length_entry.configure(font="TkFixedFont")
        self.axial_length_entry.configure(foreground="#000000")
        self.axial_length_entry.configure(highlightbackground="#e6e6e6")
        self.axial_length_entry.configure(highlightcolor="black")
        self.axial_length_entry.configure(insertbackground="black")
        self.axial_length_entry.configure(selectbackground="#c4c4c4")
        self.axial_length_entry.configure(selectforeground="black")
        self.axial_length_entry.configure(textvariable=self.axial_length)

        self.Label1 = Label(self.Labelframe1)
        self.Label1.grid(row=0, column=0, sticky=E)
        self.Label1.configure(activebackground="#e6e6e6")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#e6e6e6")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#e6e6e6")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Axial Length''')

        self.Label2 = Label(self.Labelframe1)
        self.Label2.grid(row=0, column=2, sticky=W)
        self.Label2.configure(activebackground="#e6e6e6")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#e6e6e6")
        self.Label2.configure(disabledforeground="#e6e6e6")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#e6e6e6")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text='''mm''')

        self.Label3 = Label(self.Labelframe1)
        self.Label3.grid(row=1, column=0, sticky=E)
        self.Label3.configure(activebackground="#e6e6e6")
        self.Label3.configure(activeforeground="black")
        self.Label3.configure(background="#e6e6e6")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(highlightbackground="#e6e6e6")
        self.Label3.configure(highlightcolor="black")
        self.Label3.configure(text='''Printbed Diameter''')

        self.Entry2 = Entry(self.Labelframe1)
        self.Entry2.grid(row=1, column=1)
        self.Entry2.configure(background="white")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(highlightbackground="#e6e6e6")
        self.Entry2.configure(highlightcolor="black")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(selectbackground="#c4c4c4")
        self.Entry2.configure(selectforeground="black")
        self.Entry2.configure(textvariable=self.printbed_diameter)

        self.Label4 = Label(self.Labelframe1)
        self.Label4.grid(row=1, column=2, sticky=W)
        self.Label4.configure(activebackground="#e6e6e6")
        self.Label4.configure(activeforeground="black")
        self.Label4.configure(background="#e6e6e6")
        self.Label4.configure(foreground="#000000")
        self.Label4.configure(highlightbackground="#e6e6e6")
        self.Label4.configure(highlightcolor="black")
        self.Label4.configure(text='''mm''')

        self.Label5 = Label(self.Labelframe1)
        self.Label5.grid(row=2, column=0, sticky=E)
        self.Label5.configure(activebackground="#e6e6e6")
        self.Label5.configure(activeforeground="black")
        self.Label5.configure(background="#e6e6e6")
        self.Label5.configure(foreground="#000000")
        self.Label5.configure(highlightbackground="#e6e6e6")
        self.Label5.configure(highlightcolor="black")
        self.Label5.configure(text='''Final Print Diameter''')

        self.final_diameter_entry = Entry(self.Labelframe1)
        self.final_diameter_entry.grid(row=2, column=1)
        self.final_diameter_entry.configure(background="white")
        self.final_diameter_entry.configure(font="TkFixedFont")
        self.final_diameter_entry.configure(foreground="#000000")
        self.final_diameter_entry.configure(highlightbackground="#e6e6e6")
        self.final_diameter_entry.configure(highlightcolor="black")
        self.final_diameter_entry.configure(insertbackground="black")
        self.final_diameter_entry.configure(selectbackground="#c4c4c4")
        self.final_diameter_entry.configure(selectforeground="black")
        self.final_diameter_entry.configure(textvariable=self.final_diameter)

        self.Label6 = Label(self.Labelframe1)
        self.Label6.grid(row=2, column=2, sticky=W)
        self.Label6.configure(activebackground="#e6e6e6")
        self.Label6.configure(activeforeground="black")
        self.Label6.configure(background="#e6e6e6")
        self.Label6.configure(foreground="#000000")
        self.Label6.configure(highlightbackground="#e6e6e6")
        self.Label6.configure(highlightcolor="black")
        self.Label6.configure(text='''mm''')

        self.Entry4 = Entry(self.Labelframe1)
        self.Entry4.grid(row=3, column=1)
        self.Entry4.configure(background="white")
        self.Entry4.configure(font="TkFixedFont")
        self.Entry4.configure(foreground="#000000")
        self.Entry4.configure(highlightbackground="#e6e6e6")
        self.Entry4.configure(highlightcolor="black")
        self.Entry4.configure(insertbackground="black")
        self.Entry4.configure(selectbackground="#c4c4c4")
        self.Entry4.configure(selectforeground="black")
        self.Entry4.configure(textvariable=self.filament_width_og)

        self.Label7 = Label(self.Labelframe1)
        self.Label7.grid(row=3, column=2, sticky=W)
        self.Label7.configure(activebackground="#e6e6e6")
        self.Label7.configure(activeforeground="black")
        self.Label7.configure(background="#e6e6e6")
        self.Label7.configure(foreground="#000000")
        self.Label7.configure(highlightbackground="#e6e6e6")
        self.Label7.configure(highlightcolor="black")
        self.Label7.configure(text='''mm''')

        self.Label8 = Label(self.Labelframe1)
        self.Label8.grid(row=3, column=0, sticky=E)
        self.Label8.configure(activebackground="#e6e6e6")
        self.Label8.configure(activeforeground="black")
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(highlightbackground="#e6e6e6")
        self.Label8.configure(highlightcolor="black")
        self.Label8.configure(text='''Filament Width''')

        self.tip = Label(self.Labelframe1, width=300, height=300)

        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))

        img = Image.open(os.path.join(__location__, 'dimensions.png'))
        one = ImageTk.PhotoImage(img)

        self.tip = Label(self.Labelframe1, image=one)
        self.tip.image = one
        self.tip.configure(background="#e6e6e6")
        self.tip.grid(row=4, columnspan=3)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.grid(row=1, column=1, sticky=N+S)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Print Properties''')
        self.Labelframe2.configure(background="#e6e6e6")
        self.Labelframe2.configure(highlightbackground="#e6e6e6")
        self.Labelframe2.configure(highlightcolor="black")

        self.Label9 = Label(self.Labelframe2)
        self.Label9.grid(row=0, column=0, sticky=E)
        self.Label9.configure(activebackground="#e6e6e6")
        self.Label9.configure(activeforeground="black")
        self.Label9.configure(background="#e6e6e6")
        self.Label9.configure(foreground="#000000")
        self.Label9.configure(highlightbackground="#e6e6e6")
        self.Label9.configure(highlightcolor="black")
        self.Label9.configure(text='''Helix Angle''')

        self.Entry5 = Entry(self.Labelframe2)
        self.Entry5.grid(row=0, column=1)
        self.Entry5.configure(background="white")
        self.Entry5.configure(font="TkFixedFont")
        self.Entry5.configure(foreground="#000000")
        self.Entry5.configure(highlightbackground="#e6e6e6")
        self.Entry5.configure(highlightcolor="black")
        self.Entry5.configure(insertbackground="black")
        self.Entry5.configure(selectbackground="#c4c4c4")
        self.Entry5.configure(selectforeground="black")
        self.Entry5.configure(textvariable=self.helix_angle)

        self.Label10 = Label(self.Labelframe2)
        self.Label10.grid(row=0, column=2, sticky=W)
        self.Label10.configure(activebackground="#e6e6e6")
        self.Label10.configure(activeforeground="black")
        self.Label10.configure(background="#e6e6e6")
        self.Label10.configure(foreground="#000000")
        self.Label10.configure(highlightbackground="#e6e6e6")
        self.Label10.configure(highlightcolor="black")
        self.Label10.configure(text='''degrees [0 - 90]''')

        self.strong_targeter_button = Radiobutton(self.Labelframe2)
        self.strong_targeter_button.grid(row=1, column=0, sticky=E)
        self.strong_targeter_button.configure(variable=self.use_strong_pattern)
        self.strong_targeter_button.configure(value=True)
        self.strong_targeter_button.configure(activebackground="#e6e6e6")
        self.strong_targeter_button.configure(activeforeground="black")
        self.strong_targeter_button.configure(background="#e6e6e6")
        self.strong_targeter_button.configure(foreground="#000000")
        self.strong_targeter_button.configure(highlightbackground="#e6e6e6")
        self.strong_targeter_button.configure(highlightcolor="black")

        self.strong_targeter_label = Label(self.Labelframe2)
        self.strong_targeter_label.grid(row=1, column=1, sticky=W)
        self.strong_targeter_label.configure(activebackground="#e6e6e6")
        self.strong_targeter_label.configure(activeforeground="black")
        self.strong_targeter_label.configure(background="#e6e6e6")
        self.strong_targeter_label.configure(foreground="#000000")
        self.strong_targeter_label.configure(highlightbackground="#e6e6e6")
        self.strong_targeter_label.configure(highlightcolor="black")
        self.strong_targeter_label.configure(text="Strong angle pattern")

        self.default_targeter_button = Radiobutton(self.Labelframe2)
        self.default_targeter_button.grid(row=2, column=0, sticky=E)
        self.default_targeter_button.configure(activebackground="#e6e6e6")
        self.default_targeter_button.configure(activeforeground="black")
        self.default_targeter_button.configure(background="#e6e6e6")
        self.default_targeter_button.configure(foreground="#000000")
        self.default_targeter_button.configure(highlightbackground="#e6e6e6")
        self.default_targeter_button.configure(highlightcolor="black")
        self.default_targeter_button.configure(
                variable=self.use_strong_pattern)
        self.default_targeter_button.configure(value=False)

        self.default_targeter_label = Label(self.Labelframe2)
        self.default_targeter_label.grid(row=2, column=1, sticky=W)
        self.default_targeter_label.configure(activebackground="#e6e6e6")
        self.default_targeter_label.configure(activeforeground="black")
        self.default_targeter_label.configure(background="#e6e6e6")
        self.default_targeter_label.configure(foreground="#000000")
        self.default_targeter_label.configure(highlightbackground="#e6e6e6")
        self.default_targeter_label.configure(highlightcolor="black")
        self.default_targeter_label.configure(text="Default angle pattern")

        self.Scale1 = Scale(self.Labelframe2)
        self.Scale1.grid(row=5, column=1, columnspan=2, sticky=S+W)
        self.Scale1.configure(activebackground="#e6e6e6")
        self.Scale1.configure(background="#e6e6e6")
        self.Scale1.configure(font="TkTextFont")
        self.Scale1.configure(foreground="#000000")
        self.Scale1.configure(from_="5.0")
        self.Scale1.configure(highlightbackground="#d9d9d9")
        self.Scale1.configure(highlightcolor="black")
        self.Scale1.configure(length="150")
        self.Scale1.configure(orient="horizontal")
        self.Scale1.configure(resolution="5.0")
        self.Scale1.configure(troughcolor="#d9d9d9")
        self.Scale1.configure(variable=self.smear_factor)

        self.Label8 = Label(self.Labelframe2)
        self.Label8.grid(row=3, column=0, sticky=E)
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(text='''Flow rate''')

        self.Entry6 = Entry(self.Labelframe2)
        self.Entry6.grid(row=3, column=1)
        self.Entry6.configure(background="white")
        self.Entry6.configure(font="TkFixedFont")
        self.Entry6.configure(foreground="#000000")
        self.Entry6.configure(highlightbackground="#e6e6e6")
        self.Entry6.configure(highlightcolor="black")
        self.Entry6.configure(insertbackground="black")
        self.Entry6.configure(selectbackground="#c4c4c4")
        self.Entry6.configure(selectforeground="black")
        self.Entry6.configure(textvariable=self.flow_rate)

        self.Label12 = Label(self.Labelframe2)
        self.Label12.grid(row=3, column=2, sticky=W)
        self.Label12.configure(activebackground="#e6e6e6")
        self.Label12.configure(activeforeground="black")
        self.Label12.configure(background="#e6e6e6")
        self.Label12.configure(foreground="#000000")
        self.Label12.configure(highlightbackground="#d9d9d9")
        self.Label12.configure(highlightcolor="black")
        self.Label12.configure(text='''cm^3 / s''')

        self.uv_label = Label(self.Labelframe2)
        self.uv_label.grid(row=4, column=0, sticky=E)
        self.uv_label.configure(activebackground="#e6e6e6")
        self.uv_label.configure(activeforeground="black")
        self.uv_label.configure(background="#e6e6e6")
        self.uv_label.configure(foreground="#000000")
        self.uv_label.configure(highlightbackground="#d9d9d9")
        self.uv_label.configure(highlightcolor="black")
        self.uv_label.configure(text="UV Distance")

        self.uv_entry = Entry(self.Labelframe2)
        self.uv_entry.grid(row=4, column=1)
        self.uv_entry.configure(background="white")
        self.uv_entry.configure(font="TkFixedFont")
        self.uv_entry.configure(foreground="#000000")
        self.uv_entry.configure(highlightbackground="#e6e6e6")
        self.uv_entry.configure(highlightcolor="black")
        self.uv_entry.configure(insertbackground="black")
        self.uv_entry.configure(selectbackground="#c4c4c4")
        self.uv_entry.configure(selectforeground="black")
        self.uv_entry.configure(textvariable=self.uv_offset)

        self.uv_label_2 = Label(self.Labelframe2)
        self.uv_label_2.grid(row=4, column=2, sticky=W)
        self.uv_label_2.configure(activebackground="#e6e6e6")
        self.uv_label_2.configure(activeforeground="black")
        self.uv_label_2.configure(background="#e6e6e6")
        self.uv_label_2.configure(foreground="#000000")
        self.uv_label_2.configure(highlightbackground="#d9d9d9")
        self.uv_label_2.configure(highlightcolor="black")
        self.uv_label_2.configure(text='''mm''')

        self.Label11 = Label(self.Labelframe2)
        self.Label11.grid(row=5, column=0, sticky=S+E)
        self.Label11.configure(activebackground="#e6e6e6")
        self.Label11.configure(activeforeground="black")
        self.Label11.configure(background="#e6e6e6")
        self.Label11.configure(foreground="#000000")
        self.Label11.configure(highlightbackground="#d9d9d9")
        self.Label11.configure(highlightcolor="black")
        self.Label11.configure(text='''Layer Height %''')

        self.Label13 = Label(self.Labelframe2)
        self.Label13.grid(row=6, columnspan=3)
        self.Label13.configure(activebackground="#f9f9f9")
        self.Label13.configure(activeforeground="black")
        self.Label13.configure(background="#e6e6e6")
        self.Label13.configure(foreground="#000000")
        self.Label13.configure(highlightbackground="#d9d9d9")
        self.Label13.configure(highlightcolor="black")
        self.Label13.configure(text='''caution: layer height % is experimental
default = 100% (ie. layer height = filament width)''')

        self.Message1 = Message(self.Labelframe2)
        self.Message1.grid(row=8, columnspan=3)
        self.Message1.configure(anchor=N)
        self.Message1.configure(background="#e6e6e6")
        self.Message1.configure(foreground="#000000")
        self.Message1.configure(highlightbackground="#e6e6e6")
        self.Message1.configure(highlightcolor="black")
        self.Message1.configure(text='''Helix Angle Conditions:
If the angle is > 90, it will be set to 90 degrees

If angle is < 0, it will be set to 0 degrees

If angle = 0, the layer will consist of a single helix printed as close \
together as possible

If angle = 90, the layer will consist of many straight lines''')

        self.tip2 = Label(self.Labelframe2, width=300, height=91)

        img2 = Image.open(os.path.join(__location__, 'theta.jpg'))
        two = ImageTk.PhotoImage(img2)

        self.tip2 = Label(self.Labelframe2, image=two)
        self.tip2.image = two
        self.tip2.configure(background="#e6e6e6")
        self.tip2.grid(row=7, columnspan=3)

        self.Label8 = Label(top)
        self.Label8.grid(row=5, columnspan=2)
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(text='''G Code file will be saved on your Desktop under:
"gcode/timestamp_skeleprint_gcode.gcode"''')

        self.Button1 = Button(top)
        self.Button1.grid(row=2, columnspan=2)
        self.Button1.configure(activebackground="#e6e6e6")
        self.Button1.configure(activeforeground="#e6e6e6")
        self.Button1.configure(background="#e6e6e6")
        self.Button1.configure(command=lambda: tpg_gui_support.tpg(
            self.axial_length.get(),
            self.filament_width_og.get(),
            self.printbed_diameter.get(),
            self.final_diameter.get(),
            self.helix_angle.get(),
            self.smear_factor.get(),
            self.flow_rate.get(),
            self.uv_offset.get(),
            self.use_strong_pattern.get()))
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#e6e6e6")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(relief=RAISED)
        self.Button1.configure(text='''Generate G Code''')

        self.menubar = Menu(top, font="TkMenuFont", bg=_bgcolor, fg=_fgcolor)
        top.configure(menu=self.menubar)
예제 #32
0
    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Binding F5 application-wide to run lint
        self.root.bind('<F5>', self.run_lint)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                                  yscrollcommand=rightscrollbar.set,
                                  xscrollcommand=bottomscrollbar.set,
                                  bg="white")
        self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile)
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #Message context menu
        self.mnMessages = Menu(self.lbMessages, tearoff=0)
        self.mnMessages.add_command(label="View in sourcefile",
                                    command=self.show_sourcefile)
        self.mnMessages.add_command(label="Add to ignore patchfile",
                                    command=self.add_to_ignore_patchfile)
        self.lbMessages.bind("<Button-3>", self.show_messages_context)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                                   yscrollcommand=rightscrollbar2.set,
                                   xscrollcommand=bottomscrollbar2.set,
                                   bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                               yscrollcommand=rightscrollbar.set,
                               xscrollcommand=bottomscrollbar.set,
                               bg="white",
                               font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame,
               text='Open Package',
               command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame,
                        text="Information",
                        fg=COLORS['(I)'],
                        variable=self.information_box,
                        command=self.refresh_msg_window)
        c = Checkbutton(check_frame,
                        text="Convention",
                        fg=COLORS['(C)'],
                        variable=self.convention_box,
                        command=self.refresh_msg_window)
        r = Checkbutton(check_frame,
                        text="Refactor",
                        fg=COLORS['(R)'],
                        variable=self.refactor_box,
                        command=self.refresh_msg_window)
        w = Checkbutton(check_frame,
                        text="Warning",
                        fg=COLORS['(W)'],
                        variable=self.warning_box,
                        command=self.refresh_msg_window)
        e = Checkbutton(check_frame,
                        text="Error",
                        fg=COLORS['(E)'],
                        variable=self.error_box,
                        command=self.refresh_msg_window)
        f = Checkbutton(check_frame,
                        text="Fatal",
                        fg=COLORS['(F)'],
                        variable=self.fatal_box,
                        command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame,
                             text="Report",
                             variable=self.box,
                             value="Report",
                             command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame,
                             text="Raw metrics",
                             variable=self.box,
                             value="Raw metrics",
                             command=self.refresh_results_window)
        dup = Radiobutton(radio_frame,
                          text="Duplication",
                          variable=self.box,
                          value="Duplication",
                          command=self.refresh_results_window)
        ext = Radiobutton(radio_frame,
                          text="External dependencies",
                          variable=self.box,
                          value="External dependencies",
                          command=self.refresh_results_window)
        stat = Radiobutton(radio_frame,
                           text="Statistics by type",
                           variable=self.box,
                           value="Statistics by type",
                           command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame,
                             text="Messages by category",
                             variable=self.box,
                             value="Messages by category",
                             command=self.refresh_results_window)
        msg = Radiobutton(radio_frame,
                          text="Messages",
                          variable=self.box,
                          value="Messages",
                          command=self.refresh_results_window)
        sourceFile = Radiobutton(radio_frame,
                                 text="Source File",
                                 variable=self.box,
                                 value="Source File",
                                 command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=W)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, sticky=W)
        sourceFile.grid(column=3, row=1, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I': lambda: self.information_box.get() == 1,
            'C': lambda: self.convention_box.get() == 1,
            'R': lambda: self.refactor_box.get() == 1,
            'E': lambda: self.error_box.get() == 1,
            'W': lambda: self.warning_box.get() == 1,
            'F': lambda: self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()
예제 #33
0
파일: game.py 프로젝트: klasy/tic-tac-toe
class Game:
    """
    This is our Game - everything important is handled here
    """
    def __init__(self, parent):
        self.parent = parent
        self.level = 1

        # create a board
        self.board = Board(self.parent, 100, "#ECECEC")  # hex color gray
        self.board.draw_board()

        # create players
        self.player1 = Player("Human")
        self.player2 = Player("Computer")

        self.level_var = IntVar()

        # setting the player to Human as the Human starts
        self.player = self.player1

        self.initialize_controls()
        self.layout()

    def initialize_controls(self, rest=False):
        label_text = StringVar()
        label_text.set("It is a %s's turn" % self.player.name)
        self.board.canvas.bind('<Button-1>', self.move)

        self.label = Label(self.board.container, textvariable=label_text)
        self.level1 = Radiobutton(self.board.container,
                                  text="Easy",
                                  variable=self.level_var,
                                  value=1,
                                  command=self.update_level)
        self.level2 = Radiobutton(self.board.container,
                                  text="Medium",
                                  variable=self.level_var,
                                  value=2,
                                  command=self.update_level)
        self.level3 = Radiobutton(self.board.container,
                                  text="Hard",
                                  variable=self.level_var,
                                  value=3,
                                  command=self.update_level)
        self.reset_button = Button(self.board.container,
                                   text="Reset",
                                   width=25,
                                   command=self.restart)

    def layout(self):
        # register buttons to board's container
        self.label.grid()
        self.level1.grid(row=0, column=1, sticky=W)
        self.level2.grid(row=1, column=1, sticky=W)
        self.level3.grid(row=2, column=1, sticky=W)
        self.level_var.set(self.level)
        self.reset_button.grid(row=4, sticky=E)

    def update_level(self):
        self.level = self.level_var.get()

    def restart(self):
        ''' Restart the game from the very beginning, reinitialize everything '''
        self.board.container.destroy()
        self.player1.clean_moves()
        self.player2.clean_moves()

        self.board = Board(self.parent, 100, "#ECECEC")
        self.board.draw_board()
        self.player = self.player1
        self.initialize_controls(rest=True)
        self.layout()

    def move(self, event):
        """
        This method is called when the button is clicked
        :param event: this is a mouse click with coordinates
        """

        if self.player.name == "Computer":
            self.computers_move()
        else:
            self.humans_move(event)

    def computers_move(self):

        xy_key = self.make_a_move(self.level)

        if xy_key is None:
            # something went wrong
            # need to handle it correctly
            self.result("We can't make a move any more!", "error")
            return

        x, y = self.board.translate_cells_dict_key_to_text_coords(xy_key)
        self.board.canvas.create_text(x, y, text="O", font=("Purisa", 60))

        # update the unused cells dictionary
        self.player.add_move(self.board.unused_cells_dict[xy_key])
        self.board.update_unused_cells_dict(xy_key)

        if self.check_if_won():
            return

        self.player = self.player1

    def humans_move(self, event):
        """
        This function handles
        :param event: this is a click event
        """

        if len(self.board.get_unused_cells_dict()) == 0:
            self.result("The game is over! Click Reset button", "info")
            return

        # a little logic to get the top left corner coords to draw the text
        floor_x, floor_y = self.board.get_floor_coord(event.x, event.y)
        xy_key = self.board.convert_coord_to_key(floor_x, floor_y)

        if not self.board.check_if_key_available(xy_key):
            self.result(
                "This cell is already busy - please, make another move",
                "warning")
            return

        x, y = self.board.translate_cells_dict_key_to_text_coords(xy_key)
        self.board.canvas.create_text(x, y, text="X", font=("Purisa", 60))

        # update the unused cells dictionary
        self.player.add_move(self.board.unused_cells_dict[xy_key])
        self.board.update_unused_cells_dict(xy_key)

        if self.check_if_won():
            return

        self.player = self.player2

        # imitate a button click for a computer move
        # with the event = None
        self.move(None)

    def make_a_move(self, level):
        """
        Here we make a move according to the computer intelligence level
        """

        unused_cells = self.board.get_unused_cells_dict()
        # if there's no more unused cells left
        # we can't move
        if len(unused_cells) == 0:
            return None

        cell_key = ""

        cells_list = unused_cells.keys()
        if level == 1:
            cell_key = choice(cells_list)
        if level == 3:
            # if it is the first move
            if len(unused_cells) == 8:
                corner_values = [1, 3, 7, 9]
                # if the first move was made in the corner
                if any(x in corner_values for x in self.player1.moves):
                    return "11"
                # else if the center field is taken
                elif "11" not in unused_cells.keys():
                    tmp_unused_cells = []
                    for key, value in unused_cells.iteritems():
                        if value in corner_values:
                            tmp_unused_cells.append(key)
                    return choice(tmp_unused_cells)
        if level == 2 or level == 3:
            # check if there's any pair where we can win
            tmp_cell_key_computer = self.check_twos(self.player2)
            if tmp_cell_key_computer == []:
                # if there's no such pair we need to prevent human from winning
                tmp_cell_key_human = self.check_twos(self.player1)
                if tmp_cell_key_human == []:
                    cell_key = choice(cells_list)
                else:
                    cell_key = choice(tmp_cell_key_human)
            else:
                cell_key = choice(tmp_cell_key_computer)

        return cell_key

    def check_twos(self, player):
        result_list = []
        for item in self.board.winning_combos:
            tmp_twos_dict = [[item[1], item[2]], [item[0], item[2]],
                             [item[0], item[1]]]
            if tmp_twos_dict[0][0] in player.moves and tmp_twos_dict[0][
                    1] in player.moves:
                result_list.append(item[0])
            if tmp_twos_dict[1][0] in player.moves and tmp_twos_dict[1][
                    1] in player.moves:
                result_list.append(item[1])
            if tmp_twos_dict[2][0] in player.moves and tmp_twos_dict[2][
                    1] in player.moves:
                result_list.append(item[2])
        result_keys = self.board.convert_vals_to_keys(result_list)
        return result_keys

    def check_if_won(self):
        ''' Here we define if the current user wins the game or is t a tie '''

        # if we did not do the 3 moves yet we could not have won
        if len(self.player.moves) < 3:
            return False

        for combo in self.board.winning_combos:
            if combo[0] in self.player.moves and \
               combo[1] in self.player.moves and \
               combo[2] in self.player.moves:
                self.result("%s wins!" % self.player.name, "info")
                self.board.unused_cells_dict = {}
                return True

        if len(self.board.get_unused_cells_dict()) == 0:
            self.result("It's a TIE!!!!", "info")
            return True

    def result(self, text, show_opt):
        ''' This function is gonna show the message box above the board '''
        if show_opt == "info":
            tkMessageBox.showinfo(title="Congraulations!", message=text)
        elif show_opt == "warning":
            tkMessageBox.showwarning(title="Warning!", message=text)
        elif show_opt == "error":
            tkMessageBox.showerror(title="Error!!!", message=text)
예제 #34
0
class JuegoChozas:
    def __init__(self, parent):
        self.imagen_fondo = PhotoImage(file="Jungle_small_2.gif")
        self.imagen_choza = PhotoImage(file="Hut_small_2.gif")

        self.ancho_choza = 60
        self.alto_choza = 140
        self.container = parent

        self.Chozas = []
        self.result = ""

        self.ocupar_chozas()

        self.setup()

    def ocupar_chozas(self):
        ocupantes = ['enemigo', 'amigo', 'vacia']
        while len(self.Chozas) < 5:
            computer_choice = random.choice(ocupantes)
            self.Chozas.append(computer_choice)
        print("Los ocupantes de las chozas son:", self.Chozas)

    def entrar_choza(self, numero_choza):
        print("Entrando en la choza #:", numero_choza)
        ocupante_choza = self.Chozas[numero_choza - 1]
        print("El ocupante de la choza es: ", ocupante_choza)

        if ocupante_choza == 'enemigo':
            self.result = "Enemigo visto en la choza # %d \n\n" % numero_choza
            self.result += "Has perdido :( Mucha suerte la próxima vez!"
        elif ocupante_choza == 'vacia':
            self.result = "La Choza # %d está vacia\n\n" % numero_choza
            self.result += "Enhorabuena! Has ganado!!!"
        else:
            self.result = "Amigo visto en la choza # %d \n\n" % numero_choza
            self.result += "Enhorabuena! Has ganado!!!"

        self.anunciar_ganador(self.result)

    def crear_widgets(self):

        self.var = IntVar()
        self.background_label = Label(self.container, image=self.imagen_fondo)
        txt = "Selecciona una choza en la que entrar. Ganarás si:\n"
        txt += "La choza está vacia o si su ocupante es tu aliado, de lo contrario morirás"
        self.info_label = Label(self.container, text=txt, bg='white')
        # Creamos un dicionario con las opciones para las imagenes de las chozas
        r_btn_config = {
            'variable': self.var,
            'bg': '#8AA54C',
            'activebackground': 'green',
            'image': self.imagen_choza,
            'height': self.alto_choza,
            'width': self.ancho_choza,
            'command': self.radio_btn_pressed
        }

        self.r1 = Radiobutton(self.container, r_btn_config, value=1)
        self.r2 = Radiobutton(self.container, r_btn_config, value=2)
        self.r3 = Radiobutton(self.container, r_btn_config, value=3)
        self.r4 = Radiobutton(self.container, r_btn_config, value=4)
        self.r5 = Radiobutton(self.container, r_btn_config, value=5)

    def setup(self):
        self.crear_widgets()
        self.setup_layout()

    def setup_layout(self):
        self.container.grid_rowconfigure(1, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(4, weight=1)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.info_label.grid(row=0, column=0, columnspan=5, sticky='nsew')
        self.r1.grid(row=1, column=0)
        self.r2.grid(row=1, column=2)
        self.r3.grid(row=1, column=4)
        self.r4.grid(row=4, column=2)
        self.r5.grid(row=4, column=0)

    def anunciar_ganador(self, data):
        messagebox.showinfo("¡Atención!", message=data)

    # Handle Events
    def radio_btn_pressed(self):
        self.entrar_choza(self.var.get())
class PAGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Parameter Analyzer Control")
        self.style = Style()
        self.style.theme_use("clam")
        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)

        #set up instance variables
        self.directory = StringVar()
        self.fname = StringVar()
        self.fname_final = StringVar()
        self.device = StringVar()
        self.chip = StringVar()
        self.run = StringVar()

        self.toplabel = Label(self,
                              text="Dummy label at the top of the widget",
                              justify="center")
        self.bottomlabel = Label(
            self,
            text="for help/info see github.com/leobrowning92/pa-control",
            justify="center",
            font="arial 11 italic")

        self.directory_btn = Button(self,
                                    text="Directory",
                                    command=self.askdirectory)

        self.filename_btn = Button(self, text="Filename", command=self.askfile)

        # self.exit_btn = Button(self, text="Exit", command=self.quit)
        # self.exit_btn.grid(row=5, column=0, padx=5)

        self.update_btn = Button(self, text="Update", command=self.runUpdate)

        self.iterdevice_btn = Button(self,
                                     text="Iterate [device]",
                                     command=self.newDevice)

        self.iterchip_btn = Button(self,
                                   text="Iterate [chip]",
                                   command=self.newChip)
        self.iterrun_btn = Button(self,
                                  text="Iterate [run]",
                                  command=self.newRun)

        self.chip.set("001")
        self.chipnum_entry = Entry(self, textvariable=self.chip, width=5)

        self.device.set("01")
        self.devicenum_entry = Entry(self, textvariable=self.device, width=5)

        self.run.set("001")
        self.runnum_entry = Entry(self, textvariable=self.run, width=5)

        self.directory_entry = Entry(self, textvariable=self.directory)

        self.fname.set(
            'Chip[chip]_[device]_run[run]_somenotes_[INFO]_[time].csv')
        self.fname_final.set(
            make_fname_final(self.fname.get(), self.chip.get(),
                             self.device.get(), self.run.get()))

        self.fname_entry = Entry(self, textvariable=self.fname)

        self.fname_final_label = Label(self,
                                       textvariable=self.fname_final,
                                       justify="center",
                                       font="arial 11 italic")

        # this button runs pulldata with parameter set by
        # self.datatype, which stores the value of self.radbtn
        self.pulldata_btn = Button(self,
                                   text="Pull Data",
                                   command=self.pulldata)

        self.datarun_btn = Button(self,
                                  text="Run Data sweep",
                                  command=self.datarun)

        #datatype=1 => diode, datatype=2 => FET
        self.datatype = IntVar()
        self.datatype1_radiobutton = Radiobutton(self,
                                                 text='Diode (VF, IF)',
                                                 variable=self.datatype,
                                                 value=1)
        self.datatype2_radiobutton = Radiobutton(self,
                                                 text='FET (VG, VDS, ID, IG)',
                                                 variable=self.datatype,
                                                 value=2)

        #grid alignments of all widgets
        self.toplabel.grid(column=0, columnspan=3, sticky=W, pady=4, padx=5)

        self.directory_btn.grid(row=1, column=0)
        self.directory_entry.grid(row=1,
                                  column=1,
                                  columnspan=2,
                                  padx=5,
                                  sticky=E + W)

        self.filename_btn.grid(row=2, column=0)
        self.fname_entry.grid(row=2,
                              column=1,
                              columnspan=2,
                              padx=5,
                              sticky=E + W)
        self.fname_final_label.grid(row=3,
                                    column=1,
                                    columnspan=2,
                                    sticky=N + E + W,
                                    pady=4,
                                    padx=5)

        self.iterchip_btn.grid(row=4, column=0, sticky=N)
        self.chipnum_entry.grid(row=4, column=1, padx=5, sticky=W)

        self.iterdevice_btn.grid(row=5, column=0, sticky=N)
        self.devicenum_entry.grid(row=5, column=1, padx=5, sticky=W)

        self.iterrun_btn.grid(row=6, column=0, sticky=N)
        self.runnum_entry.grid(row=6, column=1, padx=5, sticky=W)

        self.update_btn.grid(row=7, column=0, padx=5)
        self.pulldata_btn.grid(row=7, column=3, padx=5, sticky=E)
        self.datarun_btn.grid(row=6, column=3, padx=5, sticky=E)

        self.datatype1_radiobutton.grid(row=7,
                                        column=1,
                                        padx=5,
                                        sticky=N + E + S)
        self.datatype2_radiobutton.grid(row=7,
                                        column=2,
                                        padx=5,
                                        sticky=N + W + S)
        self.bottomlabel.grid(row=8,
                              column=0,
                              columnspan=3,
                              sticky=W,
                              pady=4,
                              padx=5)

#action funcctions for the various buttons

    def newChip(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.chip.set(str((int(self.chip.get()) + 1)).zfill(3))
                self.device.set(str(1).zfill(2))
            except Exception as e:
                print(e)
            self.runUpdate()

    def newRun(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.run.set(str((int(self.run.get()) + 1)).zfill(3))
            except Exception as e:
                print(e)
            self.runUpdate()

    def newDevice(self):
        if self.fname.get() == '':
            self.askfile()
        else:
            try:
                self.device.set(str((int(self.device.get()) + 1)).zfill(2))
            except Exception as e:
                print(e)
            self.runUpdate()

    def runUpdate(self):
        self.fname_final.set(
            make_fname_final(self.fname.get(), self.chip.get(),
                             self.device.get(), self.run.get()))

    def askdirectory(self):
        """Returns a selected directoryname."""
        self.directory.set(tkFileDialog.askdirectory())

    def askfile(self):
        fullpath = tkFileDialog.askopenfilename()
        if "/" in fullpath:
            i = fullpath.rfind("/")
        if "\\" in fullpath:
            i = fullpath.rfind("\\")
        # self.fname_final.set(fullpath[i + 1:])
        self.fname.set(fullpath[i + 1:])

    def pulldata(self):
        self.runUpdate()
        if self.datatype.get() == 1:
            download_data(path=self.directory.get(),
                          filename=self.fname_final.get(),
                          values=['VF', 'IF'])
        elif self.datatype.get() == 2:
            download_data(path=self.directory.get(),
                          filename=self.fname_final.get(),
                          values=['VG', 'VDS', 'ID', 'IG'])

    def datarun(self):
        self.runUpdate()
        if self.datatype.get() == 1:
            print("oh no we havent written a script for that yet!")
        elif self.datatype.get() == 2:
            run_FET_series(self.fname_final.get(), self.directory.get())
  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()
예제 #37
0
파일: gui.py 프로젝트: imcj/pybbs
    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white")
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                    yscrollcommand=rightscrollbar2.set,
                    xscrollcommand=bottomscrollbar2.set,
                    bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white", font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window)
        c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window)
        r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window)
        w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window)
        e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window)
        f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window)
        dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window)
        ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window)
        stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window)
        msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=E)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, columnspan=2, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I' : lambda : self.information_box.get() == 1,
            'C' : lambda : self.convention_box.get() == 1,
            'R' : lambda : self.refactor_box.get() == 1,
            'E' : lambda : self.error_box.get() == 1,
            'W' : lambda : self.warning_box.get() == 1,
            'F' : lambda : self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()
예제 #38
0
    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)
예제 #39
0
class View:
    def __init__(self, parent):
        """The View component of the Hut Game

        This class represents the view component of a MVC architecture. It
        defines and sets up a graphical user interface. In this example, the
        View has no knowlegde of the Controller or the model. However, the
        Controller sets up the necessary callback functions that are invoked
        when various events are triggered.

        :param parent: the parent tkinter widget
        :ivar int hut_width: the width of the application window in pixels
        :ivar int hut_height: the height of the application window in pixels
        :ivar PhotoImage village_image: background image for the app
        :ivar PhotoImage hut_image: the hut image for the radio buttons
        :ivar Tk container: the main widget serving as a parent for others. In
            this example it is just the main Tk instance.
        :ivar str result: the string to declare the result via a messagebox.
        """
        self.village_image = PhotoImage(file="jungle_small.gif")
        self.hut_image = PhotoImage(file="hut_small.gif")
        self.container = parent
        self.hut_width = 40
        self.hut_height = 56
        self.radio_btn_pressed = None

    def setup(self):
        """Calls methods to setup the user interface."""
        self.create_widgets()
        self.setup_layout()

    def set_callbacks(self, callback_function):
        """Assign the given function (argument) to a method in this class.

        This enables communication with the Controller. Another way is to use
        PyPubSub API.

        :param callback_function: the function to be assigned to an attribute
            of this View class.
        """
        self.radio_btn_pressed = callback_function

    def create_widgets(self):
        """Create various widges in the tkinter main window."""
        self.var = IntVar()
        self.background_label = Label(self.container, image=self.village_image)
        txt = "Select a hut to enter. You win if:\n"
        txt += "The hut is unoccupie or the occupant is a friend!"
        self.info_label = Label(self.container, text=txt, bg='yellow')

        # Create a dictionary for radio button config options.
        r_btn_config = {
            'variable': self.var,
            'bg': '#A8884C',
            'activebackground': 'yellow',
            'image': self.hut_image,
            'height': self.hut_height,
            'width': self.hut_width,
            'command': self.radio_btn_pressed
        }

        self.r1 = Radiobutton(self.container, r_btn_config, value=1)
        self.r2 = Radiobutton(self.container, r_btn_config, value=2)
        self.r3 = Radiobutton(self.container, r_btn_config, value=3)
        self.r4 = Radiobutton(self.container, r_btn_config, value=4)
        self.r5 = Radiobutton(self.container, r_btn_config, value=5)

    def setup_layout(self):
        """Use the grid geometry manager to place widgets."""
        self.container.grid_rowconfigure(1, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(4, weight=1)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.info_label.grid(row=0, column=0, columnspan=5, sticky='nsew')
        self.r1.grid(row=1, column=0)
        self.r2.grid(row=1, column=4)
        self.r3.grid(row=2, column=3)
        self.r4.grid(row=3, column=0)
        self.r5.grid(row=4, column=4)

    def announce_winner(self, data):
        """Declare the winner by displaying a tkinter messagebox

        :param string data: the data to be displayed in the messagebox.
        """
        messagebox.showinfo("Winner Announcement", message=data)
예제 #40
0
class View:
    def __init__(self, parent):
        """The View component of the Hut Game.

        This class represents the view component of a MVC architecture.
        It defines and sets up graphical user interface. In this example,
        the View has no knowledge of the Controller or the model. However,
        the Controller sets up the necessary callback functions that are
        invoked when various events are triggered.

        :param parent: The parent tkinter widget.In this example it is the
            instance of Tk class (called mainwin)
        :ivar int hut_width: The width of the application window in pixels.
        :ivar int hut_height: The height of the application window in pixels
        :ivar PhotoImage village_image: Background image for the app
        :ivar PhotoImage hut_image: The hut image for the radio buttons.
        :ivar container: The main widget serving as a parent for others.
            In this example it is just the main Tk instance passed as
        :ivar str result: The string to declare the result via a messagebox.
        """
        self.village_image = PhotoImage(file="Jungle_small.gif")
        self.hut_image = PhotoImage(file="Hut_small.gif")
        self.container = parent
        # ------------------------------------------------------------------
        # Important: Set the hut_width to about 70 pixels if the radio
        # button is configured with "indicatoron=0" option (i.e. without the
        # radio button indicator
        # ------------------------------------------------------------------
        self.hut_width = 40
        self.hut_height = 56

    def radio_btn_pressed(self):
        """Publishes a message to notify the Controller.

         Uses PyPubSub to publish a message to a topic Radio_button_pressed.
         The 'subscriber' here is the Controller which gets notified.
         """
        pub.sendMessage("Radio_Button_Pressed")

    def setup(self):
        """Calls methods to setup the user interface."""
        self.create_widgets()
        self.setup_layout()

    def create_widgets(self):
        """Create various widgets in the tkinter main window."""
        self.var = IntVar()
        self.background_label = Label(self.container, image=self.village_image)
        txt = "Select a hut to enter. You win if:\n"
        txt += "The hut is unoccupied or the occupant is a friend!"
        self.info_label = Label(self.container, text=txt, bg='yellow')
        # Create a dictionary for radio button config options.
        r_btn_config = {
            'variable': self.var,
            'bg': '#A8884C',
            'activebackground': 'yellow',
            'image': self.hut_image,
            'height': self.hut_height,
            'width': self.hut_width,
            'command': self.radio_btn_pressed
        }

        self.r1 = Radiobutton(self.container, r_btn_config, value=1)
        self.r2 = Radiobutton(self.container, r_btn_config, value=2)
        self.r3 = Radiobutton(self.container, r_btn_config, value=3)
        self.r4 = Radiobutton(self.container, r_btn_config, value=4)
        self.r5 = Radiobutton(self.container, r_btn_config, value=5)

    def setup_layout(self):
        """Use the grid geometry manager to place widgets."""
        self.container.grid_rowconfigure(1, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(4, weight=1)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.info_label.grid(row=0, column=0, columnspan=5, sticky='nsew')
        self.r1.grid(row=1, column=0)
        self.r2.grid(row=1, column=4)
        self.r3.grid(row=2, column=3)
        self.r4.grid(row=3, column=0)
        self.r5.grid(row=4, column=4)

    def announce_winner(self, data):
        """Declare the winner by displaying a tkinter messagebox.

        :param string data: The data to be displayed in the messagebox.
        """
        messagebox.showinfo("Winner Announcement", message=data)