def initialize(self):
        plot_axes = [0, self.baseline_cost, 0, 1]
        self.plot_frame = PlotFrame(self, "Quality of Solution", \
                                plot_axes, "dodgerblue", "Poor", "Perfect")
        self.plot_frame.grid(row=0, column=0, sticky=(N))

        self.num_tries_title = Label(self, text="Number of Attempts Made",
                                     font=("Optima Italic", 24), fg="gray")
        self.num_tries_title.grid(row=1, column=0, sticky=(NW), pady=(20, 0))

        self.num_tries_var = StringVar()
        self.num_tries_var.set('__')
        self.num_tries = Label(self, textvariable=self.num_tries_var,
                          font=("Optima Bold", 24), foreground="gray")
        self.num_tries.grid(row=2, column=0, columnspan=2, sticky=(S),
                            pady=(20, 20))


        self.pause_var = StringVar()
        self.pause_var.set('Pause')
        self.pause_button = Button(self, textvariable=self.pause_var,
                                   state='disabled',
                                   command=lambda: self.input_frame.pause_or_resume(),
                                   width=10, pady=20)
        self.pause_button.grid(row=9, column=0)


        self.reset_button = Button(self, text="Reset", state='disabled',
                                   command=lambda: self.input_frame.reset(), 
                                   width=10)
        self.reset_button.grid(row=9, column=1)
Пример #2
0
    def __init__(self, x):
        LabelFrame.__init__(self, x)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10)

        self.config(relief=GROOVE)
        self.config(borderwidth=2)
        self.config(text = "Up Time")
        self.config(labelanchor = "n")
        
        self.Hsv = StringVar()
        self.Hsv.set("")
        self.Hlabel = Label(self, textvariable = self.Hsv)
        self.Hlabel.grid(row=0, column=0, sticky="wens")
        self.Hlabel.config(font=("Courier", 14))
        
        self.Msv = StringVar()
        self.Msv.set("")
        self.Mlabel = Label(self, textvariable = self.Msv)
        self.Mlabel.grid(row=1, column=0, sticky="wens")
        self.Mlabel.config(font=("Courier", 14))
        
        self.Ssv = StringVar()
        self.Ssv.set("")
        self.Slabel = Label(self, textvariable = self.Ssv)
        self.Slabel.grid(row=2, column=0, sticky="wens")
        self.Slabel.config(font=("Courier", 14))

        self.pack()
Пример #3
0
 def initialize_buttons(self):
     deposit_money = self.add_button(self.frame_left, width=20, 
                     compound=LEFT, text="deposit money",
                     command= lambda: self.main_actions.deposit_money_runner(self.ROOT))
     withdraw_money = self.add_button(self.frame_left, width=20, 
                     compound=LEFT, text="withdraw money",
                     command= lambda: self.main_actions.withdraw_money_runner(self.ROOT))
     transfer_money = self.add_button(self.frame_left, width=20,
                     compound=LEFT, text="transfer money",
                     command= lambda: self.main_actions.transfer_money_runner(self.ROOT))
     exit = self.add_button(self.frame_left, width=20, compound=LEFT, 
                     text="exit", command=self.ROOT.destroy)
     check_account = self.add_button(self.frame_left, width=20, 
                     compound=LEFT, text="check account", 
                     command= lambda: self.main_actions.check_account_runner(self.ROOT))
     deposit_money.pack()
     withdraw_money.pack()
     transfer_money.pack()
     check_account.pack()
     exit.pack()
     var = StringVar()
     text_area = self.add_label(self.frame_right, height=100, width=60, 
                     compound=TOP, textvariable=var, relief=RAISED)
     var.set("how are you")
     text_area.pack()
Пример #4
0
    def __init__(self, parent, projects, onCreation=None):
        Frame.__init__(self, parent)

        self.onCreation = onCreation

        self.time = StringVar()
        self.time.set("00:00:00")
        self.timeEntry = None

        self.projects = projects.values()
        self.projects.sort(key=lambda x: x.name)

        l = Label(self, text="Description")
        l.grid(row=0, column=0)

        self.description = StringVar()
        e = Entry(self, textvariable=self.description, font=("Helvetica", 16))
        e.grid(row=1, column=0)

        l = Label(self, text="Project")
        l.grid(row=0, column=1)

        values = map(lambda x: x.name, self.projects)
        self.projectChooser = Combobox(self, values=values, font=("Helvetica", 16))
        self.projectChooser.grid(row=1, column=1)

        self.timeEntryClock = Label(self, textvariable=self.time, font=("Helvetica", 16))
        self.timeEntryClock.grid(row=1, column=2)

        self.submitText = StringVar()
        self.submitText.set("Start")
        self.submit = Button(self, textvariable=self.submitText, command=self.start, font=("Helvetica", 16))
        self.submit.grid(row=1, column=3, padx=10)
Пример #5
0
class VelocitySelect(Frame):
    VELOCITIES = [speeds.kmh, speeds.mih, speeds.ms]

    def __init__(self, **kwargs):
        master = None if 'master' not in kwargs else kwargs['master']
        Frame.__init__(self, master)
        Label(text='Output Velocity').grid(row=0, column=0, sticky=W,
                                           in_=self)
        self.vel = VelocitySelect.VELOCITIES[0]
        self.vel_selected = StringVar()
        vel_opts = ['%s (%s)' % (sp.name, sp.symbol)
                    for sp in VelocitySelect.VELOCITIES]
        self.velopt = OptionMenu(self, self.vel_selected, *vel_opts)
        self.vel_selected.set('%s (%s)' % (self.vel.name, self.vel.symbol))
        self.velopt.grid(row=0, column=1, sticky=W)

    def val(self, val=None):
        if val is not None:
            self.vel.value = val
        else:
            sel = self.vel_selected.get().split()[0]
            for v in VelocitySelect.VELOCITIES:
                if sel in v.name:
                    self.vel = v
        return self.vel
Пример #6
0
 def __init__(self, canvas, paramobj):
     super(TkMutationStrip,self).__init__()
     self.paramobj = paramobj
     self.frame = factory.frame(canvas)
     lab_param = factory.label(self.frame, "%-16s" % paramobj.param)
     lab_param.config(width=17)
     lab_prob = factory.label(self.frame, "P")
     lab_range = factory.label(self.frame, "R")
     self.var_prob = StringVar()
     self.var_prob.set(10)   # as int percent 0..100
     self.var_range = StringVar()
     self.var_range.set(1)   # as int percent 0..100
     
     spin_prob = factory.int_spinbox(self.frame,
                                       self.var_prob,0.0,100,
                                       self._set_probability)
     spin_prob.config(width=6)
     spin_range = factory.int_spinbox(self.frame,
                                        self.var_range,0.0,100,
                                        self._set_range)
     spin_range.config(width=6)
     
     lab_param.grid(row=1,column=0, sticky="w", padx=4)
     lab_prob.grid(row=1,column=1, sticky="w", padx=4)
     spin_prob.grid(row=1,column=2, sticky="w", padx=4)
     lab_range.grid(row=1,column=3, sticky="w", padx=4)
     spin_range.grid(row=1,column=4, sticky="w", padx=4)
Пример #7
0
 def initializeComponents(self):
     self.boxValue = StringVar()
     self.boxValue.trace('w', \
         lambda name, index, mode, \
         boxValue = self.boxValue : \
         self.box_valueEditted(boxValue))
         
     self.box = Combobox(self,\
         justify = 'left',\
         width = 50, \
         textvariable = self.boxValue,\
     )
     self.box.pack(side = 'left',expand = 1, padx = 5, pady = 5)
     self.box.bind('<<ComboboxSelected>>',self.box_selected)
     self.box.bind('<Return>',self.box_returned)
     
     self.importButton = Button(self, \
         text = "Import", \
         command = self.importButton_clicked,\
     )
     self.importButton.pack(side = 'left',expand = 1)
     
     self.cmd_str = StringVar(None,"Prefix Only")
     self.switchButton = Button(self, \
         textvariable = self.cmd_str, \
         command = self.switchButton_clicked, \
     )
     self.switchButton.pack(side = 'right', padx = 5, pady = 5)
Пример #8
0
class WheelEntry(LabelFrame):
    DIA_UNITS = [dist.mm, dist.cm, dist.inch]

    def __init__(self, **kwargs):
        master = None if 'master' not in kwargs else kwargs['master']
        LabelFrame.__init__(self, master, text='Wheel')
        self.unitopts = ['%s (%s)' % (x.name, x.symbol)
                         for x in WheelEntry.DIA_UNITS]
        self.__val = WheelEntry.DIA_UNITS[0]
        self.createSpin()
        self.create_unit_opts()

    def create_unit_opts(self):
        self.unitoptselected = StringVar()
        self.unitoptselected.set(self.unitopts[2])
        self.unitopt = OptionMenu(self, self.unitoptselected, *self.unitopts)
        self.unitopt.grid(row=1, column=1, in_=self)
        self.val()

    def val(self, val=None):
        if val is not None:
            self.__val.value = val
        else:
            sel = self.unitoptselected.get().split()[0]
            for u in WheelEntry.DIA_UNITS:
                if sel in u.name:
                    self.__val = u
                    self.__val.value = int(self.Spin.val.get())
        return self.__val

    def createSpin(self):
        self.Spin = LabeledSpin(title='Dia')
        self.Spin.val.set(27)
        self.Spin.Spin.config(from_=10, to=1000, width=4)
        self.Spin.grid(row=1, column=0, in_=self)
Пример #9
0
    def __init__(self, master=None):
        Observable.__init__(self)
        hashText = StringVar()
        
        hashText.trace("w", lambda nm, idx, mode, var=hashText: self.textChanged(hashText))

        Entry.__init__(self, master, textvariable = hashText)
Пример #10
0
    def __init__(self, master, customers, payments, refresh):
        Toplevel.__init__(self,master)

        self.root = master
        self.refresh = refresh

        self.title("Check In")
        self.iconname = "Check In"

        self.name = StringVar() # variable for customer
        self.customers = customers # customers object
        self.payments = payments
        self.names = []
        self.workout = StringVar()
        self.workouts = []
        self.workouts_form = []
        self.date = StringVar()
        self.date.set(strftime("%m/%d/%Y"))
        self.refresh_time = 15 # in minutes
        self.output = '' # for the output label at the bottom
        self.schedule = Schedule()

        self.logger = Logger() #throws IOError if file is open

        inf = Frame(self)
        inf.pack(padx=10,pady=10,side='top')
        Label(inf, text="Name:").grid(row=0,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text='Date:').grid(row=1,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text="Workout:").grid(row=2,column=0,sticky=E,ipady=2,pady=2,padx=10)

        self.name_cb = Combobox(inf, textvariable=self.name, width=30,
                                values=self.names)
        self.name_cb.grid(row=0,column=1,sticky=W,columnspan=2)
        self.date_ent = Entry(inf, textvariable=self.date)
        self.date_ent.grid(row=1,column=1,sticky=W)
        self.date_ent.bind('<FocusOut>', self.update_workouts)
        Button(inf,text='Edit', command=self.enable_date_ent).grid(row=1,column=2,sticky=E)
        self.workout_cb = Combobox(inf, textvariable=self.workout, width=30,
                                   values=self.workouts_form,state='readonly')
        self.workout_cb.grid(row=2,column=1,sticky=W,columnspan=2)

        self.log_btn=Button(inf,text="Log Workout",command=self.log,width=12)
        self.log_btn.grid(row=3,column=1,columnspan=2,pady=4,sticky='ew')
        
        stf = Frame(self)
        stf.pack(padx=10,pady=10,fill='x',side='top')
        self.scrolled_text = ScrolledText(stf,height=15,width=50,wrap='word',state='disabled')
        self.scrolled_text.pack(expand=True,fill='both')

        self.update_workouts()
        self.update_names()

        self.bind('<Return>',self.log)
        self.name_cb.focus_set()  # set the focus here when created

        #disable the date field
        self.disable_date_ent()

        #start time caller
        self.time_caller()
Пример #11
0
 def CreateWidgets(self):
     self.menu = StringVar(self)
     self.path = StringVar(self)
     self.fontSize = StringVar(self)
     self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
     self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
     labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
                       text='Menu Item:')
     self.entryMenu = Entry(self.frameMain, textvariable=self.menu,
                            width=30)
     self.entryMenu.focus_set()
     labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
                       text='Help File Path: Enter URL or browse for file')
     self.entryPath = Entry(self.frameMain, textvariable=self.path,
                            width=40)
     self.entryMenu.focus_set()
     labelMenu.pack(anchor=W, padx=5, pady=3)
     self.entryMenu.pack(anchor=W, padx=5, pady=3)
     labelPath.pack(anchor=W, padx=5, pady=3)
     self.entryPath.pack(anchor=W, padx=5, pady=3)
     browseButton = Button(self.frameMain, text='Browse', width=8,
                           command=self.browseFile)
     browseButton.pack(pady=3)
     frameButtons = Frame(self)
     frameButtons.pack(side=BOTTOM, fill=X)
     self.buttonOk = Button(frameButtons, text='OK',
                            width=8, default=ACTIVE,  command=self.Ok)
     self.buttonOk.grid(row=0, column=0, padx=5,pady=5)
     self.buttonCancel = Button(frameButtons, text='Cancel',
                                width=8, command=self.Cancel)
     self.buttonCancel.grid(row=0, column=1, padx=5, pady=5)
Пример #12
0
 def __init__(self, interface, toplevel=False, start_t=False, stop_t=False):
     '''
     '''
     self.abort = False
     if not start_t:
         start_t = datetime.utcnow() - timedelta(hours=2)
     if not stop_t:
         stop_t = datetime.utcnow()
     self.update_pending = False
     self.pype = interface
     self.plot_dicts = {}
     if isinstance(start_t, datetime):
         self.start_t = StringVar(value=start_t.strftime(time_format))
     elif isinstance(start_t, str):
         self.start_t = StringVar(value=start_t)
     else:
         raise TypeError('start_t must be string or datetime')
     if isinstance(stop_t, datetime):
         self.stop_t = StringVar(value=stop_t.strftime(time_format))
     elif isinstance(stop_t, str):
         self.stop_t = StringVar(value=stop_t)
     else:
         raise TypeError('stop_t must be string or datetime')
     self.time_interval = [self.start_t.get(), self.stop_t.get()]
     self.ymin = DoubleVar()
     self.ymax = DoubleVar()
     if toplevel:
         self.toplevel = toplevel
     else:
         self.toplevel = Tk.Tk()
     self.status_var = StringVar(value='initializing')
     self._SetupCanvas()
     self._BuildGui()
     if not toplevel:
         Tk.mainloop()
Пример #13
0
class ComboBox(Control):
    def __init__(self, parent, **kwargs):
        Control.__init__(self, TkComboBox(parent._frame), **kwargs)
        self._items = ComboItems(self)
        self._combotext = StringVar(self._ctrl)
        self._control_set('exportselection', 0)
        self._control_set('textvariable', self._combotext)

    @property
    def items(self):
        return self._items

    @property
    def text(self):
        return self._combotext.get()

    @text.setter
    def text(self, value):
        self._combotext.set(value)

    @property
    def readonly(self):
        return 'readonly' in self._control_get('state')

    @readonly.setter
    def readonly(self, value):
        if self.readonly == value:
            return
        elif value:
            self._control_set('state', 'readonly')
        else:
            self._control_set('state', 'normal')
class TexteeStatusBar(Frame):
	def __init__(self, master):
		Frame.__init__(self, master)
		self.update_interval = 100 # updat the statusbar with line numbers after every 100ms
		self.status_label_variable = StringVar()
		font = tkFont.Font(self.master, family='Arial', size='10')
		self.status_label = Label(self, relief=SUNKEN, bd=1, textvariable=self.status_label_variable, anchor='w', font=font)
		self.status_label.pack(fill=X) # this will pack the label within the status bar, statusbar needs to be packed when needed
		self.pack(side=BOTTOM, fill=X)

	def display(self, flag):
		self.show() if flag else self.hide()

	def hide(self):
		self.pack_forget()
	
	def show(self):
		# TODO : this is not working after hiding, it works on the child label but not parent. fix it later
		self.pack(side=BOTTOM, fill=X)

	def update_status(self, message):
		self.status_label_variable.set(message)

	def appened_status(self, message):
		updated_status = self.status_label_variable.get() + ' %s' % (message)
		self.status_label_variable.set(updated_status) 

	def timeout_status(self, message, timeout=5):
		# TODO : display the previous status after tempory timeout status message
		pass
		
	# TODO :use to display back the old value after displaying temporary value
	def reset_status(self):
		pass
Пример #15
0
    def get_box(self):
        if not self.dialog:
            from Tkinter import Tk,Listbox,Button,Scrollbar,X,Y,BOTTOM,RIGHT,HORIZONTAL,VERTICAL,OptionMenu,StringVar
            self.dialog = Tk()
            self.dialog.title("TODO")
            scrollbar = Scrollbar(self.dialog,orient=HORIZONTAL)
            yscrollbar = Scrollbar(self.dialog,orient=VERTICAL)
            self.todolist = Listbox(self.dialog,width=50,xscrollcommand=scrollbar.set,yscrollcommand=yscrollbar.set)
            scrollbar.config(command=self.todolist.xview)
            scrollbar.pack(side=BOTTOM,fill=X)
            yscrollbar.config(command=self.todolist.yview)
            yscrollbar.pack(side=RIGHT,fill=Y)
            self.todolist.pack(side="left",fill="both",expand=True)
            
            cat_list_name = StringVar()
            cat_list_name.set("Category")
            

            btn = Button(self.dialog,text="Refresh",command=self.refresh_list)
            btn.pack()
            
            self.refresh_list()
            if self.categories:
                self.cat_list = OptionMenu(self.dialog,cat_list_name,*(self.categories+["ALL","NONE"]),command=self.filter_list)
                self.cat_list.pack()
        
        return (self.dialog,self.todolist)
Пример #16
0
    def __init__(self, x):
        LabelFrame.__init__(self, x)       
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=12)
        self.config(relief=GROOVE)
        self.config(borderwidth=2, padx=5, pady=5)
        self.config(text = "Encoder")
        self.config(labelanchor = "n")

        self.INSTRUCTION = StringVar()
        self.INSTRUCTION.set("Instruction")
        
        self.machinecode = StringVar()
        self.machinecode.set("")

        self.codeEntry = Entry(self, textvariable=self.INSTRUCTION)

        #self.codeEntry.configure(font=("Helvetica", 12), width=40)
        self.codeEntry.configure(width=40)

        self.codeButton = Button(self, text="Compile")

        self.VHPL = Label(self, text="VHPL")

        self.codeButton.grid(row=0, column=0, rowspan=4, sticky="wens")

        self.VHPL.grid(row=0, column=1, sticky="wens")
        self.VHPL.config(relief=GROOVE, borderwidth=2)
        
        self.codeEntry.grid(row=1, column=1, sticky="wens")
        self.codeEntry.config(fg="green", bg="black")
        
        self.pack()
Пример #17
0
class UnitPanel(CtxSubPanel):
	
	name='UnitPanel'	
	
	def __init__(self, parent):
		CtxSubPanel.__init__(self, parent)
		self.my_changes=0
		
		self.var_unit = StringVar(self.mw.root)
		self.var_unit.set(config.preferences.default_unit)
		
		label = TLabel(self.panel, text=_("Units:"))
		label.pack(side = LEFT, padx=2)
		self.entry_width = TCombobox(self.panel, state='readonly', postcommand = self.applyUnits, 
									 values=self.make_units(), width=4, style='ComboNormal', textvariable=self.var_unit)
		self.entry_width.pack(side = LEFT, padx=2)
		
		config.preferences.Subscribe(CHANGED, self.update)
		
	def applyUnits(self):
		self.my_changes=1
		config.preferences.default_unit=self.var_unit.get()
	
	def update(self,event, event2):	
		if self.my_changes:
			self.my_changes=0
		else:
			self.var_unit.set(config.preferences.default_unit)
	
	def make_units(self):
		units_tuple=()
		for unit in unit_names:
			units_tuple+=(unit,)		
		return units_tuple
			
Пример #18
0
 def input_select_dropdown(self, e):
     var = StringVar(master=self.frame)
     self.master.serialized[e.name] = lambda: var.get()
     if e.default is not None:
         var.set(e.default)
     w = OptionMenu(self.frame, var, *e.options)
     self.pack_element(w)
Пример #19
0
    def initialize(self):
        self.grid()
        self.entryVariable = StringVar()
        self.entry = Entry(self, textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)

        button = Button(self,text="Set Brake", command=self.OnButtonClick)
        button.grid(column=1,row=0)

        self.labelVariable = StringVar()
        label = Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="red")
        label.grid(column=0,row=1,columnspan=1,sticky='EW')
        self.labelVariable.set("Start..")

        onButton = Button(self,text="Brake On", command=self.BrakeOn)
        onButton.grid(column=0,row=3)

        offButton = Button(self,text="Brake Off", command=self.BrakeOff)
        offButton.grid(column=1,row=3)

        self.brakeVariable = StringVar()
        brakeState = Label(self,textvariable=self.brakeVariable,
                           anchor="w",fg="white",bg="red")
        brakeState.grid(column=0,row=2,columnspan=1,sticky='EW')
        self.brakeVariable.set("Start..")
         
        self.grid_columnconfigure(0,weight=1)
        self.update()
        #self.geometry(self.geometry()) # caused busy wait?
        self.entry.focus_set()
Пример #20
0
    def __init__(self, image):
        self.original = image
        self.image = image.copy()
        self.window = Tk()

        self.genViews()
        self.currentView = StringVar(self.window)
        self.currentView.set('Original')
        options = self.filters.keys();options.sort()
        self.views = OptionMenu(self.window, self.currentView,
                *options, command=self.applyFilter)
        self.views.pack()

        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage = Label(image=self.tkImage)
        self.lblImage.bind('<Button-1>', self.displayInfos)
        self.lblImage.bind('<Button-3>', self.save)
        self.lblImage.image = self.tkImage
        self.lblImage.pack()

        self.status = StringVar()
        self.lblStatus = Label(textvariable=self.status, justify='right')
        self.lblStatus.pack()

        self.window.mainloop()
Пример #21
0
class HostBox(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        
        self.labelHost = Label(self, text = "Host: http://")
        self.entryHost = Entry(self, width = 20)
        self.labelUrl = Label(self, text = "Url:")
        self.entryUrl = Entry(self, width = 20)
        self.labelPort = Label(self, text = "Port:")
        self.port = StringVar()
        self.port.set("80")
        self.entryPort = Entry(self, width = 8, textvariable = self.port)
        self.__boxComponents()
    
    def __boxComponents(self):
        self.labelHost.grid(row = 0, column = 0)
        self.entryHost.grid(row = 0, column = 1)
        self.labelUrl.grid(row = 1, column = 0)
        self.entryUrl.grid(row = 1, column = 1)
        self.labelPort.grid(row = 0, column = 2)
        self.entryPort.grid(row = 0, column = 3)
        
    def getHost(self):
        return self.entryHost.get()
    
    def getPort(self):
        return self.port.get()
    
    def getUrl(self):
        return self.entryUrl.get()
Пример #22
0
    def init3Voices(self):
        # [(47, 67), (52, 76), (60, 81)])
        # (B,2) - 20
        # (E,3) - 24
        # (C,4) - 25
        self.note_name = ['C','Cs','D','Ds','E','F','Fs','G','Gs','A','As','B']
        self.pitchC1 = StringVar()
        self.pitchC2 = StringVar()
        self.pitchC3 = StringVar()
        self.octave1 = IntVar()
        self.octave2 = IntVar()
        self.octave3 = IntVar()
        self.range1 = IntVar()
        self.range2 = IntVar()
        self.range3 = IntVar()


        v1Label =Label(self, text="Voice 1 start:")
        v1Label.place(x = 30, y = 25)
        self.w1 = OptionMenu(self, self.pitchC1, *self.note_name)
        self.w1.place(x = 135, y = 25)
        self.pitchC1.set(self.note_name[11])
        self.oc1 = OptionMenu(self, self.octave1, *range(1, 9))
        self.oc1.place(x=200, y=25)
        self.octave1.set(2)
        v1_rangeLabel = Label(self, text="Range:")
        v1_rangeLabel.place(x=300, y=25)
        self.rangeoption1 = OptionMenu(self, self.range1, *range(18, 26))
        self.rangeoption1.place(x=360, y=25)
        self.range1.set(20)


        v2Label = Label(self, text="Voice 2 start:")
        v2Label.place(x=30, y=50)
        self.w2 = OptionMenu(self, self.pitchC2, *self.note_name)
        self.w2.place(x=135, y=50)
        self.pitchC2.set(self.note_name[4])
        self.oc2 = OptionMenu(self, self.octave2, *range(1, 9))
        self.oc2.place(x=200, y=25 * 2)
        self.octave2.set(3)
        v2_rangeLabel = Label(self, text="Range:")
        v2_rangeLabel.place(x=300, y=25 * 2)
        self.rangeoption2 = OptionMenu(self, self.range2, *range(18, 26))
        self.rangeoption2.place(x=360, y=25 * 2)
        self.range2.set(24)


        v3Label = Label(self, text="Voice 3 start:")
        v3Label.place(x=30, y=75)
        self.w3 = OptionMenu(self, self.pitchC3, *self.note_name)
        self.w3.place(x=135, y=75)
        self.pitchC3.set(self.note_name[0])
        self.oc3 = OptionMenu(self, self.octave3, *range(1, 9))
        self.oc3.place(x=200, y=25 * 3)
        self.octave3.set(4)
        v3_rangeLabel = Label(self, text="Range:")
        v3_rangeLabel.place(x=300, y=25 * 3)
        self.rangeoption3 = OptionMenu(self, self.range3, *range(18, 26))
        self.rangeoption3.place(x=360, y=25 * 3)
        self.range3.set(25)
Пример #23
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("ListBox")
        self.pack(fill=BOTH, expand=1)

        eagles = ["Sam Bradford", "Jordan Matthews", "LeBron James", "Donnie Jones"]
        lb = Listbox(self)
        for i in eagles:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)
        self.var.set(value)
Пример #24
0
class SimpleSeparationDialog(SKModal):

	title = "Simple Separation"

	def __init__(self, master, num_colors, basename):
		self.num_colors = num_colors
		self.basename = basename
		SKModal.__init__(self, master)

	def build_dlg(self):
		self.var_name = StringVar(self.top)
		self.var_name.set(self.basename)

		frame = Frame(self.top)
		frame.pack(side = TOP, fill = BOTH, expand = 1)

		text = filename_dialog_text % self.num_colors
		label = Label(frame, text = text, justify = "left")
		label.grid(column = 0, row = 0, sticky = E, columnspan = 2)

		label = Label(frame, text = _("Basename:"))
		label.grid(column = 0, row = 1, sticky = E)
		entry = Entry(frame, width = 15, textvariable = self.var_name)
		entry.grid(column = 1, row = 1)

		frame = Frame(self.top)
		frame.pack(side = BOTTOM, fill = X, expand = 1)
		button = Button(frame, text = _("OK"), command = self.ok)
		button.pack(side = LEFT, expand = 1)
		button = Button(frame, text = _("Cancel"), command = self.cancel)
		button.pack(side = LEFT, expand = 1)

	def ok(self):
		self.close_dlg(self.var_name.get())
Пример #25
0
    def __init__(self, controller, index, title='', username='', password='', email='', location='', note=''):
        self.newPassWindow = tk.Toplevel()
        self.newPassWindow.title('Change Password')
        self.newPassWindow.geometry('400x320')
        
        self.mainController = controller
        self.index = index

        self.varTitle = StringVar()
        self.varUsername = StringVar()
        self.varPassword = StringVar()
        self.varEmail = StringVar()
        self.varLocation = StringVar()
        self.varNote = StringVar()
                
        self.__buildFrameData(title, username, password, email)
        self.__buildFramePic(location, note)
        
        self.varTitle.trace('w', self.resetTime)
        self.varUsername.trace('w', self.resetTime)
        self.varPassword.trace('w', self.resetTime)
        self.varEmail.trace('w', self.resetTime)
        self.varLocation.trace('w', self.resetTime)
        
        self.buttonSave.config(text='Change')
Пример #26
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]

    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT)  # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Пример #27
0
	def initGUI(self):
		self.parent.title("Spark Core control")
		self.pack()

		# Initialize Entry widget for device_id and access_token
		self.frmDeviceId = Frame(self)
		self.frmDeviceId.pack()
		self.lblDeviceId = Label(self.frmDeviceId, text="Device ID")
		self.lblDeviceId.pack(side=LEFT)
		self.DeviceId = StringVar()
		self.entryDeviceId = Entry(self.frmDeviceId, textvariable=self.DeviceId)
		self.DeviceId.set("53ff70066678505553201467")
		self.entryDeviceId.pack()

		self.frmAccessToken = Frame(self)
		self.frmAccessToken.pack()
		self.lblDeviceId = Label(self.frmAccessToken, text="Access Token")
		self.lblDeviceId.pack(side=LEFT)
		self.AccessToken = StringVar()
		self.entryAccessToken = Entry(self.frmAccessToken, textvariable=self.AccessToken)
		self.AccessToken.set("f107f8f0fd642b56a2cdf0e88b3bf597761de556")
		self.entryAccessToken.pack()


		self.btnTurnOnLed = Button(self, text="LED ON", command=self.turnLedOn)
		self.btnTurnOnLed.pack()
		self.btnTurnOffLed = Button(self, text="LED OFF", command=self.turnLedOff)
		self.btnTurnOffLed.pack()
Пример #28
0
    def CreateWidgets(self):
        self.menu = StringVar(self)
        self.path = StringVar(self)
        self.fontSize = StringVar(self)
        self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
        labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
            text='Menu Item:')
        self.entryMenu = Entry(self.frameMain, textvariable=self.menu)
        labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
            text='Help File Path: Enter URL or browse for file')
        self.entryPath = Entry(self.frameMain, textvariable=self.path,
            width=30)
        browseButton = Button(self.frameMain, text='Browse', width=8,
            command=self.browseFile)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='OK', width=8,
            default=ACTIVE,  command=self.Ok)
        self.buttonCancel = Button(frameButtons, text='Cancel', width=8,
            command=self.Cancel)

        self.entryMenu.focus_set()

        self.frameMain.pack(side=TOP, expand=True, fill=BOTH)
        labelMenu.pack(anchor=W, padx=5, pady=3)
        self.entryMenu.pack(anchor=W, padx=5, pady=3, fill=X)
        labelPath.pack(anchor=W, padx=5, pady=3)
        self.entryPath.pack(anchor=W, padx=5, pady=3, side=LEFT, fill=X)
        browseButton.pack(pady=3, padx=5, side=RIGHT)
        frameButtons.pack(side=BOTTOM, fill=X)
        self.buttonOk.pack(pady=5, side=RIGHT)
        self.buttonCancel.pack(padx=5, pady=5, side=RIGHT)

        if TTK:
            frameButtons['style'] = 'RootColor.TFrame'
Пример #29
0
    def initialize(self):
        self.grid()
        self.entryVariable = StringVar()
        self.entry = Entry(self, textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)

        button = Button(self,text="SPI send", command=self.OnButtonClick)
        button.grid(column=1,row=0)
        
        #ramp = Button(self,text="RAMP", command=self.setlabvar)
        #ramp.grid(column=1,row=1)        

        self.labelVariable = StringVar()
        label = Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=1,sticky='EW')
        self.labelVariable.set("Start..")
        
        self.slider = Scale(self, from_=0, to=80, orient=HORIZONTAL, 
                            command=self.setlabvar)
        self.slider.grid(column=0, row=2, columnspan=3, sticky='EW')
        
        self.PID = PIDTune(self)
        self.PID.grid(column=0, row=3, columnspan=3, sticky='EW')
        
        self.grid_columnconfigure(0,weight=1)
        self.update()
        #self.geometry(self.geometry()) # caused busy wait?
        self.entry.focus_set()
Пример #30
0
class pgmsface(LabelFrame):

    def getPGMfileName(self):
        options = {'filetypes': [('pgm files', '.pgm')]}
        f = askopenfilename(**options)
        g = f.split('/')
        self.filenameVar.set(g[len(g) - 1])
        return f

    def __init__(self, x):
        LabelFrame.__init__(self, x)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10)         
        self.config(relief=GROOVE)
        self.config(borderwidth=2)
        self.config(text = "Testing")
        self.config(labelanchor = "n")

        self.loadPGMbutton = Button(self, text="Load PGM")
        self.loadPGMbutton.grid(row=0, column=0)
        
        self.filenameVar = StringVar()
        self.filenameVar.set("*****.pgm")
        
        self.fileNameLabel = Label(self, textvariable=self.filenameVar)
        self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=18)
        self.fileNameLabel.grid(row=0, column=1)

        self.pack()
Пример #31
0
 def __init__(self, root, engine, flist):
     SearchDialogBase.__init__(self, root, engine)
     self.flist = flist
     self.globvar = StringVar(root)
     self.recvar = BooleanVar(root)
Пример #32
0
class GrepDialog(SearchDialogBase):

    title = "Find in Files Dialog"
    icon = "Grep"
    needwrapbutton = 0

    def __init__(self, root, engine, flist):
        SearchDialogBase.__init__(self, root, engine)
        self.flist = flist
        self.globvar = StringVar(root)
        self.recvar = BooleanVar(root)

    def open(self, text, searchphrase, io=None):
        SearchDialogBase.open(self, text, searchphrase)
        if io:
            path = io.filename or ""
        else:
            path = ""
        dir, base = os.path.split(path)
        head, tail = os.path.splitext(base)
        if not tail:
            tail = ".py"
        self.globvar.set(os.path.join(dir, "*" + tail))

    def create_entries(self):
        SearchDialogBase.create_entries(self)
        self.globent = self.make_entry("In files:", self.globvar)[0]

    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()

    def create_command_buttons(self):
        SearchDialogBase.create_command_buttons(self)
        self.make_button("Search Files", self.default_command, 1)

    def default_command(self, event=None):
        prog = self.engine.getprog()
        if not prog:
            return
        path = self.globvar.get()
        if not path:
            self.top.bell()
            return
        from idlelib.OutputWindow import OutputWindow  # leave here!
        save = sys.stdout
        try:
            sys.stdout = OutputWindow(self.flist)
            self.grep_it(prog, path)
        finally:
            sys.stdout = save

    def grep_it(self, prog, path):
        dir, base = os.path.split(path)
        list = self.findfiles(dir, base, self.recvar.get())
        list.sort()
        self.close()
        pat = self.engine.getpat()
        print("Searching %r in %s ..." % (pat, path))
        hits = 0
        try:
            for fn in list:
                try:
                    with open(fn) as f:
                        for lineno, line in enumerate(f, 1):
                            if line[-1:] == '\n':
                                line = line[:-1]
                            if prog.search(line):
                                sys.stdout.write("%s: %s: %s\n" %
                                                 (fn, lineno, line))
                                hits += 1
                except IOError as msg:
                    print(msg)
            print(("Hits found: %s\n"
                  "(Hint: right-click to open locations.)"
                  % hits) if hits else "No hits.")
        except AttributeError:
            # Tk window has been closed, OutputWindow.text = None,
            # so in OW.write, OW.text.insert fails.
            pass

    def findfiles(self, dir, base, rec):
        try:
            names = os.listdir(dir or os.curdir)
        except os.error as msg:
            print(msg)
            return []
        list = []
        subdirs = []
        for name in names:
            fn = os.path.join(dir, name)
            if os.path.isdir(fn):
                subdirs.append(fn)
            else:
                if fnmatch.fnmatch(name, base):
                    list.append(fn)
        if rec:
            for subdir in subdirs:
                list.extend(self.findfiles(subdir, base, rec))
        return list

    def close(self, event=None):
        if self.top:
            self.top.grab_release()
            self.top.withdraw()
Пример #33
0
class SearchEngine:
    """Handles searching a text widget for Find, Replace, and Grep."""
    def __init__(self, root):
        '''Initialize Variables that save search state.

        The dialogs bind these to the UI elements present in the dialogs.
        '''
        self.root = root  # need for report_error()
        self.patvar = StringVar(root, '')  # search pattern
        self.revar = BooleanVar(root, False)  # regular expression?
        self.casevar = BooleanVar(root, False)  # match case?
        self.wordvar = BooleanVar(root, False)  # match whole word?
        self.wrapvar = BooleanVar(root, True)  # wrap around buffer?
        self.backvar = BooleanVar(root, False)  # search backwards?

    # Access methods

    def getpat(self):
        return self.patvar.get()

    def setpat(self, pat):
        self.patvar.set(pat)

    def isre(self):
        return self.revar.get()

    def iscase(self):
        return self.casevar.get()

    def isword(self):
        return self.wordvar.get()

    def iswrap(self):
        return self.wrapvar.get()

    def isback(self):
        return self.backvar.get()

    # Higher level access methods

    def setcookedpat(self, pat):
        "Set pattern after escaping if re."
        # called only in SearchDialog.py: 66
        if self.isre():
            pat = re.escape(pat)
        self.setpat(pat)

    def getcookedpat(self):
        pat = self.getpat()
        if not self.isre():  # if True, see setcookedpat
            pat = re.escape(pat)
        if self.isword():
            pat = r"\b%s\b" % pat
        return pat

    def getprog(self):
        "Return compiled cooked search pattern."
        pat = self.getpat()
        if not pat:
            self.report_error(pat, "Empty regular expression")
            return None
        pat = self.getcookedpat()
        flags = 0
        if not self.iscase():
            flags = flags | re.IGNORECASE
        try:
            prog = re.compile(pat, flags)
        except re.error as what:
            args = what.args
            msg = args[0]
            col = arg[1] if len(args) >= 2 else -1
            self.report_error(pat, msg, col)
            return None
        return prog

    def report_error(self, pat, msg, col=-1):
        # Derived class could override this with something fancier
        msg = "Error: " + str(msg)
        if pat:
            msg = msg + "\nPattern: " + str(pat)
        if col >= 0:
            msg = msg + "\nOffset: " + str(col)
        tkMessageBox.showerror("Regular expression error",
                               msg,
                               master=self.root)

    def search_text(self, text, prog=None, ok=0):
        '''Return (lineno, matchobj) or None for forward/backward search.

        This function calls the right function with the right arguments.
        It directly return the result of that call.

        Text is a text widget. Prog is a precompiled pattern.
        The ok parameteris a bit complicated as it has two effects.

        If there is a selection, the search begin at either end,
        depending on the direction setting and ok, with ok meaning that
        the search starts with the selection. Otherwise, search begins
        at the insert mark.

        To aid progress, the search functions do not return an empty
        match at the starting position unless ok is True.
        '''

        if not prog:
            prog = self.getprog()
            if not prog:
                return None  # Compilation failed -- stop
        wrap = self.wrapvar.get()
        first, last = get_selection(text)
        if self.isback():
            if ok:
                start = last
            else:
                start = first
            line, col = get_line_col(start)
            res = self.search_backward(text, prog, line, col, wrap, ok)
        else:
            if ok:
                start = first
            else:
                start = last
            line, col = get_line_col(start)
            res = self.search_forward(text, prog, line, col, wrap, ok)
        return res

    def search_forward(self, text, prog, line, col, wrap, ok=0):
        wrapped = 0
        startline = line
        chars = text.get("%d.0" % line, "%d.0" % (line + 1))
        while chars:
            m = prog.search(chars[:-1], col)
            if m:
                if ok or m.end() > col:
                    return line, m
            line = line + 1
            if wrapped and line > startline:
                break
            col = 0
            ok = 1
            chars = text.get("%d.0" % line, "%d.0" % (line + 1))
            if not chars and wrap:
                wrapped = 1
                wrap = 0
                line = 1
                chars = text.get("1.0", "2.0")
        return None

    def search_backward(self, text, prog, line, col, wrap, ok=0):
        wrapped = 0
        startline = line
        chars = text.get("%d.0" % line, "%d.0" % (line + 1))
        while 1:
            m = search_reverse(prog, chars[:-1], col)
            if m:
                if ok or m.start() < col:
                    return line, m
            line = line - 1
            if wrapped and line < startline:
                break
            ok = 1
            if line <= 0:
                if not wrap:
                    break
                wrapped = 1
                wrap = 0
                pos = text.index("end-1c")
                line, col = map(int, pos.split("."))
            chars = text.get("%d.0" % line, "%d.0" % (line + 1))
            col = len(chars) - 1
        return None
Пример #34
0
class Launcher:
    def __init__(self, root, app, appOptions):
        self.title_prefix = "SUMO Application launcher"
        self.root = root
        self.appVar = StringVar()
        self.appVar.set(app)
        self.appOptions = appOptions
        self.optionValues = {}

        self.root.title(self.title_prefix)
        self.root.minsize(700, 200)
        numButtons = self.mainButtons()
        for i in range(numButtons):
            root.columnconfigure(i, weight=1)
        root.rowconfigure(0, weight=10)
        root.rowconfigure(1, weight=1)

        sFrame = ScrollableFrame(root)
        sFrame.grid(row=1, column="0", columnspan=numButtons, sticky="NSEW")
        self.optFrame = sFrame.frame

        self.buildAppOptions(appOptions)

        # define options for opening or saving a file
        self.file_opt = options = {}
        self.filedir = os.getcwd()
        options['defaultextension'] = 'cfg'
        options['filetypes'] = [('all files', '.*')]
        options['initialdir'] = self.filedir
        options['parent'] = root

    def buildAppOptions(self, appOptions):
        NAME, VALUE, HELP = range(3)
        row = 0
        for o in appOptions:
            row += 1
            Label(self.optFrame, text=o.name).grid(row=row,
                                                   column=NAME,
                                                   sticky="NW")
            widget, var = buildValueWidget(self.optFrame, o.type)
            self.optionValues[o.name] = var
            widget.grid(row=row, column=VALUE, sticky="NW")
            Label(self.optFrame, text=o.help, justify=LEFT).grid(row=row,
                                                                 column=HELP,
                                                                 sticky="NW")

    def mainButtons(self):
        row = 0
        col = 0
        self.buttons = []

        mb = Menubutton(self.root, text="Select Application")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        for app in APPLICATIONS:
            mb.menu.add_radiobutton(label=app,
                                    variable=self.appVar,
                                    command=self.onSelectApp)
        mb.grid(row=row, column=col, sticky="NEW")
        col += 1

        self.buttons.append(mb)
        otherButtons = (
            ("Run %12s" % self.appVar.get(), self.runApp),
            ("load Config", self.loadCfg),
            ("Save Config", self.saveCfg),
            ("Save Config as", self.saveCfgAs),
            ("Quit", self.root.quit),
        )

        for text, command in otherButtons:
            self.buttons.append(Button(self.root, text=text, command=command))
            self.buttons[-1].grid(row=row, column=col, sticky="NEW")
            col += 1
        return len(self.buttons)

    def onSelectApp(self):
        self.buttons[1].configure(text="Run %12s" % self.appVar.get())

    def runApp(self):
        subprocess.call(os.path.join(BINDIR, self.appVar.get()))

    def loadCfg(self):
        self.file_opt['title'] = 'Load configuration file'
        filename = tkFileDialog.askopenfilename(**self.file_opt)
        self.root.title(self.title_prefix + " " + filename)
        self.loadedOptions = readOptions(filename)
        for o in self.loadedOptions:
            self.optionValues[o.name].set(o.value)

    def saveCfg(self):
        pass

    def saveCfgAs(self):
        pass
    def __init__(self, port, pin1, pin2, pin3, pin4, pin5):
        # Setting up Arduino
        self.arduino = Arduino(port)

        self.servo1 = pin1
        self.servo2 = pin2
        self.servo3 = pin3
        self.servo4 = pin4
        self.servo5 = pin5

        self.arduino.digital[self.servo1].mode = SERVO
        self.arduino.digital[self.servo2].mode = SERVO
        self.arduino.digital[self.servo3].mode = SERVO
        self.arduino.digital[self.servo4].mode = SERVO
        self.arduino.digital[self.servo5].mode = SERVO

        # Setting up Database Connect
        path = 'C:/Users/Mohamad/Desktop/db/servo_2d.db'
        self.Connect = lite.connect(path)

        self.servo1OldVal = 0
        self.servo2OldVal = 0
        self.servo3OldVal = 0
        self.servo4OldVal = 0
        self.servo5OldVal = 0

        self.root = Tkinter.Tk()
        self.root.geometry('600x600')

        # GUI variables
        self.servo1Val = IntVar()
        self.servo2Val = IntVar()
        self.servo3Val = IntVar()
        self.servo4Val = IntVar()
        self.servo5Val = IntVar()

        self.pointName = StringVar()

        # GUI Components
        servo1_slider = Tkinter.Scale(self.root,
                                      label='Servo 1',
                                      length=400,
                                      from_=0, to_=360,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo1Val)
        servo1_slider.grid(column=1, row=2)

        servo2_slider = Tkinter.Scale(self.root,
                                      label='Servo 2',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo2Val)
        servo2_slider.grid(column=2, row=2)

        servo3_slider = Tkinter.Scale(self.root,
                                      label='Servo 3',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo3Val)
        servo3_slider.grid(column=3, row=2)

        servo4_slider = Tkinter.Scale(self.root,
                                      label='Servo 4',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo4Val)
        servo4_slider.grid(column=4, row=2)

        servo5_slider = Tkinter.Scale(self.root,
                                      label='Servo 5',
                                      length=400,
                                      from_=0, to_=60,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo5Val)
        servo5_slider.grid(column=5, row=2)

        self.btnSave = Button(self.root, text='Save', command=self.onSaveClicked)
        self.btnSave.grid(column=1, row=0)

        self.btnGet = Button(self.root, text='Get', command=self.onGetClicked)
        self.btnGet.grid(column=6, row=0)

        self.pName = Entry(self.root, textvariable=self.pointName)
        self.pName.grid(column=0, row=0)

        self.root.after(100, self.onSliderChange)
        self.root.mainloop()
Пример #36
0
class Calendar(ttk.Frame):
    datetime = calendar.datetime.datetime
    timedelta = calendar.datetime.timedelta

    def __init__(self, master=None, year=None, month=None,
                 firstweekday=calendar.MONDAY, locale=None,
                 activebackground='#b1dcfb', activeforeground='black',
                 selectbackground='#003eff', selectforeground='white',
                 command=None, borderwidth=1, relief="solid",
                 on_click_month_button=None):
        """
        WIDGET OPTIONS

            locale, firstweekday, year, month, selectbackground,
            selectforeground, activebackground, activeforeground,
            command, borderwidth, relief, on_click_month_button
        """

        if year is None:
            year = self.datetime.now().year

        if month is None:
            month = self.datetime.now().month

        self._selected_date = None

        self._sel_bg = selectbackground
        self._sel_fg = selectforeground

        self._act_bg = activebackground
        self._act_fg = activeforeground

        self.on_click_month_button = on_click_month_button

        self._selection_is_visible = False
        self._command = command

        ttk.Frame.__init__(self, master, borderwidth=borderwidth,
                           relief=relief)

        self.bind("<FocusIn>",
                  lambda event: self.event_generate('<<DatePickerFocusIn>>'))
        self.bind("<FocusOut>",
                  lambda event: self.event_generate('<<DatePickerFocusOut>>'))

        self._cal = get_calendar(locale, firstweekday)

        # custom ttk styles
        style = ttk.Style()
        style.layout('L.TButton', (
            [('Button.focus', {'children': [('Button.leftarrow', None)]})]
        ))
        style.layout('R.TButton', (
            [('Button.focus', {'children': [('Button.rightarrow', None)]})]
        ))

        self._font = tkFont.Font()

        self._header_var = StringVar()

        # header frame and its widgets
        hframe = ttk.Frame(self)
        lbtn = ttk.Button(hframe, style='L.TButton',
                          command=self._on_press_left_button)
        lbtn.pack(side=LEFT)

        self._header = elements.SimpleLabel(hframe, width=15, anchor=CENTER,
                                            textvariable=self._header_var)
        self._header.pack(side=LEFT, padx=12)

        rbtn = ttk.Button(hframe, style='R.TButton',
                          command=self._on_press_right_button)
        rbtn.pack(side=LEFT)
        hframe.grid(columnspan=7, pady=4)

        self._day_labels = {}

        days_of_the_week = self._cal.formatweekheader(3).split()

        for i, day_of_the_week in enumerate(days_of_the_week):
            elements.SimpleLabel(self, text=day_of_the_week,
                                 background='grey90').grid(row=1, column=i,
                                                           sticky=N + E + W + S)

        for i in range(6):
            for j in range(7):
                self._day_labels[i, j] = label = elements.SimpleLabel(self,
                                                                      background="white")

                label.grid(row=i + 2, column=j, sticky=N + E + W + S)
                label.bind("<Enter>", lambda event: event.widget.configure(
                    background=self._act_bg, foreground=self._act_fg))
                label.bind("<Leave>", lambda event: event.widget.configure(
                    background="white"))

                label.bind("<1>", self._pressed)

        # adjust its columns width
        font = tkFont.Font()
        maxwidth = max(font.measure(text) for text in days_of_the_week)
        for i in range(7):
            self.grid_columnconfigure(i, minsize=maxwidth, weight=1)

        self._year = None
        self._month = None

        # insert dates in the currently empty calendar
        self._build_calendar(year, month)

    def _build_calendar(self, year, month):
        if not (self._year == year and self._month == month):
            self._year = year
            self._month = month

            # update header text (Month, YEAR)
            header = self._cal.formatmonthname(year, month, 0)
            self._header_var.set(header.title())

            # update calendar shown dates
            cal = self._cal.monthdayscalendar(year, month)

            for i in range(len(cal)):

                week = cal[i]
                fmt_week = [('%02d' % day) if day else '' for day in week]

                for j, day_number in enumerate(fmt_week):
                    self._day_labels[i, j]["text"] = day_number

            if len(cal) < 6:
                for j in range(7):
                    self._day_labels[5, j]["text"] = ""

        if self._selected_date is not None \
                and self._selected_date.year == self._year \
                and self._selected_date.month == self._month:
            self._show_selection()

    def _find_label_coordinates(self, date):
        first_weekday_of_the_month = (date.weekday() - date.day) % 7

        return divmod((
                        first_weekday_of_the_month - self._cal.firstweekday)
                      % 7 + date.day, 7
                      )

    def _show_selection(self):
        """Show a new selection."""

        i, j = self._find_label_coordinates(self._selected_date)

        label = self._day_labels[i, j]

        label.configure(background=self._sel_bg, foreground=self._sel_fg)

        label.unbind("<Enter>")
        label.unbind("<Leave>")

        self._selection_is_visible = True

    def _clear_selection(self):
        """Show a new selection."""
        i, j = self._find_label_coordinates(self._selected_date)

        label = self._day_labels[i, j]
        label.configure(background="white", foreground="black")

        label.bind("<Enter>", lambda event: event.widget.configure(
            background=self._act_bg, foreground=self._act_fg))
        label.bind("<Leave>",
                   lambda event: event.widget.configure(background="white"))

        self._selection_is_visible = False

    # Callback

    def _pressed(self, evt):
        """Clicked somewhere in the calendar."""

        text = evt.widget["text"]

        if text == "":
            return

        day_number = int(text)

        new_selected_date = datetime.datetime(self._year, self._month,
                                              day_number)
        if self._selected_date != new_selected_date:
            if self._selected_date is not None:
                self._clear_selection()

            self._selected_date = new_selected_date

            self._show_selection()

        if self._command:
            self._command(self._selected_date)

    def _on_press_left_button(self):
        self.prev_month()

        if self.on_click_month_button is not None:
            self.on_click_month_button()

    def _on_press_right_button(self):
        self.next_month()

        if self.on_click_month_button is not None:
            self.on_click_month_button()

    def select_prev_day(self):
        """Updated calendar to show the previous day."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date - self.timedelta(days=1)

        self._build_calendar(self._selected_date.year,
                             self._selected_date.month)  # reconstruct calendar

    def select_next_day(self):
        """Update calendar to show the next day."""

        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date + self.timedelta(days=1)

        self._build_calendar(self._selected_date.year,
                             self._selected_date.month)  # reconstruct calendar

    def select_prev_week_day(self):
        """Updated calendar to show the previous week."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date - self.timedelta(days=7)

        self._build_calendar(self._selected_date.year,
                             self._selected_date.month)  # reconstruct calendar

    def select_next_week_day(self):
        """Update calendar to show the next week."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date + self.timedelta(days=7)

        self._build_calendar(self._selected_date.year,
                             self._selected_date.month)  # reconstruct calendar

    def select_current_date(self):
        """Update calendar to current date."""
        if self._selection_is_visible: self._clear_selection()

        self._selected_date = datetime.datetime.now()
        self._build_calendar(self._selected_date.year,
                             self._selected_date.month)

    def prev_month(self):
        """Updated calendar to show the previous week."""
        if self._selection_is_visible: self._clear_selection()

        date = self.datetime(self._year, self._month, 1) - self.timedelta(
            days=1)
        self._build_calendar(date.year, date.month)  # reconstuct calendar

    def next_month(self):
        """Update calendar to show the next month."""
        if self._selection_is_visible: self._clear_selection()

        date = self.datetime(self._year, self._month, 1) + \
               self.timedelta(
                   days=calendar.monthrange(self._year, self._month)[1] + 1)

        self._build_calendar(date.year, date.month)  # reconstuct calendar

    def prev_year(self):
        """Updated calendar to show the previous year."""

        if self._selection_is_visible: self._clear_selection()

        self._build_calendar(self._year - 1,
                             self._month)  # reconstruct calendar

    def next_year(self):
        """Update calendar to show the next year."""

        if self._selection_is_visible: self._clear_selection()

        self._build_calendar(self._year + 1,
                             self._month)  # reconstruct calendar

    def get_selection(self):
        """Return a datetime representing the current selected date."""
        return self._selected_date

    selection = get_selection

    def set_selection(self, date):
        """Set the selected date."""
        if self._selected_date is not None and self._selected_date != date:
            self._clear_selection()

        self._selected_date = date

        self._build_calendar(date.year, date.month)  # reconstruct calendar
Пример #37
0
 def test_get_null(self):
     v = StringVar(self.root, "abc\x00def", "name")
     self.assertEqual("abc\x00def", v.get())
     self.root.globalsetvar("name", "val\x00ue")
     self.assertEqual("val\x00ue", v.get())
Пример #38
0
def LeftFrame_Up(Frame_Left_Up, ListTest):
    global FrameListTest
    FrameListTest = ListTest
    #####--a
    Lable_a = Label(Frame_Left_Up, text='(a)网关向运营平台注册      ', width=20)
    Lable_a.grid(row=0, column=0, sticky=W)
    global Lable_a_list
    Lable_a_list = StringVar()
    Lable_a2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_a_list)
    Lable_a_list.set("未设置")
    Lable_a2["values"] = ("未设置", "返回0同时返回ChallengeCode。", "平台响应超时或返回-1。",
                          "返回-2时,表示网关提交信息不合法。", "返回-5时,网关开始重新注册。")  #注册OLT选择
    Lable_a2.bind("<<ComboboxSelected>>", Get_Lable_a_list)  #
    Lable_a2.grid(row=0, column=1, sticky=W)  # sticky=(W, E)靠左还是靠右
    ###---b
    Lable_b = Label(Frame_Left_Up, text='(b)网关向运营平台注册2    ', width=20)
    Lable_b.grid(row=1, column=0, sticky=W)
    global Lable_b_list
    Lable_b_list = StringVar()
    Lable_b2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_b_list)
    Lable_b_list.set("未设置")
    Lable_b2["values"] = ("未设置", "返回2,UserID相同,", "返回3,UserID不相同或不存在",
                          "平台响应超时,网关重新发起平台注册。", "返回-2时,静默150分钟",
                          "返回-5时,网关开始重新注册。")  #注册OLT选择
    Lable_b2.bind("<<ComboboxSelected>>", Get_Lable_b_list)
    Lable_b2.grid(row=1, column=1, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---c
    Lable_c = Label(Frame_Left_Up,
                    text='(c)心跳保活                     ',
                    width=20)
    global Lable_c_list
    Lable_c_list = StringVar()
    Lable_c2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_c_list)
    Lable_c_list.set("未设置")
    Lable_c2["values"] = ("未设置", "保持正常心跳,间隔30秒", "如果30秒内没有收到回复",
                          "返回-3,需要网关重新向平台注册", "返回-5,网关重新连接其它服务器")  #注册OLT选择
    Lable_c2.bind("<<ComboboxSelected>>", Get_Lable_c_list)
    Lable_c.grid(row=2, column=0, sticky=W)
    Lable_c2.grid(row=2, column=1, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---d
    Lable_d = Label(Frame_Left_Up, text='(d)反向触发网关到插件中心', width=20)
    Lable_d.grid(row=3, column=0, sticky=W)
    global Lable_d_list
    Lable_d_list = StringVar()
    Lable_d2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_d_list)
    Lable_d_list.set("未设置")
    Lable_d2["values"] = ("未设置", "正常流程测试", "平台返回-1,重新开始网关向平台注册")  #注册OLT选择
    Lable_d2.bind("<<ComboboxSelected>>", Get_Lable_d_list)
    Lable_d2.grid(row=3, column=1, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---e
    Lable_e = Label(Frame_Left_Up, text='(e)反向触发网关重新注册   ', width=20)
    Lable_e.grid(row=4, column=0, sticky=W)
    global Lable_e_list
    Lable_e_list = StringVar()
    Lable_e2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_e_list)
    Lable_e_list.set("未设置")
    Lable_e2["values"] = ("未设置", "正常流程测试", "平台返回-1,重新开始网关向平台注册")  #注册OLT选择
    Lable_e2.bind("<<ComboboxSelected>>", Get_Lable_e_list)
    Lable_e2.grid(row=4, column=1, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---f
    Lable_f = Label(Frame_Left_Up, text='(f)反向触发网关重新注册   ', width=20)
    Lable_f.grid(row=5, column=0, sticky=W)
    global Lable_f_list
    Lable_f_list = StringVar()
    Lable_f2 = ttk.Combobox(Frame_Left_Up, width=30, textvariable=Lable_f_list)
    Lable_f_list.set("未设置")
    Lable_f2["values"] = ("未设置", "触发网关和插件中心断开连接!")  #注册OLT选择
    Lable_f2.bind("<<ComboboxSelected>>", Get_Lable_f_list)
    Lable_f2.grid(row=5, column=1, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---aa
    Lable_aa = Label(Frame_Left_Up, text='(a)网关向分发平台注册  ', width=20)
    Lable_aa.grid(row=0, column=2, sticky=W)
    global Lable_aa_list
    Lable_aa_list = StringVar()
    Lable_aa = ttk.Combobox(Frame_Left_Up,
                            width=30,
                            textvariable=Lable_aa_list)
    Lable_aa_list.set("未设置")
    Lable_aa["values"] = ("未设置", "返回0, 连接成功", "返回-1,不响应", "返回-2,静默150分钟再重新注册"
                          )  #注册OLT选择
    Lable_aa.bind("<<ComboboxSelected>>", Get_Lable_aa_list)
    Lable_aa.grid(row=0, column=3, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---bb
    Lable_bb = Label(Frame_Left_Up, text='(b)网关向分发平台注册2', width=20)
    Lable_bb.grid(row=1, column=2, sticky=W)
    global Lable_bb_list
    Lable_bb_list = StringVar()
    Lable_bb = ttk.Combobox(Frame_Left_Up,
                            width=30,
                            textvariable=Lable_bb_list)
    Lable_bb_list.set("未设置")
    Lable_bb["values"] = ("未设置", "返回2, 连接成功", "平台没有响应,终端应用相同服务器端口重试。",
                          "运营平台响应超时,网关向分发平台发起平台注册.", "返回-2,静默150分钟重新注册"
                          )  #注册OLT选择
    Lable_bb.bind("<<ComboboxSelected>>", Get_Lable_bb_list)
    Lable_bb.grid(row=1, column=3, sticky=W)  # sticky=(W, W)靠左还是靠右
    ###---选择远程命令:
    Lable_dd_Button = Button(Frame_Left_Up,
                             text='选择远程命令',
                             relief="groove",
                             command=OpenCmdListWindows)
    Lable_dd_Button.grid(row=3, column=2)
    global Lable_cmd_list
    Lable_cmd_list = StringVar()
    Lable_cmd = Entry(Frame_Left_Up, textvariable=Lable_cmd_list, width=28)
    Lable_cmd.grid(row=3, column=3, sticky=W)
    Lable_cmd_list.set('---请选择执行命令---')
    ###---打开系统日志
    Lable_dd_Button = Button(Frame_Left_Up,
                             text='打开系统日志',
                             relief="groove",
                             command=OpenCmdLogWindows)
    Lable_dd_Button.grid(row=5, column=2)
    ###---开始异常流程测试
    global Lable_ee_Button
    Lable_ee_Button = Button(Frame_Left_Up,
                             text='开始异常流程测试',
                             foreground="red",
                             relief="groove",
                             state='normal',
                             command=TestButton)
    Lable_ee_Button.grid(row=5, column=3)
    #Lable_ee_Button.configure(state='normal')
    ###---清空窗口
    Lable_ee_Button = Button(Frame_Left_Up,
                             text='清空窗口Log',
                             relief="groove",
                             state='normal',
                             command=CleaWindows)
    Lable_ee_Button.grid(row=5, column=4)
Пример #39
0
class BatchSolver:
    """Displays the progress of CapSim for the simulation."""
    def __init__(self, master, systems, type):
        """Constructor method."""

        self.sizeflag = 0
        self.master = master
        self.tframe = Frame(master.tframe)
        self.frame = Frame(master.frame)
        self.bframe = Frame(master.bframe)
        self.version = systems[0].version
        self.fonttype = systems[0].fonttype
        self.top = None
        self.output = None
        self.progress = StringVar(value='')  #percent complete
        self.remaintime = StringVar(value='')  #percent complete
        self.abort = IntVar()  #abort flag
        self.type = type
        self.parameters = []
        self.outputs = []
        for system in systems:
            self.parameters.append(Parameters(system))  #input system

    def make_widgets(self):
        """Makes widgets for the progress window while CapSim evaluates the
        system."""

        self.instructions1 = Label(
            self.frame, text='Please choose from the following options:')
        self.instructions2 = Label(
            self.frame,
            text=
            'Please wait while CapSim simulates transport through the system...'
        )
        self.blank1 = Label(self.frame, text=' ' * 51)
        self.blank2 = Label(self.frame, text=' ' * 51)
        self.blank3 = Label(self.frame, text='')
        self.blank4 = Label(self.frame, text='')
        self.blank5 = Label(self.frame, text='')
        self.blank6 = Label(self.frame, text='')
        self.progresswidget = Label(self.frame, textvariable=self.progress)
        self.timewidget = Label(self.frame, textvariable=self.remaintime)
        self.postwidget = Label(self.frame, text='Postprocessing...')

        self.startbutton = Button(self.frame,
                                  text='Begin Simulation',
                                  command=self.solve_system,
                                  width=20)
        self.abortbutton = Button(self.frame,
                                  text='Abort Run',
                                  command=self.abortrun,
                                  width=20)

        #show the widgets on the grid

        self.instructions1.grid(row=0, columnspan=2)
        self.blank1.grid(row=1, column=0)
        self.blank2.grid(row=1, column=1)
        self.blank3.grid(row=2)
        self.blank4.grid(row=3)
        self.startbutton.grid(row=4, columnspan=2, pady=1)

        #bind the buttons to the appropriate commands

        self.startbutton.bind('<Return>', self.solve_system)
        self.abortbutton.bind('<Return>', self.abortrun)

        self.focusbutton = self.startbutton

    def solve_system(self, event=0):
        """Makes the finite difference matrices to step forward in time, pre-
        allocates memory for the output information, clears the "run" screen,
        directs the system to the appropriate solver, and grids the "run
        progress" information and "abort" button."""

        #clear the screen and start the progress bar

        self.instructions1.grid_forget()
        self.startbutton.grid_forget()

        self.instructions2.grid(row=0, columnspan=2)
        self.progresswidget.grid(row=2, columnspan=2)
        self.blank3.grid(row=3)
        self.timewidget.grid(row=4, columnspan=2)
        self.blank4.grid(row=5)
        self.abortbutton.grid(row=6, columnspan=2)
        self.blank5.grid(row=7, columnspan=2)
        self.blank6.grid(row=8, columnspan=2)

        self.master.canvas.update()
        self.master.buttonframe.grid_forget()

        self.output = []

        start = timer.time()  #real time at t = 0

        for parameters in self.parameters:

            if self.abort.get() <> 1:

                if self.type == 'Separate': start = timer.time()

                sorp = parameters.sorp
                cons = parameters.con
                dep = parameters.dep
                tidal = parameters.tidal
                reac = parameters.reac
                bio = parameters.bio
                biomix = parameters.biomix

                variable_list = ['Cn', 'Fi', 'F', 'q', 'qm', 'W', 'Cw']

                Temp = {}
                for variable in variable_list:
                    Temp[variable] = []

                #determine the grid, time step size, and set up the equations for the
                #finite differencing

                parameters.make_uniform_grid()
                if bio == 1:
                    parameters.update_bioturbation()
                    parameters.make_grid_Dbiops()

                Fis, FisL, FisM = parameters.get_initial_component_fractions()
                Cn = parameters.get_initial_concentrations()
                Fis_plus_1 = {}
                FisL_plus_1 = {}
                FisM_plus_1 = {}
                for component in parameters.components:
                    Fis_plus_1[component.name] = [
                        Fi for Fi in Fis[component.name]
                    ]
                    FisL_plus_1[component.name] = [
                        Fi for Fi in FisL[component.name]
                    ]
                    FisM_plus_1[component.name] = [
                        Fi for Fi in FisM[component.name]
                    ]
                parameters.make_matrix_parameter_vectors(Cn, Fis, FisL)
                parameters.make_transport_parameter_vectors()
                parameters.make_reaction_parameter_vectors(Cn, Fis)
                parameters.update_time_dependents()
                parameters.make_matrices()

                output = Output(parameters)
                if output.sizeflag == 1: self.show_size_error()

                t = parameters.tstart
                n = 0

                if sorp == 1 or reac == 1:
                    parameters.update_nonlinear(Cn, Fis, FisL)

                results = output.converter(parameters, Cn, FisL)
                for variable in variable_list:
                    Temp[variable].append(
                        results[variable_list.index(variable)])

                t_start = 0
                t_end = 0

                while t < (parameters.tfinal_ori + parameters.delt *
                           (2 + parameters.steps)
                           ):  #loop through time to the simulation end

                    if dep == 1:
                        Cn, Fis_plus_1, FisL_plus_1, FisM_plus_1 = parameters.update_deposition(
                            Cn, Fis, FisL, FisM, t + parameters.delt)
                    parameters.update_time_dependents()
                    if cons == 1:
                        parameters.update_consolidation(
                            t + parameters.delt, parameters.Vdar)
                    if tidal == 1:
                        parameters.update_tidal(t + parameters.delt,
                                                parameters.U_plus_1)

                    if biomix == 1:
                        parameters.make_components_matrices()
                        Fis_plus_1, FisL_plus_1, FisM_plus_1 = parameters.get_Fis_plus_1(
                            Fis_plus_1, FisL_plus_1, FisM_plus_1)
                        parameters.make_matrix_parameter_vectors(
                            Cn, Fis_plus_1, FisL_plus_1)
                        parameters.make_reaction_parameter_vectors(
                            Cn, Fis_plus_1)

                    if (cons + tidal + biomix) > 0:
                        parameters.make_transport_parameter_vectors()

                    if (cons + tidal + dep + biomix + reac + sorp) > 0:
                        parameters.make_matrices()

                    if sorp == 1 or reac == 1:
                        Cn_plus_1 = parameters.non_linear_solver(
                            Cn, Fis_plus_1, FisL_plus_1)
                    else:
                        Cn_plus_1 = parameters.get_Cn_plus_1(Cn)

                    #collect the pertinent data from the time step
                    if parameters.averageoption == 'Instaneous':
                        if output.n < len(output.times) and round(
                                output.times[output.n], 8) < round(
                                    t + parameters.delt, 8):
                            output.store_no_dep(Cn, Cn_plus_1, t,
                                                t + parameters.delt,
                                                parameters, FisL, FisL_plus_1)
                    else:
                        new_results = output.converter(parameters, Cn_plus_1,
                                                       FisL_plus_1)
                        for variable in variable_list:
                            Temp[variable].append(
                                new_results[variable_list.index(variable)])

                        if len(Temp['Cn']) >= parameters.steps:
                            results_plus_1 = []
                            for variable in variable_list:
                                results_plus_1.append(Temp[variable][0])
                                for temp in Temp[variable][1:]:
                                    results_plus_1[
                                        -1] = results_plus_1[-1] + temp
                                results_plus_1[-1] = results_plus_1[-1] / len(
                                    Temp['Cn'])

                            t_middle = (t + parameters.delt -
                                        t_end) / 2 + t_end

                            output.store(t_start, t_middle, parameters,
                                         results, results_plus_1)

                            Temp = {}
                            for variable in variable_list:
                                Temp[variable] = []
                            results = results_plus_1
                            t_start = t_middle
                            t_end = t + parameters.delt

                    t = t + parameters.delt
                    Cn = [C for C in Cn_plus_1]
                    if biomix == 1:
                        Fis = {}
                        FisL = {}
                        FisM = {}
                        for component in parameters.components:
                            Fis[component.name] = [
                                Fi for Fi in Fis_plus_1[component.name]
                            ]
                            FisL[component.name] = [
                                Fi for Fi in FisL_plus_1[component.name]
                            ]
                            FisM[component.name] = [
                                Fi for Fi in FisM_plus_1[component.name]
                            ]

                    if self.type == 'Continuous':
                        self.progress.set(
                            'Simulation Progress: ' + str(int(t)) + ' / ' +
                            str(int(self.parameters[-1].tfinal_ori)) + ' ' +
                            self.parameters[-1].timeunit)
                        self.remaintime.set(
                            'Approximate Remaining Time: %d Seconds' %
                            ((timer.time() - start) *
                             (self.parameters[-1].tfinal - t) /
                             (t - self.parameters[0].tstart)))
                    else:
                        self.progress.set(
                            'Simulation Progress: ' +
                            str(self.parameters.index(parameters)) + ' / ' +
                            str(len(self.parameters)))
                        self.remaintime.set(
                            'Approximate Remaining Time: %d Seconds' %
                            ((timer.time() - start) * (parameters.tfinal - t) /
                             (t)))

                    self.frame.update()
                    if self.abort.get() == 1: break

                if self.abort.get() <> 1: self.outputs.append(output)

        if self.abort.get() == 0:  #checks if the abort button was invoked

            self.progresswidget.grid_forget()
            self.postwidget.grid(row=2, column=0, columnspan=3)
            self.frame.update()

        self.frame.quit()

    def abortrun(self, event=0):
        """Used to abort run."""

        if tkmb.askyesno(self.version, 'Do you really want to abort?') == 1:
            self.abort.set(1)
            self.output = None
            self.outputs = None
            self.frame.quit()

    def show_size_error(self):
        """Shows ann error if the user specifies an overly complicated system
        that requires too much memory allocation."""

        tkmb.showerror(title='Memory Error',
                       message='The parameters ' +
                       'you have specified require too much memory to be ' +
                       'computed.  Please decrease the simulation time ' +
                       'and/or the transport rates to rectify this issue.')
        self.frame.quit()
Пример #40
0
class App(object):
    def __init__(self, parent):
        self.process = None
        self.after = parent.after
        self.command = START
        self.button_text = None
        self.progressbar = None
        self.make_widgets(parent)

    def make_widgets(self, parent):
        parent = ttk.Frame(parent, padding="3 3 3 3")
        parent.pack()
        self.progressbar = ttk.Progressbar(parent,
                                           length=200,
                                           mode='indeterminate')
        self.progressbar.pack()
        self.button_text = StringVar()
        self.button_text.set(self.command)
        button = ttk.Button(parent,
                            textvariable=self.button_text,
                            command=self.toggle)
        button.pack()
        button.focus()

    def toggle(self, event_unused=None):
        if self.command is START:
            self.progressbar.start()
            try:
                self.start_process()
            except:
                self.progressbar.stop()
                raise
            self.command = STOP
            self.button_text.set(self.command)
        else:
            assert self.command is STOP
            self.stop_process()

    def stop(self):
        self.progressbar.stop()
        self.command = START
        self.button_text.set(self.command)

    def start_process(self):
        self.stop_process()
        self.process = Popen(cmd)

        def poller():
            if self.process is not None and self.process.poll() is None:
                # process is still running
                self.after(delay, poller)  # continue polling
            else:
                self.stop()

        delay = 100  # milliseconds
        self.after(delay, poller)

    def stop_process(self):
        if self.process is not None and self.process.poll() is None:
            self.process.terminate()
            # kill process in a couple of seconds if it is not terminated
            self.after(2000, kill_process, self.process)
        self.process = None
Пример #41
0
class TkLedBrd():
    #Private data
    _ledOffImage = 0
    _ledOnWhtImage = 0
    _ledOnGrnImage = 0

    ## The constructor
    #
    #  Creates the TK frame interface for the input board.  Creates a frame
    #  for each of the input bits, and an overall frame for card information.
    #
    #  @param  self          [in]   Object reference
    #  @param  brdNum        [in]   Input board instance index (base 0)
    #  @param  frmRow        [in]   Row to display LED board.  (LED boards after input/sol cards)
    #  @param  parentFrm     [in]   Parent frame
    #  @return None
    def __init__(self, brdNum, frmRow, parentFrm):
        self.brdNum = brdNum
        self.brdPos = frmRow
        self.statLbl = StringVar()
        self.prevLedState = 0x00  #1 is on, 0 is off
        self.bitFrms = []
        self.canvas = []

        if (TkLedBrd._ledOffImage == 0):
            TkLedBrd._ledOffImage = PhotoImage(file="graphics/ledOff.gif")
        if (TkLedBrd._ledOnWhtImage == 0):
            TkLedBrd._ledOnWhtImage = PhotoImage(file="graphics/ledOnWht.gif")
        if (TkLedBrd._ledOnGrnImage == 0):
            TkLedBrd._ledOnGrnImage = PhotoImage(file="graphics/ledOnGrn.gif")

        #Create main frame
        self.ledCardFrm = Frame(parentFrm, borderwidth=5, relief=RAISED)
        self.ledCardFrm.grid(column=0, row=frmRow)

        #Create card info frame
        ledCardInfoFrm = Frame(self.ledCardFrm)
        ledCardInfoFrm.grid(column=8, row=0)

        #Add card info
        tmpLbl = Label(ledCardInfoFrm, text="LED Card %d" % (brdNum + 1))
        tmpLbl.grid(column=0, row=0)
        tmpLbl = Label(ledCardInfoFrm, text="Status")
        tmpLbl.grid(column=0, row=1)
        tmpLbl = Label(ledCardInfoFrm,
                       textvariable=self.statLbl,
                       relief=SUNKEN)
        self.statLbl.set("0x%02x" % self.prevLedState)
        tmpLbl.grid(column=0, row=2)

        for i in xrange(rs232Intf.NUM_LED_PER_BRD):
            TkLedBrd.createBitFrame(self, i)

    ## Create Bit Frame function
    #
    #  Called for each bit on an LED card.
    #
    #  @param  self          [in]   Object reference
    #  @param  bit           [in]   Input bit number
    #  @return None
    def createBitFrame(self, bit):
        ledCardBitFrm = Frame(self.ledCardFrm, borderwidth=5, relief=RAISED)
        self.bitFrms.append(ledCardBitFrm)
        ledCardBitFrm.grid(column=rs232Intf.NUM_LED_PER_BRD - bit - 1, row=0)
        tmpLbl = Label(
            ledCardBitFrm,
            text="%s" %
            GameData.LedBitNames.LED_BRD_BIT_NAMES[self.brdNum][bit])
        tmpLbl.grid(column=0, row=0)

        #Graphic of LED on
        self.canvas.append(Canvas(ledCardBitFrm, width=100, height=80))
        self.canvas[bit].grid(column=0, row=1)

        if ((self.prevLedState & (1 << bit)) == 0):
            self.canvas[bit].create_image(48, 40, image=TkLedBrd._ledOffImage)
        else:
            self.canvas[bit].create_image(48,
                                          40,
                                          image=TkLedBrd._ledOnGrnImage)

    ## Update LED states
    #
    #  If the LED state has changed, the graphics are updated.
    #
    #  @param  self          [in]   Object reference
    #  @param  data          [in]   New LED state
    #  @return None
    def updateLeds(self, data):
        if (self.prevLedState != data):
            for index in xrange(rs232Intf.NUM_LED_PER_BRD):
                if ((self.prevLedState ^ data) & (1 << index)):
                    if (data & (1 << index)) != 0:
                        self.canvas[index].create_image(
                            48, 40, image=TkLedBrd._ledOnGrnImage)
                    else:
                        self.canvas[index].create_image(
                            48, 40, image=TkLedBrd._ledOffImage)
            self.prevLedState = data
            self.statLbl.set("0x%02x" % self.prevLedState)

    ## Remove images
    #
    #  Remove images so threads can be cleaned
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def removeImages(self):
        for index in xrange(rs232Intf.NUM_LED_PER_BRD):
            self.canvas[index].create_image(48, 40, image="")
Пример #42
0
    def initUI(self):

        self.parent.title("Calculator")

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

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)

        self.v = StringVar()

        entry = Entry(self, textvariable=self.v)
        entry.grid(row=0, columnspan=4, sticky=W + E)
        cls = Button(self, text="Cls")
        cls.grid(row=1, column=0)
        bck = Button(self, text="Back")
        bck.grid(row=1, column=1)
        lbl = Button(self)
        lbl.grid(row=1, column=2)
        clo = Button(self, text="Close")
        clo.grid(row=1, column=3)
        sev = Button(self, text="7")
        sev.grid(row=2, column=0)
        eig = Button(self, text="8")
        eig.grid(row=2, column=1)
        nin = Button(self, text="9")
        nin.grid(row=2, column=2)
        div = Button(self, text="/")
        div.grid(row=2, column=3)

        fou = Button(self, text="4")
        fou.grid(row=3, column=0)
        fiv = Button(self, text="5")
        fiv.grid(row=3, column=1)
        six = Button(self, text="6", command=self.addSix)
        six.grid(row=3, column=2)
        mul = Button(self, text="*")
        mul.grid(row=3, column=3)

        one = Button(self, text="1")
        one.grid(row=4, column=0)
        two = Button(self, text="2")
        two.grid(row=4, column=1)
        thr = Button(self, text="3")
        thr.grid(row=4, column=2)
        mns = Button(self, text="-")
        mns.grid(row=4, column=3)

        zer = Button(self, text="0")
        zer.grid(row=5, column=0)
        dot = Button(self, text=".")
        dot.grid(row=5, column=1)
        equ = Button(self, text="=")
        equ.grid(row=5, column=2)
        pls = Button(self, text="+")
        pls.grid(row=5, column=3)

        self.pack()
Пример #43
0
 def test_default(self):
     v = StringVar(self.root)
     self.assertEqual("", v.get())
Пример #44
0
 def test_get_null(self):
     v = StringVar(self.root, 'abc\x00def', 'name')
     self.assertEqual('abc\x00def', v.get())
     self.root.globalsetvar('name', 'val\x00ue')
     self.assertEqual('val\x00ue', v.get())
Пример #45
0
 def test_get(self):
     v = StringVar(self.root, "abc", "name")
     self.assertEqual("abc", v.get())
     self.root.globalsetvar("name", "value")
     self.assertEqual("value", v.get())
Пример #46
0
class QRReturnMainWindow(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.serial_num = StringVar()
        self.master = master
        self.results = StringVar()
        self.__initUi()

    #===========================================================================
    # Initialize and reset GUI
    #===========================================================================
    def __initUi(self):
        self.master.title('Shine Production')
        self.pack(fill=BOTH, expand=1)

        Style().configure("TFrame", background="#333")

        #Status of Test frame
        self.status_frame = LabelFrame(self, text='Status', relief=RIDGE, width=800, height=500)
        self.status_frame.place(x=20, y=20)
        
        #QR SERIAL # Frame
        self.path_frame = LabelFrame(self, text='QR Serial Code', relief=RIDGE, height=60, width=225)
        self.path_frame.place(x=400, y=550)
        entry = Entry(self.path_frame, bd=5, textvariable=self.serial_num)
        entry.place(x=50, y=5)


        #TEST RESULTS LABEL
        w = Label(self.status_frame, textvariable=self.results)
        w.place(x=50, y=50)

        #START Button
        self.start_button = Button(self, text="Start", command=self.start, height=4, width=20)
        self.start_button.place(x=100, y=550)

    def start(self):
        self.start_button.config(state=DISABLED)
        self.start_button.update()
        self.results.set("")
        self.__setStatusLabel(2)
        uiText = ""
        self.results.set(uiText)

        results = executeQRSerialSequence(self.serial_num.get())
        self.parseResults(results)
        
        self.serial_num.set("")
        self.start_button.config(state=ACTIVE)
        self.start_button.update()

    def parseResults(self, results):
        uiText = ''
        success = 1
        print results
        if results == -1:
            success = 3
            uiText += "Something wrong with connection to source meter."
        else:
            if results[SCAN_FAIL] == 1:
                success = 0
                uiText += "Couldn't find Shine \n"

            if results[CHECK_FW_FAIL] == 1:
                success = 0
                uiText += "Invalid firmware version. \n"
                
            if results[ACCEL_STREAM_FAIL] == 1:
                success = 0
                uiText += "Acceleromete data not correct. \n"

            if results[SN_DEFAULT_FAIL] == 1:
                success = 0
                uiText += "This serial # is 9876543210.\n"

            if results[SN_MISMATCH_FAIL] == 1:
                success = 0
                uiText += "Serial # scanned does not match internal (bt) serial #. \n"

            if results[TIMEOUT_FAIL] == 1:
                success = 0
                uiText += "Bluetooth connection timeout. \n"

            if results[AVG_CURRENT_FAIL] == 1:
                success = 0
                uiText += "Average operating current falls outside accepted range for this firmware. \n"

            if results[SN_DUPLICATE_FAIL] == 1:
                success = 0
                uiText += "This Shine is a duplicate serial number. \n"

            if results[RECENTLY_SYNCED_FAIL] == 1:
                success = 0
                uiText += "A Shine with this SN was synced in the past month. \n"

            if results[BATTERY_PLOT_FAIL] == 1:
                success = 0
                uiText += "Human determined battery plots failed."

            if success:
                uiText = "This Shine is in good condition!\n"

        self.results.set(uiText)
        self.__setStatusLabel(success)

    def __setStatusLabel(self, success):
        if success == 1:
            self.status_frame.config(text='SUCCESS', bg=STATUS_OK_COLOR)
        elif success == 2:
            self.status_frame.config(text='Status', bg='yellow')
        elif success == 3:
            self.status_frame.config(text='Something Wrong', bg='blue')
        else:
            self.status_frame.config(text='FAIL', bg=STATUS_ERROR_COLOR)
        self.update()
Пример #47
0
 def __init__(self, master, app):
     Toplevel.__init__(self, master)
     self.wm_title = "MIDI Channels"
     self.app = app
     self.config = app.config
     self.parser = app.ls_parser
     self._current_index = 0
     self._save_backup()
     main = factory.frame(self, modal=True)
     main.pack(expand=True)
     lab_title = factory.dialog_title_label(main,
                                            "MIDI Channels",
                                            modal=True)
     frame_list = factory.frame(main, modal=True)
     frame_list.config(width=248, height=320)
     frame_list.pack_propagate(False)
     self.listbox = factory.listbox(frame_list, command=self.select)
     self.listbox.pack(expand=True, fill=BOTH)
     self.lab_warning = factory.warning_label(main)
     self.var_name = StringVar()
     entry_name = factory.entry(main, self.var_name)
     button_bar = factory.frame(main, modal=True)
     b_refresh = factory.refresh_button(button_bar, command=self.refresh)
     b_help = factory.help_button(button_bar, command=self.display_help)
     b_accept = factory.accept_button(button_bar, command=self.accept)
     b_cancel = factory.cancel_button(button_bar, command=self.cancel)
     b_refresh.grid(row=0, column=0)
     b_help.grid(row=0, column=1)
     b_accept.grid(row=0, column=2)
     b_cancel.grid(row=0, column=3)
     lab_title.grid(row=0, column=0, columnspan=5, pady=8)
     frame_list.grid(row=1,
                     column=0,
                     rowspan=5,
                     columnspan=6,
                     padx=4,
                     pady=8)
     factory.label(main, text="Name", modal=True).grid(row=6, column=0)
     entry_name.grid(row=6,
                     column=1,
                     columnspan=4,
                     sticky=W,
                     padx=4,
                     pady=0)
     self.lab_warning.grid(row=7,
                           column=0,
                           columnspan=5,
                           sticky=W,
                           padx=4,
                           pady=8)
     button_bar.grid(row=8,
                     column=0,
                     columnspan=5,
                     sticky=EW,
                     padx=4,
                     pady=8)
     self.refresh()
     self.protocol("WM_DELETE_WINDOW", None)  # ISSUE: Not Working
     entry_name.bind('<Return>', self.change_name)
     entry_name.bind('<Down>', self.increment_selection)
     entry_name.bind('<Up>', self.decrement_selection)
     self.listbox.bind('<Down>', self.increment_selection)
     self.listbox.bind('<Up>', self.decrement_selection)
     self.grab_set()
     self.mainloop()
Пример #48
0
 def test_get(self):
     v = StringVar(self.root, 'abc', 'name')
     self.assertEqual('abc', v.get())
     self.root.globalsetvar('name', 'value')
     self.assertEqual('value', v.get())
Пример #49
0
    def __init__(self, master):
        self.initComplete = 0
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1

        # bind master to <Configure> in order to handle any resizing, etc.
        # postpone self.master.bind("<Configure>", self.Master_Configure)
        self.master.bind('<Enter>', self.bindConfigure)

        self.master.title("PyHatch GUI")
        self.master.resizable(0, 0)  # Linux may not respect this

        dialogframe = Frame(master, width=810, height=630)
        dialogframe.pack()

        self.Shortdesc_Labelframe = LabelFrame(
            dialogframe,
            text="Short Description (1-liner)",
            height="90",
            width="718")
        self.Shortdesc_Labelframe.place(x=60, y=127)

        helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold')

        self.Buildproject_Button = Button(dialogframe,
                                          text="Build Project",
                                          width="15",
                                          font=helv20)
        self.Buildproject_Button.place(x=492, y=10, width=263, height=68)
        self.Buildproject_Button.bind("<ButtonRelease-1>",
                                      self.Buildproject_Button_Click)

        self.Selectdir_Button = Button(dialogframe,
                                       text="<Select Directory>",
                                       width="15")
        self.Selectdir_Button.place(x=72, y=585, width=672, height=31)
        self.Selectdir_Button.bind("<ButtonRelease-1>",
                                   self.Selectdir_Button_Click)

        self.Author_Entry = Entry(dialogframe, width="15")
        self.Author_Entry.place(x=228, y=424, width=187, height=21)
        self.Author_Entry_StringVar = StringVar()
        self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar)
        self.Author_Entry_StringVar.set("John Doe")

        self.Classname_Entry = Entry(dialogframe, width="15")
        self.Classname_Entry.place(x=192, y=73, width=165, height=21)
        self.Classname_Entry_StringVar = StringVar()
        self.Classname_Entry.configure(
            textvariable=self.Classname_Entry_StringVar)
        self.Classname_Entry_StringVar.set("MyClass")

        self.Copyright_Entry = Entry(dialogframe, width="15")
        self.Copyright_Entry.place(x=228, y=478, width=461, height=21)
        self.Copyright_Entry_StringVar = StringVar()
        self.Copyright_Entry.configure(
            textvariable=self.Copyright_Entry_StringVar)
        self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe")

        self.Email_Entry = Entry(dialogframe, relief="sunken", width="15")
        self.Email_Entry.place(x=228, y=505, width=458, height=21)
        self.Email_Entry_StringVar = StringVar()
        self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar)
        self.Email_Entry_StringVar.set("*****@*****.**")

        self.GithubUserName_Entry = Entry(dialogframe,
                                          relief="sunken",
                                          width="15")
        self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21)
        self.GithubUserName_Entry_StringVar = StringVar()
        self.GithubUserName_Entry.configure(
            textvariable=self.GithubUserName_Entry_StringVar)
        self.GithubUserName_Entry_StringVar.set("github_user_name")

        self.Funcname_Entry = Entry(dialogframe, width="15")
        self.Funcname_Entry.place(x=192, y=100, width=157, height=21)
        self.Funcname_Entry_StringVar = StringVar()
        self.Funcname_Entry.configure(
            textvariable=self.Funcname_Entry_StringVar)
        self.Funcname_Entry_StringVar.set("my_function")

        # License values should be correct format
        LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys()))
        self.License_Entry_StringVar = StringVar()
        self.License_Entry = OptionMenu(dialogframe,
                                        self.License_Entry_StringVar,
                                        *LICENSE_OPTIONS)
        self.License_Entry.place(x=552, y=424, width=184, height=21)
        self.License_Entry_StringVar.set(LICENSE_OPTIONS[0])

        self.Mainpyname_Entry = Entry(dialogframe, width="15")
        self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21)
        self.Mainpyname_Entry_StringVar = StringVar()
        self.Mainpyname_Entry.configure(
            textvariable=self.Mainpyname_Entry_StringVar)
        self.Mainpyname_Entry_StringVar.set("main.py")

        self.Projname_Entry = Entry(dialogframe, width="15")
        self.Projname_Entry.place(x=168, y=10, width=194, height=21)
        self.Projname_Entry_StringVar = StringVar()
        self.Projname_Entry.configure(
            textvariable=self.Projname_Entry_StringVar)
        self.Projname_Entry_StringVar.set("MyProject")

        self.Shortdesc_Entry = Entry(dialogframe, width="15")
        self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48)
        self.Shortdesc_Entry_StringVar = StringVar()
        self.Shortdesc_Entry.configure(
            textvariable=self.Shortdesc_Entry_StringVar)
        self.Shortdesc_Entry_StringVar.set("My project does this")

        # Status must be correct format
        self.Status_Entry_StringVar = StringVar()
        self.Status_Entry = OptionMenu(dialogframe,
                                       self.Status_Entry_StringVar,
                                       *DEV_STATUS_OPTIONS)
        self.Status_Entry.place(x=228, y=451, width=183, height=21)
        self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0])

        self.Version_Entry = Entry(dialogframe, width="15")
        self.Version_Entry.place(x=552, y=451, width=184, height=21)
        self.Version_Entry_StringVar = StringVar()
        self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar)
        self.Version_Entry_StringVar.set("0.1.1")

        self.Author_Label = Label(dialogframe, text="Author", width="15")
        self.Author_Label.place(x=96, y=424, width=112, height=22)

        self.Classname_Label = Label(dialogframe,
                                     text="Class Name",
                                     width="15")
        self.Classname_Label.place(x=60, y=73, width=112, height=22)

        self.Copyright_Label = Label(dialogframe, text="Copyright", width="15")
        self.Copyright_Label.place(x=96, y=478, width=113, height=23)

        self.Email_Label = Label(dialogframe, text="Email", width="15")
        self.Email_Label.place(x=96, y=505, width=113, height=23)

        self.GithubUserName_Label = Label(dialogframe,
                                          text="GithubUserName",
                                          width="15")
        self.GithubUserName_Label.place(x=96, y=539, width=113, height=23)

        self.Funcname_Label = Label(dialogframe,
                                    text="Function Name",
                                    width="15")
        self.Funcname_Label.place(x=60, y=100, width=112, height=22)

        self.License_Label = Label(dialogframe, text="License", width="15")
        self.License_Label.place(x=432, y=424, width=113, height=23)

        self.Longdesc_Label = Label(dialogframe,
                                    text="Paragraph Description",
                                    width="15")
        self.Longdesc_Label.place(x=216, y=220, width=376, height=22)

        self.Mainpyname_Label = Label(dialogframe,
                                      text="Main Python File",
                                      width="15")
        self.Mainpyname_Label.place(x=48, y=37, width=112, height=22)

        self.Projname_Label = Label(dialogframe,
                                    text="Project Name",
                                    width="15")
        self.Projname_Label.place(x=48, y=10, width=112, height=22)

        self.Selectdir_Label = Label(
            dialogframe,
            text="Select the Directory Below Which to Place Your Project",
            width="15")
        self.Selectdir_Label.place(x=156, y=567, width=536, height=24)

        self.Status_Label = Label(dialogframe, text="Status", width="15")
        self.Status_Label.place(x=96, y=451, width=114, height=24)

        self.Version_Label = Label(dialogframe, text="Version", width="15")
        self.Version_Label.place(x=432, y=451, width=113, height=23)

        self.Isclass_Radiobutton = Radiobutton(dialogframe,
                                               text="Class Project",
                                               value="Class Project",
                                               width="15",
                                               anchor=W)
        self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("Class Project")
        self.RadioGroup1_StringVar_traceName = \
            self.RadioGroup1_StringVar.trace_variable("w",
                                                      self.RadioGroup1_StringVar_Callback)
        self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar)

        self.Isfunction_Radiobutton = Radiobutton(dialogframe,
                                                  text="Function Project",
                                                  value="Function Project",
                                                  width="15",
                                                  anchor=W)
        self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27)
        self.Isfunction_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        lbframe = Frame(dialogframe)
        self.Text_1_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Text_1 = Text(lbframe,
                           width="40",
                           height="6",
                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Text_1.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Text_1.pack(side=LEFT, fill=BOTH, expand=1)

        self.Text_1_frame.place(x=72, y=250, width=665, height=160)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.dirname = '<Select Directory>'
        self.Funcname_Entry.config(state=DISABLED)

        h = Hatch(projName='MyProject', mainDefinesClass='N')
        if h.author:
            self.Author_Entry_StringVar.set(h.author)
        if h.proj_license:
            self.License_Entry_StringVar.set(h.proj_license)
        if h.proj_copyright:
            self.Copyright_Entry_StringVar.set(h.proj_copyright)
        if h.email:
            self.Email_Entry_StringVar.set(h.email)
        if h.github_user_name:
            self.GithubUserName_Entry_StringVar.set(h.github_user_name)
        del h
Пример #50
0
class TkChannelNameEditor(Toplevel):
    def __init__(self, master, app):
        Toplevel.__init__(self, master)
        self.wm_title = "MIDI Channels"
        self.app = app
        self.config = app.config
        self.parser = app.ls_parser
        self._current_index = 0
        self._save_backup()
        main = factory.frame(self, modal=True)
        main.pack(expand=True)
        lab_title = factory.dialog_title_label(main,
                                               "MIDI Channels",
                                               modal=True)
        frame_list = factory.frame(main, modal=True)
        frame_list.config(width=248, height=320)
        frame_list.pack_propagate(False)
        self.listbox = factory.listbox(frame_list, command=self.select)
        self.listbox.pack(expand=True, fill=BOTH)
        self.lab_warning = factory.warning_label(main)
        self.var_name = StringVar()
        entry_name = factory.entry(main, self.var_name)
        button_bar = factory.frame(main, modal=True)
        b_refresh = factory.refresh_button(button_bar, command=self.refresh)
        b_help = factory.help_button(button_bar, command=self.display_help)
        b_accept = factory.accept_button(button_bar, command=self.accept)
        b_cancel = factory.cancel_button(button_bar, command=self.cancel)
        b_refresh.grid(row=0, column=0)
        b_help.grid(row=0, column=1)
        b_accept.grid(row=0, column=2)
        b_cancel.grid(row=0, column=3)
        lab_title.grid(row=0, column=0, columnspan=5, pady=8)
        frame_list.grid(row=1,
                        column=0,
                        rowspan=5,
                        columnspan=6,
                        padx=4,
                        pady=8)
        factory.label(main, text="Name", modal=True).grid(row=6, column=0)
        entry_name.grid(row=6,
                        column=1,
                        columnspan=4,
                        sticky=W,
                        padx=4,
                        pady=0)
        self.lab_warning.grid(row=7,
                              column=0,
                              columnspan=5,
                              sticky=W,
                              padx=4,
                              pady=8)
        button_bar.grid(row=8,
                        column=0,
                        columnspan=5,
                        sticky=EW,
                        padx=4,
                        pady=8)
        self.refresh()
        self.protocol("WM_DELETE_WINDOW", None)  # ISSUE: Not Working
        entry_name.bind('<Return>', self.change_name)
        entry_name.bind('<Down>', self.increment_selection)
        entry_name.bind('<Up>', self.decrement_selection)
        self.listbox.bind('<Down>', self.increment_selection)
        self.listbox.bind('<Up>', self.decrement_selection)
        self.grab_set()
        self.mainloop()

    def _save_backup(self):
        self._backup = []
        for i in range(16):
            c = i + 1
            name = self.config.channel_name(c)
            self._backup.append(name)

    def status(self, msg):
        self.app.main_window().status(msg)

    def warning(self, msg):
        msg = "WARNING: %s" % msg
        self.lab_warning.config(text=msg)
        self.lab_warning.update_idletasks()
        print(msg)

    def refresh(self):
        self.listbox.delete(0, END)
        for i in range(16):
            channel = i + 1
            name = self.config.channel_name(channel)
            txt = "[%2d] " % channel
            if name == "" or name == str(channel):
                pass
            else:
                txt = txt + "%s" % name
            self.listbox.insert(END, txt)

    @staticmethod
    def split_channel_name(s):
        try:
            s = s[4:].strip()
            return s
        except IndexError:
            return ""

    def select(self, *_):
        index = self.listbox.curselection()[0]
        name = self.listbox.get(index)
        name = self.split_channel_name(name)
        self.var_name.set(name)
        self._current_index = index

    def display_help(self):
        self.app.main_window().display_help("channel_name")

    def change_name(self, *_):
        self.lab_warning.config(text="")
        try:
            channel = self.listbox.curselection()[0] + 1
            new_name = self.var_name.get().strip().replace(' ', '_')
            old_name = self.config.channel_name(channel)
            stype = self.parser.what_is(new_name)
            if not stype or stype == "channel":
                self.parser.forget(old_name)
                self.parser.channel_name(channel, new_name, silent=True)
            else:
                msg = "Can not use %s '%s' as channel name" % (stype, new_name)
                self.warning(msg)
        except ValueError as err:
            self.warning(err.message)
        except IndexError:
            msg = "No channel selected"
            self.warning(msg)
        self.refresh()

    def increment_selection(self, *_):
        n = self._current_index
        n = min(15, n + 1)
        self.listbox.selection_clear(0, END)
        self.listbox.selection_set(n)
        self.select()

    def decrement_selection(self, *_):
        n = self._current_index
        n = max(0, n - 1)
        self.listbox.selection_clear(0, END)
        self.listbox.selection_set(n)
        self.select()

    def accept(self):
        msg = "MIDI Channel names changed"
        self.status(msg)
        self.destroy()

    def cancel(self):
        for i, name in enumerate(self._backup):
            self.config.channel_name(i + 1, name)
        self.status("MIDI channel name change canceled")
        self.destroy()
	def __init__(self, master):
		master.title('Univention Lizenz Generator')
		self.master = master
		self.logoframe = Frame(self.master, bg='red')
		self.logoframe.pack(side=TOP, fill=X, expand=YES)
		self.lftopframes = LabelFrame(self.master)
		self.lftopframes.pack(side=TOP, fill=X, expand=YES)
		self.lframe = Frame(self.lftopframes)
		self.rframe = Frame(self.lftopframes)
		self.lframe.pack(side=LEFT, fill=X, expand=YES)
		self.rframe.pack(side=RIGHT, fill=X, expand=YES)

		self.bframe = Frame(self.master)
		self.bframe.pack(fill=X)

		self.kname = StringVar()
		self.kname.set('test')

		self.chkevar = IntVar()
		self.chkevar.set('1')
		self.chkivar = IntVar()
		self.chkovar = IntVar()
		self.chkdvar = IntVar()

		self.exday = StringVar()
		self.exmonth = StringVar()
		self.exyear = StringVar()
		self.getdate()  # set date to localdate (month+3)

		try:
			self.logo = PhotoImage(file='/var/www/head_logo.gif')
		except TclError:  # fall back to 64x64 white
			self.logo = PhotoImage(data='R0lGODdhQABAAIAAAP///wAAACwAAAAAQABAAAACRYSPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNarfcrhdQAAA7')
		# self.logo.pack() #muss man nicht packen??!!
		self.logolabel = Label(self.logoframe, image=self.logo, bg='#CC3300')
		self.logolabel.pack(side=LEFT, fill=X, expand=YES)

		self.lfname = LabelFrame(self.lframe, font=("Helvetica", 11), text='Kundenname:')
		self.lfname.pack(fill=X)
		self.ekname = Entry(self.lfname, textvariable=self.kname, width=30)
		self.ekname.pack(side=LEFT)

		self.lfdate = LabelFrame(self.lframe, font=("Helvetica", 11), text='Ablaufdatum (TT/MM/JJ):')
		self.lfdate.pack(fill=X)
		self.eexd = Entry(self.lfdate, textvariable=self.exday, width=2)
		self.eexd.pack(side=LEFT)
		self.eexm = Entry(self.lfdate, textvariable=self.exmonth, width=2)
		self.eexm.pack(side=LEFT)
		self.eexy = Entry(self.lfdate, textvariable=self.exyear, width=2)
		self.eexy.pack(side=LEFT)
		self.chkdate = Checkbutton(self.lfdate, text='Unbeschränkt', variable=self.chkdvar)
		self.chkdate.pack(side=RIGHT)

		self.lfchke = LabelFrame(self.lframe, font=("Helvetica", 11), text='Evaluationslizenz:')
		self.lfchke.pack(fill=X)
		self.chke = Checkbutton(self.lfchke, variable=self.chkevar)
		self.chke.pack(side=LEFT)

		self.lfchki = LabelFrame(self.lframe, font=("Helvetica", 11), text='Interne Lizenz:')
		self.lfchki.pack(fill=X)
		self.chki = Checkbutton(self.lfchki, variable=self.chkivar)
		self.chki.pack(side=LEFT)

		self.lfchko = LabelFrame(self.lframe, font=("Helvetica", 11), text='Altes Lizenzformat (vor 1.2-3):')
		self.lfchko.pack(fill=X)
		self.chko = Checkbutton(self.lfchko, variable=self.chkovar, command=self.makegrey)
		self.chko.pack(side=LEFT)

		self.kdn = StringVar()
		self.kdn.set('dc=univention,dc=de')
		self.lfdn = LabelFrame(self.rframe, font=("Helvetica", 11), text='Kunde DN:')
		self.lfdn.pack(fill=X)
		self.ekdn = Entry(self.lfdn, textvariable=self.kdn, width=30)
		self.ekdn.pack(side=LEFT)

		self.kmaxacc = IntVar()
		self.kmaxacc.set('999')
		self.kmaxgacc = IntVar()
		self.kmaxgacc.set('999')
		self.kmaxcli = IntVar()
		self.kmaxcli.set('999')
		self.kmaxdesk = IntVar()
		self.kmaxdesk.set('999')

		self.chkmaxaccvar = IntVar()
		self.chkmaxaccvar.set('0')
		self.chkmaxgaccvar = IntVar()
		self.chkmaxgaccvar.set('0')
		self.chkmaxclivar = IntVar()
		self.chkmaxclivar.set('0')
		self.chkmaxdeskvar = IntVar()
		self.chkmaxdeskvar.set('0')

		self.lfmaxacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Accounts:')
		self.lfmaxacc.pack(fill=X)
		self.lfmaxgacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Groupware Accounts:')
		self.lfmaxgacc.pack(fill=X)
		self.lfmaxcli = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Clients:')
		self.lfmaxcli.pack(fill=X)
		self.lfmaxdesk = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Univention Desktops:')
		self.lfmaxdesk.pack(fill=X)

		self.emaxacc = Entry(self.lfmaxacc, textvariable=self.kmaxacc)
		self.emaxacc.pack(side=LEFT)
		self.chkmaxacc = Checkbutton(self.lfmaxacc, text='Unbeschränkt', variable=self.chkmaxaccvar)
		self.chkmaxacc.pack(side=LEFT)

		self.emaxgacc = Entry(self.lfmaxgacc, textvariable=self.kmaxgacc)
		self.emaxgacc.pack(side=LEFT)
		self.chkmaxgacc = Checkbutton(self.lfmaxgacc, text='Unbeschränkt', variable=self.chkmaxgaccvar)
		self.chkmaxgacc.pack(side=LEFT)

		self.emaxcli = Entry(self.lfmaxcli, textvariable=self.kmaxcli)
		self.emaxcli.pack(side=LEFT)
		self.chkmaxcli = Checkbutton(self.lfmaxcli, text='Unbeschränkt', variable=self.chkmaxclivar)
		self.chkmaxcli.pack(side=LEFT)

		self.emaxdesk = Entry(self.lfmaxdesk, textvariable=self.kmaxdesk)
		self.emaxdesk.pack(side=LEFT)
		self.chkmaxdesk = Checkbutton(self.lfmaxdesk, text='Unbeschränkt', variable=self.chkmaxdeskvar)
		self.chkmaxdesk.pack(side=LEFT)

		self.bexit = Button(self.bframe, text='Beenden', command=self.quit)
		self.bexit.pack(side=RIGHT)

		self.bsave = Button(self.bframe, text='Lizenz erzeugen', command=self.generate)
		self.bsave.pack(side=RIGHT)
Пример #52
0
class _Hatch_GUI(object):
    """
    create a Hatch object from
    hatch_supt and to then create a skeleton python project.
    """
    def __init__(self, master):
        self.initComplete = 0
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1

        # bind master to <Configure> in order to handle any resizing, etc.
        # postpone self.master.bind("<Configure>", self.Master_Configure)
        self.master.bind('<Enter>', self.bindConfigure)

        self.master.title("PyHatch GUI")
        self.master.resizable(0, 0)  # Linux may not respect this

        dialogframe = Frame(master, width=810, height=630)
        dialogframe.pack()

        self.Shortdesc_Labelframe = LabelFrame(
            dialogframe,
            text="Short Description (1-liner)",
            height="90",
            width="718")
        self.Shortdesc_Labelframe.place(x=60, y=127)

        helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold')

        self.Buildproject_Button = Button(dialogframe,
                                          text="Build Project",
                                          width="15",
                                          font=helv20)
        self.Buildproject_Button.place(x=492, y=10, width=263, height=68)
        self.Buildproject_Button.bind("<ButtonRelease-1>",
                                      self.Buildproject_Button_Click)

        self.Selectdir_Button = Button(dialogframe,
                                       text="<Select Directory>",
                                       width="15")
        self.Selectdir_Button.place(x=72, y=585, width=672, height=31)
        self.Selectdir_Button.bind("<ButtonRelease-1>",
                                   self.Selectdir_Button_Click)

        self.Author_Entry = Entry(dialogframe, width="15")
        self.Author_Entry.place(x=228, y=424, width=187, height=21)
        self.Author_Entry_StringVar = StringVar()
        self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar)
        self.Author_Entry_StringVar.set("John Doe")

        self.Classname_Entry = Entry(dialogframe, width="15")
        self.Classname_Entry.place(x=192, y=73, width=165, height=21)
        self.Classname_Entry_StringVar = StringVar()
        self.Classname_Entry.configure(
            textvariable=self.Classname_Entry_StringVar)
        self.Classname_Entry_StringVar.set("MyClass")

        self.Copyright_Entry = Entry(dialogframe, width="15")
        self.Copyright_Entry.place(x=228, y=478, width=461, height=21)
        self.Copyright_Entry_StringVar = StringVar()
        self.Copyright_Entry.configure(
            textvariable=self.Copyright_Entry_StringVar)
        self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe")

        self.Email_Entry = Entry(dialogframe, relief="sunken", width="15")
        self.Email_Entry.place(x=228, y=505, width=458, height=21)
        self.Email_Entry_StringVar = StringVar()
        self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar)
        self.Email_Entry_StringVar.set("*****@*****.**")

        self.GithubUserName_Entry = Entry(dialogframe,
                                          relief="sunken",
                                          width="15")
        self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21)
        self.GithubUserName_Entry_StringVar = StringVar()
        self.GithubUserName_Entry.configure(
            textvariable=self.GithubUserName_Entry_StringVar)
        self.GithubUserName_Entry_StringVar.set("github_user_name")

        self.Funcname_Entry = Entry(dialogframe, width="15")
        self.Funcname_Entry.place(x=192, y=100, width=157, height=21)
        self.Funcname_Entry_StringVar = StringVar()
        self.Funcname_Entry.configure(
            textvariable=self.Funcname_Entry_StringVar)
        self.Funcname_Entry_StringVar.set("my_function")

        # License values should be correct format
        LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys()))
        self.License_Entry_StringVar = StringVar()
        self.License_Entry = OptionMenu(dialogframe,
                                        self.License_Entry_StringVar,
                                        *LICENSE_OPTIONS)
        self.License_Entry.place(x=552, y=424, width=184, height=21)
        self.License_Entry_StringVar.set(LICENSE_OPTIONS[0])

        self.Mainpyname_Entry = Entry(dialogframe, width="15")
        self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21)
        self.Mainpyname_Entry_StringVar = StringVar()
        self.Mainpyname_Entry.configure(
            textvariable=self.Mainpyname_Entry_StringVar)
        self.Mainpyname_Entry_StringVar.set("main.py")

        self.Projname_Entry = Entry(dialogframe, width="15")
        self.Projname_Entry.place(x=168, y=10, width=194, height=21)
        self.Projname_Entry_StringVar = StringVar()
        self.Projname_Entry.configure(
            textvariable=self.Projname_Entry_StringVar)
        self.Projname_Entry_StringVar.set("MyProject")

        self.Shortdesc_Entry = Entry(dialogframe, width="15")
        self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48)
        self.Shortdesc_Entry_StringVar = StringVar()
        self.Shortdesc_Entry.configure(
            textvariable=self.Shortdesc_Entry_StringVar)
        self.Shortdesc_Entry_StringVar.set("My project does this")

        # Status must be correct format
        self.Status_Entry_StringVar = StringVar()
        self.Status_Entry = OptionMenu(dialogframe,
                                       self.Status_Entry_StringVar,
                                       *DEV_STATUS_OPTIONS)
        self.Status_Entry.place(x=228, y=451, width=183, height=21)
        self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0])

        self.Version_Entry = Entry(dialogframe, width="15")
        self.Version_Entry.place(x=552, y=451, width=184, height=21)
        self.Version_Entry_StringVar = StringVar()
        self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar)
        self.Version_Entry_StringVar.set("0.1.1")

        self.Author_Label = Label(dialogframe, text="Author", width="15")
        self.Author_Label.place(x=96, y=424, width=112, height=22)

        self.Classname_Label = Label(dialogframe,
                                     text="Class Name",
                                     width="15")
        self.Classname_Label.place(x=60, y=73, width=112, height=22)

        self.Copyright_Label = Label(dialogframe, text="Copyright", width="15")
        self.Copyright_Label.place(x=96, y=478, width=113, height=23)

        self.Email_Label = Label(dialogframe, text="Email", width="15")
        self.Email_Label.place(x=96, y=505, width=113, height=23)

        self.GithubUserName_Label = Label(dialogframe,
                                          text="GithubUserName",
                                          width="15")
        self.GithubUserName_Label.place(x=96, y=539, width=113, height=23)

        self.Funcname_Label = Label(dialogframe,
                                    text="Function Name",
                                    width="15")
        self.Funcname_Label.place(x=60, y=100, width=112, height=22)

        self.License_Label = Label(dialogframe, text="License", width="15")
        self.License_Label.place(x=432, y=424, width=113, height=23)

        self.Longdesc_Label = Label(dialogframe,
                                    text="Paragraph Description",
                                    width="15")
        self.Longdesc_Label.place(x=216, y=220, width=376, height=22)

        self.Mainpyname_Label = Label(dialogframe,
                                      text="Main Python File",
                                      width="15")
        self.Mainpyname_Label.place(x=48, y=37, width=112, height=22)

        self.Projname_Label = Label(dialogframe,
                                    text="Project Name",
                                    width="15")
        self.Projname_Label.place(x=48, y=10, width=112, height=22)

        self.Selectdir_Label = Label(
            dialogframe,
            text="Select the Directory Below Which to Place Your Project",
            width="15")
        self.Selectdir_Label.place(x=156, y=567, width=536, height=24)

        self.Status_Label = Label(dialogframe, text="Status", width="15")
        self.Status_Label.place(x=96, y=451, width=114, height=24)

        self.Version_Label = Label(dialogframe, text="Version", width="15")
        self.Version_Label.place(x=432, y=451, width=113, height=23)

        self.Isclass_Radiobutton = Radiobutton(dialogframe,
                                               text="Class Project",
                                               value="Class Project",
                                               width="15",
                                               anchor=W)
        self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("Class Project")
        self.RadioGroup1_StringVar_traceName = \
            self.RadioGroup1_StringVar.trace_variable("w",
                                                      self.RadioGroup1_StringVar_Callback)
        self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar)

        self.Isfunction_Radiobutton = Radiobutton(dialogframe,
                                                  text="Function Project",
                                                  value="Function Project",
                                                  width="15",
                                                  anchor=W)
        self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27)
        self.Isfunction_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        lbframe = Frame(dialogframe)
        self.Text_1_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Text_1 = Text(lbframe,
                           width="40",
                           height="6",
                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Text_1.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Text_1.pack(side=LEFT, fill=BOTH, expand=1)

        self.Text_1_frame.place(x=72, y=250, width=665, height=160)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.dirname = '<Select Directory>'
        self.Funcname_Entry.config(state=DISABLED)

        h = Hatch(projName='MyProject', mainDefinesClass='N')
        if h.author:
            self.Author_Entry_StringVar.set(h.author)
        if h.proj_license:
            self.License_Entry_StringVar.set(h.proj_license)
        if h.proj_copyright:
            self.Copyright_Entry_StringVar.set(h.proj_copyright)
        if h.email:
            self.Email_Entry_StringVar.set(h.email)
        if h.github_user_name:
            self.GithubUserName_Entry_StringVar.set(h.github_user_name)
        del h

    def build_result_dict(self):
        """Takes user inputs from GUI and builds a dictionary of results"""
        # pylint: disable=W0201
        self.result = {}  # return a dictionary of results

        self.result["author"] = self.Author_Entry_StringVar.get()
        self.result["status"] = self.Status_Entry_StringVar.get()
        self.result["proj_license"] = self.License_Entry_StringVar.get()
        self.result["version"] = self.Version_Entry_StringVar.get()
        self.result["proj_copyright"] = self.Copyright_Entry_StringVar.get()
        self.result["email"] = self.Email_Entry_StringVar.get()
        self.result[
            "github_user_name"] = self.GithubUserName_Entry_StringVar.get()

        self.result["main_py_name"] = self.Mainpyname_Entry_StringVar.get()
        self.result["proj_name"] = self.Projname_Entry_StringVar.get()
        self.result["class_name"] = self.Classname_Entry_StringVar.get()
        self.result["func_name"] = self.Funcname_Entry_StringVar.get()

        self.result["short_desc"] = self.Shortdesc_Entry_StringVar.get()
        self.result["para_desc"] = self.Text_1.get(1.0, END)
        self.result["parent_dir"] = self.dirname

        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.result["is_class_project"] = 'Y'
        else:
            self.result["is_class_project"] = 'N'

    def Buildproject_Button_Click(self, event):
        """When clicked, this method gathers all the user inputs
            and builds the project skeleton in the directory specified.
        """

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613

        # >>>>>>insert any user code below this comment for section "compID=29"
        # replace, delete, or comment-out the following
        #print "executed method Buildproject_Button_Click"

        if not os.path.isdir(self.dirname):
            ShowError(
                title='Need Parent Directory',
                message=
                'You need to choose a directory in which to place your project.'
            )
        else:
            self.build_result_dict()  # builds self.result dict
            r = self.result

            h = Hatch(projName=r["proj_name"],
                      mainDefinesClass=r["is_class_project"],
                      mainPyFileName=r["main_py_name"],
                      mainClassName=r["class_name"],
                      mainFunctionName=r["func_name"],
                      author=r["author"],
                      proj_copyright=r["proj_copyright"],
                      proj_license=r["proj_license"],
                      version=r["version"],
                      email=r["email"],
                      status=r["status"],
                      github_user_name=r["github_user_name"],
                      simpleDesc=r["short_desc"],
                      longDesc=r["para_desc"])

            call_result = h.save_project_below_this_dir(self.dirname)
            if call_result == 'Success':
                if AskYesNo(title='Exit Dialog',
                            message='Do you want to leave this GUI?'):
                    self.master.destroy()
            else:
                ShowWarning( title='Project Build Error',
                             message='Project did NOT build properly.\n'+\
                            'Warning Message = (%s)'%call_result)

    # return a string containing directory name
    def AskDirectory(self, title='Choose Directory', initialdir="."):
        """Simply wraps the tkinter function of the "same" name."""
        dirname = tkFileDialog.askdirectory(parent=self.master,
                                            initialdir=initialdir,
                                            title=title)
        return dirname  # <-- string

    def Selectdir_Button_Click(self, event):
        #  I don't care what the exception is, if there's a problem, bail
        #     Also, I want to redefine the dirname attribute here
        # pylint: disable=W0702, W0201

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Selects the directory in which to build project."""

        dirname = self.AskDirectory(title='Choose Directory For Nose Tests',
                                    initialdir='.')
        if dirname:
            try:
                dirname = os.path.abspath(dirname)
            except:
                self.dirname = '<Select Directory>'
                return  # let Alarm force dir selection

            self.dirname = dirname

            self.Selectdir_Button.config(text=self.dirname)

    def RadioGroup1_StringVar_Callback(self, varName, index, mode):
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Responds to changes in RadioGroup1_StringVar."""
        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.Funcname_Entry.config(state=DISABLED)
            self.Classname_Entry.config(state=NORMAL)
        else:
            self.Classname_Entry.config(state=DISABLED)
            self.Funcname_Entry.config(state=NORMAL)

    # tk_happy generated code. DO NOT EDIT THE FOLLOWING. section "Master_Configure"
    def bindConfigure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        if not self.initComplete:
            self.master.bind("<Configure>", self.Master_Configure)
            self.initComplete = 1

    def Master_Configure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        # >>>>>>insert any user code below this comment for section "Master_Configure"
        # replace, delete, or comment-out the following
        if event.widget != self.master:
            if self.w != -1:
                return
        x = int(self.master.winfo_x())
        y = int(self.master.winfo_y())
        w = int(self.master.winfo_width())
        h = int(self.master.winfo_height())
        if (self.x, self.y, self.w, self.h) == (-1, -1, -1, -1):
            self.x, self.y, self.w, self.h = x, y, w, h

        if self.w != w or self.h != h:
            print "Master reconfigured... make resize adjustments"
            self.w = w
            self.h = h
Пример #53
0
#activity 2

from Tkinter import Tk, Label, Entry, Button, StringVar
from Tkinter import LEFT, RIGHT

my_app = Tk(className='Calculator')

L1 = Label(my_app, text='first number')
L1.grid(row=0, column=0)
str1 = StringVar()
E1 = Entry(my_app, textvariable=str1)
E1.grid(row=0, column=1, columnspan=3)
L2 = Label(my_app, text='second number')
L2.grid(row=1, column=0)
str2 = StringVar()
E2 = Entry(my_app, textvariable=str2)
E2.grid(row=1, column=1, columnspan=3)
L3 = Label(my_app, text='result')
L3.grid(row=4, column=0)
L4 = Label(my_app, text='0')
L4.grid(row=4, column=1)


def plus():
    a = float(str1.get())
    b = float(str2.get())
    hasil = a + b
    L4.config(text=hasil)


def minus():
class tkLicenseGen:

	def __init__(self, master):
		master.title('Univention Lizenz Generator')
		self.master = master
		self.logoframe = Frame(self.master, bg='red')
		self.logoframe.pack(side=TOP, fill=X, expand=YES)
		self.lftopframes = LabelFrame(self.master)
		self.lftopframes.pack(side=TOP, fill=X, expand=YES)
		self.lframe = Frame(self.lftopframes)
		self.rframe = Frame(self.lftopframes)
		self.lframe.pack(side=LEFT, fill=X, expand=YES)
		self.rframe.pack(side=RIGHT, fill=X, expand=YES)

		self.bframe = Frame(self.master)
		self.bframe.pack(fill=X)

		self.kname = StringVar()
		self.kname.set('test')

		self.chkevar = IntVar()
		self.chkevar.set('1')
		self.chkivar = IntVar()
		self.chkovar = IntVar()
		self.chkdvar = IntVar()

		self.exday = StringVar()
		self.exmonth = StringVar()
		self.exyear = StringVar()
		self.getdate()  # set date to localdate (month+3)

		try:
			self.logo = PhotoImage(file='/var/www/head_logo.gif')
		except TclError:  # fall back to 64x64 white
			self.logo = PhotoImage(data='R0lGODdhQABAAIAAAP///wAAACwAAAAAQABAAAACRYSPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNarfcrhdQAAA7')
		# self.logo.pack() #muss man nicht packen??!!
		self.logolabel = Label(self.logoframe, image=self.logo, bg='#CC3300')
		self.logolabel.pack(side=LEFT, fill=X, expand=YES)

		self.lfname = LabelFrame(self.lframe, font=("Helvetica", 11), text='Kundenname:')
		self.lfname.pack(fill=X)
		self.ekname = Entry(self.lfname, textvariable=self.kname, width=30)
		self.ekname.pack(side=LEFT)

		self.lfdate = LabelFrame(self.lframe, font=("Helvetica", 11), text='Ablaufdatum (TT/MM/JJ):')
		self.lfdate.pack(fill=X)
		self.eexd = Entry(self.lfdate, textvariable=self.exday, width=2)
		self.eexd.pack(side=LEFT)
		self.eexm = Entry(self.lfdate, textvariable=self.exmonth, width=2)
		self.eexm.pack(side=LEFT)
		self.eexy = Entry(self.lfdate, textvariable=self.exyear, width=2)
		self.eexy.pack(side=LEFT)
		self.chkdate = Checkbutton(self.lfdate, text='Unbeschränkt', variable=self.chkdvar)
		self.chkdate.pack(side=RIGHT)

		self.lfchke = LabelFrame(self.lframe, font=("Helvetica", 11), text='Evaluationslizenz:')
		self.lfchke.pack(fill=X)
		self.chke = Checkbutton(self.lfchke, variable=self.chkevar)
		self.chke.pack(side=LEFT)

		self.lfchki = LabelFrame(self.lframe, font=("Helvetica", 11), text='Interne Lizenz:')
		self.lfchki.pack(fill=X)
		self.chki = Checkbutton(self.lfchki, variable=self.chkivar)
		self.chki.pack(side=LEFT)

		self.lfchko = LabelFrame(self.lframe, font=("Helvetica", 11), text='Altes Lizenzformat (vor 1.2-3):')
		self.lfchko.pack(fill=X)
		self.chko = Checkbutton(self.lfchko, variable=self.chkovar, command=self.makegrey)
		self.chko.pack(side=LEFT)

		self.kdn = StringVar()
		self.kdn.set('dc=univention,dc=de')
		self.lfdn = LabelFrame(self.rframe, font=("Helvetica", 11), text='Kunde DN:')
		self.lfdn.pack(fill=X)
		self.ekdn = Entry(self.lfdn, textvariable=self.kdn, width=30)
		self.ekdn.pack(side=LEFT)

		self.kmaxacc = IntVar()
		self.kmaxacc.set('999')
		self.kmaxgacc = IntVar()
		self.kmaxgacc.set('999')
		self.kmaxcli = IntVar()
		self.kmaxcli.set('999')
		self.kmaxdesk = IntVar()
		self.kmaxdesk.set('999')

		self.chkmaxaccvar = IntVar()
		self.chkmaxaccvar.set('0')
		self.chkmaxgaccvar = IntVar()
		self.chkmaxgaccvar.set('0')
		self.chkmaxclivar = IntVar()
		self.chkmaxclivar.set('0')
		self.chkmaxdeskvar = IntVar()
		self.chkmaxdeskvar.set('0')

		self.lfmaxacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Accounts:')
		self.lfmaxacc.pack(fill=X)
		self.lfmaxgacc = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Groupware Accounts:')
		self.lfmaxgacc.pack(fill=X)
		self.lfmaxcli = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Clients:')
		self.lfmaxcli.pack(fill=X)
		self.lfmaxdesk = LabelFrame(self.rframe, font=("Helvetica", 11), text='Max. Univention Desktops:')
		self.lfmaxdesk.pack(fill=X)

		self.emaxacc = Entry(self.lfmaxacc, textvariable=self.kmaxacc)
		self.emaxacc.pack(side=LEFT)
		self.chkmaxacc = Checkbutton(self.lfmaxacc, text='Unbeschränkt', variable=self.chkmaxaccvar)
		self.chkmaxacc.pack(side=LEFT)

		self.emaxgacc = Entry(self.lfmaxgacc, textvariable=self.kmaxgacc)
		self.emaxgacc.pack(side=LEFT)
		self.chkmaxgacc = Checkbutton(self.lfmaxgacc, text='Unbeschränkt', variable=self.chkmaxgaccvar)
		self.chkmaxgacc.pack(side=LEFT)

		self.emaxcli = Entry(self.lfmaxcli, textvariable=self.kmaxcli)
		self.emaxcli.pack(side=LEFT)
		self.chkmaxcli = Checkbutton(self.lfmaxcli, text='Unbeschränkt', variable=self.chkmaxclivar)
		self.chkmaxcli.pack(side=LEFT)

		self.emaxdesk = Entry(self.lfmaxdesk, textvariable=self.kmaxdesk)
		self.emaxdesk.pack(side=LEFT)
		self.chkmaxdesk = Checkbutton(self.lfmaxdesk, text='Unbeschränkt', variable=self.chkmaxdeskvar)
		self.chkmaxdesk.pack(side=LEFT)

		self.bexit = Button(self.bframe, text='Beenden', command=self.quit)
		self.bexit.pack(side=RIGHT)

		self.bsave = Button(self.bframe, text='Lizenz erzeugen', command=self.generate)
		self.bsave.pack(side=RIGHT)

	def generate(self):
		makelicense = ['univention_make_license']
		path = tkFileDialog.asksaveasfilename(initialdir='~', initialfile=self.kname.get() + '-license', defaultextension='.ldif')
		# print path
		if path:
			if self.chkevar.get():
				makelicense.append('-e')
			if self.chkivar.get():
				makelicense.append('-i')
			makelicense.append('-f')
			makelicense.append(path)

			if not self.chkdvar.get():
				makelicense.append('-d')
				makelicense.append("%s/%s/%s" % (self.exmonth.get(), self.exday.get(), self.exyear.get()))

			if not self.chkovar.get():
				if not self.chkmaxaccvar.get():
					makelicense.append('-a')
					makelicense.append('%d' % self.kmaxacc.get())
				else:
					makelicense.append('-a')
					makelicense.append('unlimited')
				if not self.chkmaxgaccvar.get():
					makelicense.append('-g')
					makelicense.append('%d' % self.kmaxgacc.get())
				else:
					makelicense.append('-g')
					makelicense.append('unlimited')
				if not self.chkmaxclivar.get():
					makelicense.append('-c')
					makelicense.append('%d' % self.kmaxcli.get())
				else:
					makelicense.append('-c')
					makelicense.append('unlimited')
				if not self.chkmaxdeskvar.get():
					makelicense.append('-u')
					makelicense.append('%d' % self.kmaxdesk.get())
				else:
					makelicense.append('-u')
					makelicense.append('unlimited')
			else:
				makelicense.append('-o')

			makelicense.append(self.kname.get())
			makelicense.append(self.kdn.get())
			os.chdir('/home/groups/99_license/')
			p = subprocess.Popen(makelicense, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
			stdout, stderr = p.communicate()
			if p.returncode == 0:
				showinfo('Lizenz Erstellt!', 'Die Lizenz für %s wurde erfolgreich erstellt!' % self.kname.get())
			elif p.returncode == 257:
				showerror('Fehler', 'Errorcode: "%s"\nEvtl. sind Sie nicht in dem Sudoers File!' % p.returncode)
			elif p.returncode == 8704:
				showerror('Fehler', 'Errorcode: "%s"\nmake_license.sh meldet: "invalid DN"!' % p.returncode)
			else:
				print >>sys.stderr, '%r\n%s' % (makelicense, stdout)
				showerror('Fehler', 'Errorcode: "%s"\nEin unbekannter Fehler ist aufgetreten!\nBitte senden Sie eine komplette Fehlerbeschreibung an "*****@*****.**"' % p.returncode)
			# print makelicense
			# print '-->ErrorCode: %d'%i[0]
			# print i[1]

	def getdate(self):
		localtime = time.strftime('%d %m %y')
		split = localtime.split(' ')
		day = int(split[0])
		month = int(split[1])
		year = int(split[2])
		month += 3
		if month > 12:
			month = month - 12
			year += 1
		if day < 10:
			day = '0' + str(day)
		if month < 10:
			month = '0' + str(month)
		if year < 10:
			year = '0' + str(year)
		self.exday.set(day)
		self.exmonth.set(month)
		self.exyear.set(year)

	def makegrey(self):
		pass

        def quit(self, event=None):
                self.master.quit()
Пример #55
0
class RGBDigitizer(TFrame):
    def __init__(self, parent, callback, **kw):
        self.callback = callback
        TFrame.__init__(self, parent, style='FlatFrame', **kw)
        self.R_value = IntVar(0)
        self.G_value = IntVar(0)
        self.B_value = IntVar(0)
        self.A_value = IntVar(0)

        self.HTML_value = StringVar('')

        b = TLabel(self, style='HLine')
        b.pack(side=BOTTOM, fill=X)

        frame = TFrame(self, borderwidth=0, style='FlatFrame')
        frame.pack(side=BOTTOM)
        label = TLabel(frame, text=_("Alpha channel: "))
        label.pack(side=LEFT)
        self.A_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.A_value,
                               command=self.rgb_component_changed)
        self.A_spin.pack(side=RIGHT)

        b = TLabel(self, style='HLine')
        b.pack(side=BOTTOM, fill=X)

        html_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        html_frame.pack(side=BOTTOM)

        self.HTML_entry = TEntrybox(html_frame,
                                    text='#000000',
                                    width=10,
                                    textvariable=self.HTML_value,
                                    command=self.html_component_changed)
        self.HTML_entry.pack(side=RIGHT)

        label = TLabel(html_frame, text="HTML: ")
        label.pack(side=RIGHT)

        rgb_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        rgb_frame.pack(side=LEFT, padx=10)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="R: ")
        label.pack(side=LEFT)
        self.R_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.R_value,
                               command=self.rgb_component_changed)
        self.R_spin.pack(side=RIGHT)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="G: ")
        label.pack(side=LEFT)
        self.G_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.G_value,
                               command=self.rgb_component_changed)
        self.G_spin.pack(side=RIGHT)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="B: ")
        label.pack(side=LEFT)
        self.B_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.B_value,
                               command=self.rgb_component_changed)
        self.B_spin.pack(side=RIGHT)

        cmyk_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        cmyk_frame.pack(side=LEFT)

        self.CMYK_label = TLabel(cmyk_frame,
                                 text='C:\nM:\nY:\nK:',
                                 justify=LEFT)
        self.CMYK_label.pack(side=LEFT)

    def set_color(self, color):
        self.color = color
        self.R_value.set(int(round(color.red * 255)))
        self.G_value.set(int(round(color.green * 255)))
        self.B_value.set(int(round(color.blue * 255)))
        self.A_value.set(int(round(color.alpha * 255)))
        c, m, y, k = color.getCMYK()
        self.CMYK_label['text'] = 'C: %.2f\nM: %.2f\nY: %.2f\nK: %.2f' % (
            round(c * 100, 2), round(m * 100, 2), round(y * 100,
                                                        2), round(k * 100, 2))
        int_color = (round(color.red * 255), round(color.green * 255),
                     round(color.blue * 255))
        self.HTML_value.set('#%02X%02X%02X' % int_color)

    def rgb_component_changed(self, *arg):
        r = self.R_value.get() / 255.0
        g = self.G_value.get() / 255.0
        b = self.B_value.get() / 255.0
        a = self.A_value.get() / 255.0
        self.callback(CreateRGBAColor(r, g, b, a))

    def html_component_changed(self, *arg):
        html = self.HTML_value.get()
        try:
            r = int(string.atoi(html[1:3], 0x10)) / 255.0
            g = int(string.atoi(html[3:5], 0x10)) / 255.0
            b = int(string.atoi(html[5:], 0x10)) / 255.0
        except:
            r = round(self.color.red * 255, 2)
            g = round(self.color.green * 255, 2)
            b = round(self.color.blue * 255, 2)
        self.callback(CreateRGBAColor(r, g, b, self.A_value.get() / 255.0))
Пример #56
0
    def __init__(self, master=None, year=None, month=None,
                 firstweekday=calendar.MONDAY, locale=None,
                 activebackground='#b1dcfb', activeforeground='black',
                 selectbackground='#003eff', selectforeground='white',
                 command=None, borderwidth=1, relief="solid",
                 on_click_month_button=None):
        """
        WIDGET OPTIONS

            locale, firstweekday, year, month, selectbackground,
            selectforeground, activebackground, activeforeground,
            command, borderwidth, relief, on_click_month_button
        """

        if year is None:
            year = self.datetime.now().year

        if month is None:
            month = self.datetime.now().month

        self._selected_date = None

        self._sel_bg = selectbackground
        self._sel_fg = selectforeground

        self._act_bg = activebackground
        self._act_fg = activeforeground

        self.on_click_month_button = on_click_month_button

        self._selection_is_visible = False
        self._command = command

        ttk.Frame.__init__(self, master, borderwidth=borderwidth,
                           relief=relief)

        self.bind("<FocusIn>",
                  lambda event: self.event_generate('<<DatePickerFocusIn>>'))
        self.bind("<FocusOut>",
                  lambda event: self.event_generate('<<DatePickerFocusOut>>'))

        self._cal = get_calendar(locale, firstweekday)

        # custom ttk styles
        style = ttk.Style()
        style.layout('L.TButton', (
            [('Button.focus', {'children': [('Button.leftarrow', None)]})]
        ))
        style.layout('R.TButton', (
            [('Button.focus', {'children': [('Button.rightarrow', None)]})]
        ))

        self._font = tkFont.Font()

        self._header_var = StringVar()

        # header frame and its widgets
        hframe = ttk.Frame(self)
        lbtn = ttk.Button(hframe, style='L.TButton',
                          command=self._on_press_left_button)
        lbtn.pack(side=LEFT)

        self._header = elements.SimpleLabel(hframe, width=15, anchor=CENTER,
                                            textvariable=self._header_var)
        self._header.pack(side=LEFT, padx=12)

        rbtn = ttk.Button(hframe, style='R.TButton',
                          command=self._on_press_right_button)
        rbtn.pack(side=LEFT)
        hframe.grid(columnspan=7, pady=4)

        self._day_labels = {}

        days_of_the_week = self._cal.formatweekheader(3).split()

        for i, day_of_the_week in enumerate(days_of_the_week):
            elements.SimpleLabel(self, text=day_of_the_week,
                                 background='grey90').grid(row=1, column=i,
                                                           sticky=N + E + W + S)

        for i in range(6):
            for j in range(7):
                self._day_labels[i, j] = label = elements.SimpleLabel(self,
                                                                      background="white")

                label.grid(row=i + 2, column=j, sticky=N + E + W + S)
                label.bind("<Enter>", lambda event: event.widget.configure(
                    background=self._act_bg, foreground=self._act_fg))
                label.bind("<Leave>", lambda event: event.widget.configure(
                    background="white"))

                label.bind("<1>", self._pressed)

        # adjust its columns width
        font = tkFont.Font()
        maxwidth = max(font.measure(text) for text in days_of_the_week)
        for i in range(7):
            self.grid_columnconfigure(i, minsize=maxwidth, weight=1)

        self._year = None
        self._month = None

        # insert dates in the currently empty calendar
        self._build_calendar(year, month)
Пример #57
0
    def __init__(self, parent, callback, **kw):
        self.callback = callback
        TFrame.__init__(self, parent, style='FlatFrame', **kw)
        self.R_value = IntVar(0)
        self.G_value = IntVar(0)
        self.B_value = IntVar(0)
        self.A_value = IntVar(0)

        self.HTML_value = StringVar('')

        b = TLabel(self, style='HLine')
        b.pack(side=BOTTOM, fill=X)

        frame = TFrame(self, borderwidth=0, style='FlatFrame')
        frame.pack(side=BOTTOM)
        label = TLabel(frame, text=_("Alpha channel: "))
        label.pack(side=LEFT)
        self.A_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.A_value,
                               command=self.rgb_component_changed)
        self.A_spin.pack(side=RIGHT)

        b = TLabel(self, style='HLine')
        b.pack(side=BOTTOM, fill=X)

        html_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        html_frame.pack(side=BOTTOM)

        self.HTML_entry = TEntrybox(html_frame,
                                    text='#000000',
                                    width=10,
                                    textvariable=self.HTML_value,
                                    command=self.html_component_changed)
        self.HTML_entry.pack(side=RIGHT)

        label = TLabel(html_frame, text="HTML: ")
        label.pack(side=RIGHT)

        rgb_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        rgb_frame.pack(side=LEFT, padx=10)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="R: ")
        label.pack(side=LEFT)
        self.R_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.R_value,
                               command=self.rgb_component_changed)
        self.R_spin.pack(side=RIGHT)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="G: ")
        label.pack(side=LEFT)
        self.G_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.G_value,
                               command=self.rgb_component_changed)
        self.G_spin.pack(side=RIGHT)

        frame = TFrame(rgb_frame, borderwidth=2, style='FlatFrame')
        frame.pack(side=TOP)
        label = TLabel(frame, text="B: ")
        label.pack(side=LEFT)
        self.B_spin = TSpinbox(frame,
                               min=0,
                               max=255,
                               step=1,
                               vartype=0,
                               width=7,
                               textvariable=self.B_value,
                               command=self.rgb_component_changed)
        self.B_spin.pack(side=RIGHT)

        cmyk_frame = TFrame(self, borderwidth=2, style='FlatFrame')
        cmyk_frame.pack(side=LEFT)

        self.CMYK_label = TLabel(cmyk_frame,
                                 text='C:\nM:\nY:\nK:',
                                 justify=LEFT)
        self.CMYK_label.pack(side=LEFT)
class App:

    def __init__(self, port, pin1, pin2, pin3, pin4, pin5):
        # Setting up Arduino
        self.arduino = Arduino(port)

        self.servo1 = pin1
        self.servo2 = pin2
        self.servo3 = pin3
        self.servo4 = pin4
        self.servo5 = pin5

        self.arduino.digital[self.servo1].mode = SERVO
        self.arduino.digital[self.servo2].mode = SERVO
        self.arduino.digital[self.servo3].mode = SERVO
        self.arduino.digital[self.servo4].mode = SERVO
        self.arduino.digital[self.servo5].mode = SERVO

        # Setting up Database Connect
        path = 'C:/Users/Mohamad/Desktop/db/servo_2d.db'
        self.Connect = lite.connect(path)

        self.servo1OldVal = 0
        self.servo2OldVal = 0
        self.servo3OldVal = 0
        self.servo4OldVal = 0
        self.servo5OldVal = 0

        self.root = Tkinter.Tk()
        self.root.geometry('600x600')

        # GUI variables
        self.servo1Val = IntVar()
        self.servo2Val = IntVar()
        self.servo3Val = IntVar()
        self.servo4Val = IntVar()
        self.servo5Val = IntVar()

        self.pointName = StringVar()

        # GUI Components
        servo1_slider = Tkinter.Scale(self.root,
                                      label='Servo 1',
                                      length=400,
                                      from_=0, to_=360,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo1Val)
        servo1_slider.grid(column=1, row=2)

        servo2_slider = Tkinter.Scale(self.root,
                                      label='Servo 2',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo2Val)
        servo2_slider.grid(column=2, row=2)

        servo3_slider = Tkinter.Scale(self.root,
                                      label='Servo 3',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo3Val)
        servo3_slider.grid(column=3, row=2)

        servo4_slider = Tkinter.Scale(self.root,
                                      label='Servo 4',
                                      length=400,
                                      from_=0, to_=180,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo4Val)
        servo4_slider.grid(column=4, row=2)

        servo5_slider = Tkinter.Scale(self.root,
                                      label='Servo 5',
                                      length=400,
                                      from_=0, to_=60,
                                      orient=Tkinter.VERTICAL,
                                      variable=self.servo5Val)
        servo5_slider.grid(column=5, row=2)

        self.btnSave = Button(self.root, text='Save', command=self.onSaveClicked)
        self.btnSave.grid(column=1, row=0)

        self.btnGet = Button(self.root, text='Get', command=self.onGetClicked)
        self.btnGet.grid(column=6, row=0)

        self.pName = Entry(self.root, textvariable=self.pointName)
        self.pName.grid(column=0, row=0)

        self.root.after(100, self.onSliderChange)
        self.root.mainloop()

    #def OnSliderChange(self):
    #    check(val, oldval, pin)
    #def check(self, val, oldVal, pin):
    #    if (val != oldVal):
    #       self.arduino.digital[pin].write(val)
    #        sleep(0.01)
    #        oldVal = val

    def onSliderChange(self):
        if self.servo1Val.get() != self.servo1OldVal:
            self.arduino.digital[self.servo1].write(self.servo1Val.get())
            sleep(0.01)

            self.servo1OldVal = self.servo1Val.get()

        if self.servo2Val.get() != self.servo2OldVal:
            self.arduino.digital[self.servo2].write(self.servo2Val.get())
            sleep(0.01)

            self.servo2OldVal = self.servo2Val.get()

        if self.servo3Val.get() != self.servo3OldVal:
            self.arduino.digital[self.servo3].write(self.servo3Val.get())
            sleep(0.01)

            self.servo3OldVal = self.servo3Val.get()

        if self.servo4Val.get() != self.servo4OldVal:
            self.arduino.digital[self.servo4].write(self.servo4Val.get())
            sleep(0.01)

            self.servo4OldVal = self.servo4Val.get()

        if self.servo5Val.get() != self.servo5OldVal:
            self.arduino.digital[self.servo5].write(self.servo5Val.get())
            sleep(0.01)

            self.servo5OldVal = self.servo5Val.get()

        self.root.after(123, self.onSliderChange)

    def onSaveClicked(self):
        with self.Connect:
            cur = self.Connect.cursor()
            sql = "INSERT INTO test VALUES(?,?,?,?,?,?)"
            cur.execute(sql, (self.servo1Val.get(), self.servo2Val.get(),
                              self.servo3Val.get(), self.servo4Val.get(),
                              self.servo5Val.get(), self.pointName.get()))

    def onGetClicked(self):
        with self.Connect:
            cur = self.Connect.cursor()
            sql = "SELECT * FROM test WHERE point=?"
            cur.execute(sql, [self.pointName.get()])
            points = cur.fetchone()
            #print(points[0])
            print('Servo1: {0} Servo2: {1}Servo1: {2} Servo2: {3}Servo1: {4}'.format(str(points[0]), str(points[1]),
                                                                                     str(points[2]), str(points[3]),
                                                                                     str(points[4])))

            self.servo1Val.set(points[0])
            sleep(0.1)
            self.servo2Val.set(points[1])
            sleep(0.1)
            self.servo3Val.set(points[2])
            sleep(0.1)
            self.servo4Val.set(points[3])
            sleep(0.1)
            self.servo5Val.set(points[4])
Пример #59
0
 def __init__(self, master):
     Frame.__init__(self, master)
     self.serial_num = StringVar()
     self.master = master
     self.results = StringVar()
     self.__initUi()
Пример #60
0
class GUI:
	def __init__(self, master):
		self.master = master
		self.conf = Config()
		self.student_list = None
		self.save_filetype = StringVar()
		self.save_filetype.set('.txt')
		self.selected_section = StringVar()
		self.selected_section.set('ENGR 102 01')
		self.week = StringVar()
		self.week.set('42')
		self.student_listbox_contents = []
		self.attended_students = []

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

	def save_filetype_change(self, event):
		self.save_filetype.set(self.filetype_combobox.get())