def CreateWidgets(self):
        self.name = StringVar(self)
        self.fontSize = StringVar(self)
        self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
        self.messageInfo = Label(self.frameMain, text=self.message)
        entryName = Entry(self.frameMain, textvariable=self.name, width=30)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Ok', command=self.Ok)
        self.buttonCancel = Button(frameButtons, text='Cancel',
                command=self.Cancel)

        entryName.focus_set()

        self.frameMain.pack(side=TOP, expand=True, fill=BOTH)
        self.messageInfo.pack(padx=5, pady=5)
        entryName.pack(padx=5, pady=5)
        frameButtons.pack(side=BOTTOM, fill=X)
        self.buttonOk.pack(padx=1, pady=5, side=RIGHT)
        self.buttonCancel.pack(pady=5, padx=5, side=RIGHT)

        if TTK:
            self.messageInfo['padding'] = 5
            frameButtons['style'] = 'RootColor.TFrame'
        else:
            self.messageInfo.configure(padx=5, pady=5)
    def _init_components(self):
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        upper_pane = Frame(self)
        upper_pane.columnconfigure(0, weight=1)
        upper_pane.rowconfigure(0, weight=1)

        self.apex_list = ApexList(upper_pane, self._apex)
        self.apex_list.grid(row=0, column=0, sticky='nesw')

        self._scrollbar_x = Scrollbar(upper_pane, command=self.apex_list.xview,
            orient='horizontal')
        self._scrollbar_x.grid(row=1, column=0, sticky='ews')
        self.apex_list['xscrollcommand'] = self._scrollbar_x.set
        self._scrollbar_y = Scrollbar(upper_pane, command=self.apex_list.yview)
        self._scrollbar_y.grid(row=0, column=1, sticky='nse')
        self.apex_list['yscrollcommand'] = self._scrollbar_y.set

        buttons_pane = Frame(self)

        self._expand_button = Button(buttons_pane, text="Expand all",
            command=self.apex_list.expand_all)
        self._expand_button.pack(side='left', expand=True, fill='x')

        self._reset_button = Button(buttons_pane, text="Reset",
            command=self.apex_list.reset)
        self._reset_button.pack()

        upper_pane.grid(sticky='nesw')
        buttons_pane.grid(row=1, sticky='nesw')
 def __vidButtons(self):
     self.modtitle = Button(text='Modify titles', command=self.__modTitles)
     #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2,
     #                   padx=self.padx, pady=self.pady)
     self.getcaps = Button(text="Get captions", command=self.__getCaptions)
     self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E,
                       padx=self.padx, pady=self.pady)
Beispiel #4
0
 def __init__(self, parent, title, action=None):
     self.action = action
     self.top = Toplevel(parent)
     Label(self.top, text=title).pack()
     if action:
         b = Button(self.top, text="Cancel", command=self.cancel)
         b.pack(pady=5)
class encoderface(LabelFrame):

    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()
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
        
    def initUI(self):
      
        self.parent.title("Color chooser")      
        self.pack(fill=BOTH, expand=1)
        
        self.btn = Button(self, text="Choose Color", 
            command=self.onChoose)
        self.btn.place(x=30, y=30)
        
        self.frame = Frame(self, border=1, 
            relief=SUNKEN, width=100, height=100)
        self.frame.place(x=160, y=30)


    def onChoose(self):
      
        (rgb, hx) = tkColorChooser.askcolor()
        self.frame.config(bg=hx)
    def create_option_buttons(self, right_answer, answers):

        # create buttons
        self.option_1 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[0]][0])
        self.option_1.place(x=5,y=140)
        self.option_2 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[1]][0])
        self.option_2.place(x=5,y=200) 
        self.option_3 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[2]][0])
        self.option_3.place(x=95,y=140)
        self.option_4 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[3]][0])
        self.option_4.place(x=95,y=200)
        self.option_1.config(command=lambda:
                             self.right_button(self.option_1) if answers[0] == right_answer
                             else self.wrong_button(self.option_1))
        self.option_2.config(command=lambda:
                             self.right_button(self.option_2) if answers[1] == right_answer
                             else self.wrong_button(self.option_2))
        self.option_3.config(command=lambda:
                             self.right_button(self.option_3) if answers[2] == right_answer
                             else self.wrong_button(self.option_3))
        self.option_4.config(command=lambda:
                             self.right_button(self.option_4) if answers[3] == right_answer
                             else self.wrong_button(self.option_4))
Beispiel #8
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.titleLabel = Label(self, text='please input number and digit !')
        self.titleLabel.pack()
        self.numberLabel = Label(self, text='number: ')
        self.numberLabel.pack()
        self.numberInput = Entry(self)
        self.numberInput.pack()
        self.digitLabel = Label(self, text='digit: ')
        self.digitLabel.pack()
        self.digitInput = Entry(self)
        self.digitInput.pack()
        self.runButton = Button(self, text='run', command=self.run)
        self.runButton.pack()
        self.quitButton = Button(self, text='quit', command=self.quit)
        self.quitButton.pack()

    # run Button
    def run(self):
        number = self.numberInput.get()
        digit = self.digitInput.get()

        with open('E:/pycharm/practice1/image/verify.txt', 'w') as f:
            verify = verify_str(number, digit)
            f.write(verify)

        tkMessageBox.showinfo('verify', verify)
Beispiel #9
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()
Beispiel #10
0
	def __init__(self, root, prtr, settings, log, *arg):
		Toplevel.__init__(self, root, *arg)
		self.protocol('WM_DELETE_WINDOW', self.delTop)
		self.title("Macro Buttons")
		
		self.app = root
		self.settings = settings
		self.printer = prtr
		self.log = log
		
		self.macroList = self.settings.getMacroList()
		fw = BUTTONWIDTH * 3
		fh = BUTTONHEIGHT * 10
		self.f = Frame(self, width = BUTTONWIDTH*3, height=BUTTONHEIGHT*10)
		for m in self.macroList:
			b = Button(self.f, text=m[MTEXT], width=BWIDTH, command=lambda macro=m[MNAME]: self.doMacro(macro))
			x = (m[MCOL]-1) * BUTTONWIDTH
			y = (m[MROW]-1) * BUTTONHEIGHT
			b.place(relx=0.0, rely=0.0, y=y, x=x, anchor=NW)
			
		self.f.pack()
		
		geometry = "%dx%d+50+50" % (fw, fh)
		
		self.geometry(geometry)
Beispiel #11
0
 def __init__(self, parent):
     Frame.__init__(self, parent)
     self.parent = parent
     
     open_button = Button(self, text = 'Calculate', relief = 'raised',
                          command=self._on_calculate, width = 23)
     open_button.pack()
Beispiel #12
0
	def __init__(self, master):
		rows = 10
		columns = 7
		self.d = door(rows, columns)
		master.title("The Fridge")
		self.frame = Frame(master)

		controls = Frame(self.frame)
		self.start = Button(controls,
						text = "Restart",
						width = 6,
						command = self.restart
						)
		self.start.grid(row = 0, column = 4, columnspan = 2, sticky = E)
		self.rowtext = Entry(controls, width = 4)
		self.rowtext.grid(row = 0, column = 0, columnspan = 2, sticky = W)
		self.coltext = Entry(controls, width = 4)
		self.coltext.grid(row = 0, column = 2, columnspan = 2, sticky = E)
		controls.grid(row = 0, column = 0, columnspan = 7)

		self.bttns = []
		for i in xrange(rows):
			for j in xrange(columns):
				cb = Button(self.frame,
						bg = "green" if self.d.plate[i][j].state else "red",
						text = " ",
						command = self.click(self.bttns, self.d, i, j) # coolhack
						)
				cb.grid(row = i+1, column = j)
				self.bttns.append(cb)

		self.frame.grid(column = 0, row = 0)
    def __init__(self, master):

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

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

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

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

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

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

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

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

        self.status_label = Label(self.frame)
Beispiel #14
0
	def columnChooser( self ):
		self.root = Tk()
		self.root.title( "CSV Save Options" )
		
		choiceNum = int(self.main.numSaveCols.get())
		
		geomString = '300x'+str(30+(50*choiceNum))+'-80+80'
		self.root.geometry( geomString)
		
		Label( self.root, text="Choose the header you want in each slot.").grid( row=0, columnspan=2 )
		
		axesTuple = tuple( self.axes )
		self.main.saveChoiceList = [ None ]*choiceNum
		
		for i in range( choiceNum ):
			labelString = "Column "+str(i+1)
			rowNum = i+1
			Label( self.root, text=labelString ).grid( row=rowNum, column=0 )
			self.main.saveChoiceList[i] = StringVar( self.root )
			self.main.saveChoiceList[i].set( self.axes[i] )
			w = apply( OptionMenu, ( self.root, self.main.saveChoiceList[i] ) + axesTuple )
			w.grid( row=rowNum, column=1 )
		
		def callback():
			self.root.destroy()
			self.main.writeCSVFile()
		
		b1 = Button( self.root, text="Confirm", command=callback )
		buttonRow = choiceNum+1
		b1.grid( row=buttonRow, columnspan=2 )
    def __init__(self, fileloc, rng=5, sleeptime=2):
        # experiment with range rng
        self.rng = rng
        self.sleeptime = sleeptime
        self.fileloc = fileloc
        # list of points and coords of experiments
        self.pt_dict = {'1': '68,68', '2': '67,136','3': '138,68','4': '138,136','5': '197,68','6': '197,136','7': '259,68','8': '259,136','9': '327,68','10': '327,136','11': '366,25','12': '366,136','13': '353,204','14': '353,272','15': '295,204','16': '295,272','17': '353,348','18': '353,408','19': '353,476','20': '295,348','21': '295,408','22': '295,476'}

        self.make_pub()

        self.r = Tk()
        self.c = Canvas(self.r, width=400, height=600)
        self.c.pack()
        self.mv = []
        self.smath = s_math.SonarMath()
        self.pts = []
        self.ovals = []
        self.run = Button(self.r, text='run', command=self.run)
        self.run.pack()
        self.reset = Button(self.r, text='reset', command=self.reset)
        self.reset.pack()
        for key in self.pt_dict:
            a = map(int, self.pt_dict[key].split(','))
            self.pts.append(a)
            self.c.create_oval(a[0] -1, a[1] -1, a[0] + 1, a[1] + 1)
    
        self.c.bind("<Button-1>", self.path)
        self.r.mainloop()
Beispiel #16
0
	def special1Case( self ):
		self.root = Tk()
		self.root.title('Choose Filter Options')

		filterCount = 2
		
		winHeight = str(30+(130*filterCount))
		self.root.geometry('500x'+winHeight+'-80+80')
		
		self.main.filterList = None
		
		subjectHeader = StringVar( self.root )
		subjectHeader.set( "SubjectID" )
		subjectField = StringVar( self.root )
		imageHeader = StringVar( self.root )
		imageHeader.set( "Image" )
		imageField = StringVar( self.root )
		
		self.main.colorUse = StringVar( self.root )
		self.main.colorUse.set( "Number" )
		self.main.sizeUse = StringVar( self.root )
		self.main.sizeUse.set( "Duration" )
		
		self.main.filterUse = StringVar( self.root )
		self.main.filterUse.set( "Two" )
		
		emptyFilter = StringVar( self.root )
		
		self.main.axesToPlot = [ None, None ]
		self.main.axesToPlot[0] = StringVar( self.root )
		self.main.axesToPlot[0].set( "x" )
		self.main.axesToPlot[1] = StringVar( self.root )
		self.main.axesToPlot[1].set( "y" )
		
		Label(self.root, text="Choose a subject and image to view fixation results.").grid(row=0, columnspan=2)
		Label(self.root, text="Subject:").grid(row=1, column=0, sticky=tk.W)
		Label(self.root, text="Image:").grid(row=2, column=0, sticky=tk.W)

		subjectText = Entry( self.root, textvariable=subjectField )
		subjectText.grid(row=1, column=1)

		imageText = Entry( self.root, textvariable=imageField )
		imageText.grid(row=2, column=1)
		
		subjectFieldList = [ subjectHeader, subjectText, emptyFilter, emptyFilter ]
		imageFieldList = [ imageHeader, imageText, emptyFilter, emptyFilter ]
			
		localFilterList = [ subjectFieldList, imageFieldList ]
			
		def callback():
			"""Handles the button press at the end of the filter function."""
			for i in range( len( localFilterList ) ):
				for j in range( len( localFilterList[0] ) ):
					localFilterList[i][j] = localFilterList[i][j].get()
			self.main.filterList = localFilterList
			self.root.destroy()
			self.scatterBuild()
			
		b1 = Button( self.root, text="View Fixation Results", command=callback )
		b1.grid( row=3, columnspan=2 )
Beispiel #17
0
	def __init__( self, main, dataInstance, axes ):
		"""Initializes the file saving dialog."""
		self.main = main
		self.dataInstance = dataInstance
		self.axes = axes
		
		self.root = Tk()
		self.root.title( "Save As CSV" )
		self.root.geometry( "350x200" )
		
		Label( self.root, text="Choose options for save." ).grid( row=0, columnspan=2 )
		
		Label(self.root, text="Filename").grid( row=1,column=0, sticky=tk.W )
		self.main.saveFileName = StringVar( self.root )
		fileNameField = Entry( self.root, textvariable=self.main.saveFileName )
		fileNameField.grid(row=1, column=1)
		
		Label( self.root, text="Number of Columns" ).grid( row=2,column=0, sticky=tk.W )
		self.main.numSaveCols = StringVar( self.root )
		self.main.numSaveCols.set( "All" )
		colNumTuple = ( "All", )
		for i in range( len(axes) ):
			colNumTuple += ( str(i+1), )
		w = apply( OptionMenu, ( self.root, self.main.numSaveCols ) + colNumTuple )
		w.grid( row=2, column=1 )
		
		def callback():
			self.root.destroy()
			if self.main.numSaveCols.get() == "All":
				self.main.writeCSVFile()
			else:
				self.columnChooser()
				
		b1 = Button( self.root, text="Confirm", command=callback )
		b1.grid( row=3, columnspan=2 )	
Beispiel #18
0
class StarterWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.wm_title("FRCA QBase Reader - Start Menu")
        self.exambtn = Button(self, text="start an exam", command=self.startExam)
        self.exambtn.pack()
        self.maxquestvar = IntVar()
        self.maxquest = Spinbox(self, from_=1, to=1667, width=4, textvariable=self.maxquestvar)
        self.maxquest.pack()
        self.questbtn = Button(self, text="start single questions", command=self.startQuestions)
        self.questbtn.pack()
        self.um = """User manual:\n
		Start either an exam or single questions\n
		Go to next question either with mouse or the <right arrow>\n
		Toggle checkboxes either with mouse or <keyboard buttons 1-5>\n
		In single question mode, show answer either with mouse or <return>\n
		In exam mode, results will display after the set question number\n
		Text can be made bigger/smaller with <Up> or <Down> keyboard arrows"""
        self.usermanual = Label(self, text=self.um, justify=LEFT)
        self.usermanual.pack()

    def startExam(self):
        call(["python", "exam.py", str(self.maxquestvar.get())])

    def startQuestions(self):
        call(["python", "quest_by_quest.py"])
Beispiel #19
0
	def clusterCase( self ):
		"""Controls the window used to choose options for a new PCA and clustering
		   visualization."""
		
		self.scatterWin = Tk()
		self.scatterWin.title('Choose Options For Clustering')
		
		winHeight = 150+(self.axisNum.get()*20)
		sizeString = "300x"+str( winHeight )+"-80+80"
		self.scatterWin.geometry( sizeString )
		
		self.main.clusterChoice = StringVar( self.scatterWin )
		self.main.clusterChoice.set( "Normal" )
		clusterChoiceTuple = ( "Normal", "PCA" )
		Label(self.scatterWin, text="Data by which to Cluster").grid(row=0)
		w = apply( OptionMenu, (self.scatterWin, self.main.clusterChoice) + clusterChoiceTuple )
		w.grid( row=0, column=1 )
		
		self.main.clusterNum = IntVar( self.scatterWin )
		self.main.clusterNum.set( 3 )
		clusterNumTuple = ()
		for i in range( 2, 15 ):
			clusterNumTuple += ( (i+1), )
		Label(self.scatterWin, text="Number of Clusters").grid(row=1)
		k = apply( OptionMenu, (self.scatterWin, self.main.clusterNum) + clusterNumTuple )
		k.grid( row=1, column=1 )

		def callback():
			self.scatterWin.destroy()
			self.dataInstance.prepareClusters()
			self.scatterBuild()
		
		b = Button( self.scatterWin, text="Continue", command=callback )
		b.grid( row=2, columnspan=2 )
Beispiel #20
0
    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.parent = master

        self.parent.geometry("640x480")
        self.parent.title(os.getenv("NAME") + " - Stdout")

        self.textedit = Text(self.parent, font="mono 10")
        self.textedit.pack(expand=True, fill=BOTH)
        buton = Button(self.parent, text="Close", command=self.quit)
        buton.pack(side=RIGHT, expand=False, padx=10, pady=10, ipadx=10)

        ysb = Scrollbar(self.textedit, orient='vertical', command=self.textedit.yview)
        xsb = Scrollbar(self.textedit, orient='horizontal', command=self.textedit.xview)

        self.textedit.configure(yscroll=ysb.set, xscroll=xsb.set)

        xsb.pack(side=BOTTOM, fill=X, expand=False)
        ysb.pack(side=RIGHT, fill=Y, expand=False)

        self.textedit.pack(side=TOP, fill=BOTH, expand=True)


        self.show_file()
Beispiel #21
0
	def __init__ (self):
		self.app = Tk()
		self.app.title('Tic Tac Toe')
		#self.app.resizable(width=False, height=False)
		#width and hight of window
		w = 900
		h = 1100
		#width and hight of screen
		ws = self.app.winfo_screenwidth()
		hs = self.app.winfo_screenheight()
		#calculate position
		x = ws/2 - w/2
		y = hs/2 - h/2
		#place window -> pramaters(visina, dolzina, pozicija x, pozicija y)
		self.app.geometry("%dx%d+%d+%d" % (w,h, x, y))

		#======================================
		self.frame = Frame() #main frame
		self.frame.pack(fill = 'both', expand = True)
		self.label = Label(self.frame, text	= 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue')
		self.label.pack(fill='both', expand = True)
		#self.label2 = Label(self.frame, text	= 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop-------------
		#self.label2.pack(fill='both', expand = True)
		self.canvas = Canvas(self.frame, width = 900, height = 900)
		self.canvas.pack(fill = 'both', expand = True)
		self.framepod = Frame(self.frame)#sub frame
		self.framepod.pack(fill = 'both', expand = True)
		self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue')
		self.Single.pack(fill='both', expand = True, side=RIGHT)
		self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue')
		self.Multi.pack(fill='both', expand = True, side=RIGHT)
		self.board = AI()
		self.draw()
class ParamItem(Frame):
    
    def __init__(self, master, itemList, deleteCount):
        Frame.__init__(self, master)
        self.labelKey = Label(self, text = "Key:")
        self.labelValue = Label(self, text = "Value:")
        self.entryKey = Entry(self, width = 8)
        self.entryValue = Entry(self, width = 20)
        self.deleteCount = deleteCount
        self.itemList = itemList
        self.btnDelete = Button(self, text = "delete", \
            command = self.__internalDelete, padx = 5)
        self.__boxComponents()
    
    def __boxComponents(self):
        self.labelKey.grid(row = 0, column = 0)
        self.entryKey.grid(row = 0, column = 1)
        self.labelValue.grid(row = 0, column = 2)
        self.entryValue.grid(row = 0, column = 3)
        self.btnDelete.grid(row = 0, column = 4)
    
    def __internalDelete(self):
        self.deleteCount.set(self.deleteCount.get() + 1)
        self.itemList.remove(self)
        self.destroy()
    def getKey(self):
        return self.entryKey.get()
    
    def getValue(self):
        return self.entryValue.get()
    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'
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])
Beispiel #25
0
    def __init__(self, master, text="Position", **options):
        LabelFrame.__init__(self, master, text=text, **options)
        self.tracker = master.tracker

        self.listbox = Listbox(self)
        self.listbox.widget.configure(selectmode=SINGLE)
        self.listbox.grid(row=0, column=0, rowspan=6)

        self.name_frame = LabelFrame(self, text="Name")
        self.name_field = Entry(self.name_frame)
        self.name_field.grid()
        self.name_frame.grid(row=0, column=1)

        self.save_button = Button(self, text="Save current",
                                  command=bg_caller(self.save_position))
        self.save_button.grid(row=1, column=1)
        self.go_to_button = Button(self, text="Go to",
                                   command=bg_caller(self.go_to_position))
        self.go_to_button.grid(row=2, column=1)
        self.delete_button = Button(self, text="Delete",
                                    command=self.delete_position)
        self.delete_button.grid(row=3, column=1)
        self.write_button = Button(self, text="Write to file",
                                   command=self.write_to_file)
        self.write_button.grid(row=4, column=1)
        self.load_button = Button(self, text="Load from file",
                                   command=self.load_from_file)
        self.load_button.grid(row=5, column=1)
Beispiel #26
0
    def __init__(self):
        # UI
        self.root = Tk()
        self.root.resizable(0, 0)
        self.root.title('Sudoku Solver')

        # problem sets
        easy = self._load('problems/easy')
        hard = self._load('problems/hard')

        # frames and buttons
        self.sudoku_frame = Frame(self.root)
        self.control_frame = Frame(self.root)
        self.sudoku_frame.grid(row=0, column=0)
        self.control_frame.grid(row=1, column=0, sticky=W)
        self.buttons = self._create_buttons()
        self.clear_btn = Button(self.control_frame, text='Clear',
                                command=lambda: self.clear())
        self.solve_btn = Button(self.control_frame, text='Solve',
                                command=lambda: self.attempt())
        self.easy_btn = Button(self.control_frame, text='Easy',
                               command=lambda: self.puzzle(easy, 81 - 36))
        self.med_btn = Button(self.control_frame, text='Medium',
                              command=lambda: self.puzzle(easy, 81 - 46))
        self.hard_btn = Button(self.control_frame, text='Hard',
                               command=lambda: self.puzzle(hard, 81 - 56))
        self.easy_btn.grid(row=0, column=0)
        self.med_btn.grid(row=0, column=1)
        self.hard_btn.grid(row=0, column=2)
        self.clear_btn.grid(row=0, column=3)
        self.solve_btn.grid(row=0, column=4)

        # start
        self.root.mainloop()
Beispiel #27
0
    def __init__(self, master):

        mainframe = Frame(master)
        mainframe.pack()

        self.quitb = Button(mainframe,
                            text="QUIT",
                            fg="red",
                            command=self.daquit)
        self.quitb.pack(side=RIGHT)

        self.runb = Button(mainframe,
                           text="Run 3color",
                           command=self.runapp)
        self.runb.pack(side=LEFT)

        self.launchb = Button(mainframe,
                              text="Open in Browser",
                              command=self.launchsite)
        self.launchb.pack(side=LEFT)

        self.stopb = Button(mainframe,
                            text="Stop 3color",
                            command=self.stopapp)
        self.stopb.pack(side=TOP)
Beispiel #28
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()
Beispiel #29
0
def save(squares):
    """
    Handle the save key on the main window.
    """
    def save_button_hit():
        """
        Save key (on local window) was hit.  Save the file name entered.
        """
        text_in = save_entry.get().strip()
        if len(text_in) == 0:
            showwarning('Error', 'File name specified is empty.')
            return
        outfile = os.path.join(savedir, text_in)
        with open(outfile, 'w') as fyle:
            for sqr_info in save_squares:
                fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info]))
        top.destroy()
    top = Toplevel()
    top.geometry('180x80+800+200')
    top.title('Save a layout')
    save_squares = squares
    savedir = getdir()
    label1 = Label(top, text='File name')
    save_entry = Entry(top)
    label1.grid(row=0)
    save_entry.grid(row=0, column=1, columnspan=2)
    save_entry.focus_set()
    save_button = Button(top, text='SAVE', pady=3,
            command=save_button_hit)
    sspace = Label(top)
    sspace.grid(row=1)
    save_button.grid(row=2, column=1)
    top.mainloop()
Beispiel #30
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root,
                            width=750,
                            height=350,
                            padx=250,
                            bg="black")
        self.frame2 = Frame(self.root,
                            height=250,
                            width=750,
                            bg="black",
                            padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="logo.gif")
        starth = Button(self.frame1,
                        text="Hard",
                        bg="orange",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1,
                        text="Medium",
                        bg="teal",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1,
                        text="Easy",
                        bg="orange",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp,
              padx=10).pack(side="right")
        Label(self.frame2,
              fg="white",
              bg="black",
              text=exp,
              justify="left",
              font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H = Label(self.root,
                       text="SNAKES",
                       font=head,
                       fg="orange",
                       bg="black",
                       pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def do_after_cancel(self, a, b):
        if a != 0:
            self.w.after_cancel(a)
        if b != 0:
            self.w.after_cancel(b)

    def calldown(self, key):
        if self.hor:
            self.do_after_cancel(self.leftid, self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.do_after_cancel(self.leftid, self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.do_after_cancel(self.upid, self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.do_after_cancel(self.upid, self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root,
                        width=750,
                        height=500,
                        relief="flat",
                        highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root,
                            text="Score\n" + str(self.score),
                            bg="black",
                            fg="teal",
                            padx=25,
                            pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450,
                                       250,
                                       455,
                                       250,
                                       width=10,
                                       fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2],
                                           crd[-1] + 5,
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2],
                                           crd[-1] - 5,
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2] + 5,
                                           crd[-1],
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2] - 5,
                                           crd[-1],
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx,
                                       randy,
                                       randx + 12,
                                       randy,
                                       width=10,
                                       fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(
                int(foodcoords[-4]) - 7,
                int(foodcoords[-2]) + 7) and int(headcoords[-3]) in range(
                    int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score),
                                  bg="black",
                                  fg="teal",
                                  padx=25,
                                  pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (
                        h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0
                and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (
                    h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760
                                                        and 0 < h[1] < 500):
            return True
        return False

    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
Beispiel #31
0
            # "pilot": "GliderGeek",
            # "glider_id": "PH-790",
            # "glider_type": "LS4",
            # "logger_interval": 1,
            "waypoints": Flarm_waypoints,
            "task_name": _task_name
        }

        writer.write_flarm_task(writer, task_info)


title = Label(root,
              text="Glider-task-converter",
              font=("Helvetica", 30),
              width=20)
load_cup = Button(root, text="Load .cup file", command=get_cup_filename)
cup_filename = Label(root, text="", width=20)
write_flarm = Button(root,
                     text="Destination folder",
                     command=get_flarm_directory)
flarm_directory_name = Label(root, text="", width=20)
convert = Button(root,
                 text="Convert",
                 command=start_conversion,
                 state="disabled")
conversion_status = Label(root, text="")
filler = Label(root, text="")

title.grid(row=0, column=0, columnspan=2, pady=5)
load_cup.grid(row=1, column=0, sticky=E)
cup_filename.grid(row=1, column=1)
class DataAnnotationWindow(object):
    def __init__(self):
        self.img_Wid = 500
        self.img_Hei = 500
        self.win_wid = self.img_Wid + 200
        self.win_Hei = self.img_Hei

        # init state control variable
        self.has_select_path = False  # sign has select image path(to do data annotation) or not
        self.img_path = ''
        self.img_list = []

        # create main window
        self.mainWin = Tkinter.Tk()
        self.mainWin.geometry(str(self.win_wid) + 'x' +
                              str(self.win_Hei))  # init the size of window
        self.mainWin.title("data annotation tool")
        self.mainWin.tk.eval('package require Tix')
        # bind the key press event(space to pass, d to delete, q to quit)
        self.mainWin.bind('<KeyPress>', self._keyPressEvent)

        # create init image(a black background)
        self.img = Image.new("RGB", (self.img_Wid, self.img_Hei), (0, 0, 0))
        self.photo_img = ImageTk.PhotoImage(self.img)

        # create Canvas control
        self.cv = Canvas(self.mainWin,
                         bg='white',
                         width=self.img_Wid,
                         height=self.img_Hei)
        self.cv.create_image((0, 0), anchor=Tkinter.NW, image=self.photo_img)
        self.cv.pack(side=Tkinter.LEFT, expand=True)

        # create total Frame to lay out all components
        self.frame = Frame(self.mainWin)
        self.frame.pack(fill=Tkinter.X, expand=Tkinter.YES, side=Tkinter.LEFT)

        # create text control
        root_save_path = './data_annotation_result'
        self.entry = Entry(self.frame, state='normal')
        self.entry.pack(side=Tkinter.TOP, fill=Tkinter.X)
        self.entry.insert(0, root_save_path)
        # mkdir of annotation result
        self.categoryList = ['Pass', 'Remove']
        self.category_savepath_list = []
        for category in self.categoryList:
            cur_category_save_path = os.path.join(root_save_path, category)
            self.category_savepath_list.append(cur_category_save_path)
            if os.path.exists(cur_category_save_path) == False:
                os.mkdir(cur_category_save_path)

        # create 'START' button
        self.btn_start = Button(self.frame,
                                text='START',
                                command=self._selectPath,
                                activeforeground='blue',
                                activebackground='white',
                                bg='blue',
                                fg='white')
        self.btn_start.pack(side=Tkinter.TOP, pady=30)

        # create data annotation label button
        self.btn_dog = Button(self.frame,
                              text='Pass',
                              command=lambda: self._labelButtonClick('Pass'),
                              activeforeground='black',
                              activebackground='blue',
                              bg='white',
                              fg='black')
        self.btn_dog.pack(side=Tkinter.TOP, pady=10)

        # create data annotation label button
        self.btn_cat = Button(self.frame,
                              text='Remove',
                              command=lambda: self._labelButtonClick('Remove'),
                              activeforeground='black',
                              activebackground='blue',
                              bg='white',
                              fg='black')
        self.btn_cat.pack(side=Tkinter.TOP, pady=10)

        #NumericUpDown控件
        self.num_count = Control(self.frame,
                                 integer=True,
                                 max=-1,
                                 min=-1,
                                 value=-1,
                                 step=1,
                                 label='current Image:',
                                 command=self._showImage)
        self.num_count.label.config(font='Helvetica -14 bold')
        self.num_count.pack(side=Tkinter.TOP, pady=50)

        # create 'QUIT' button
        self.btn_quit = Button(self.frame,
                               text='QUIT',
                               command=self.mainWin.quit,
                               activeforeground='blue',
                               activebackground='white',
                               bg='red',
                               fg='white')
        self.btn_quit.pack(side=Tkinter.BOTTOM, pady=10)

    def _keyPressEvent(self, event):
        if event.keycode == 32:
            self._labelButtonClick('Pass')
        elif event.keycode == 68:
            self._labelButtonClick('Remove')
        elif event.keycode == 81:
            self.mainWin.destroy()

    def _showImage(self, ev=None):
        if self.has_select_path:
            if int(self.num_count['value']) == -1:
                # create init image(a black background)
                self.img = Image.new("RGB", (self.img_Wid, self.img_Hei),
                                     (0, 0, 0))
                self.photo_img = ImageTk.PhotoImage(self.img)
                self.cv.create_image((0, 0),
                                     anchor=Tkinter.NW,
                                     image=self.photo_img)
                return
            else:
                img_cur_path = self.img_list[int(self.num_count['value'])]
                self.img = Image.open(img_cur_path).resize(
                    (self.img_Wid, self.img_Hei))
                self.photo_img = ImageTk.PhotoImage(self.img)
                self.cv.create_image((0, 0),
                                     anchor=Tkinter.NW,
                                     image=self.photo_img)

    def _labelButtonClick(self, label):
        cur_idx = int(self.num_count['value'])
        if cur_idx != -1:
            # save cur image's annotation result
            catgory_idx = self.categoryList.index(label)
            save_path = self.category_savepath_list[catgory_idx]
            cur_img_name = self.img_list[cur_idx].split('\\')[-1]
            save_path = os.path.join(save_path, cur_img_name)
            self.img.save(save_path)

            # check has next image or not
            if cur_idx + 1 < len(self.img_list):
                self.num_count['value'] = str(cur_idx + 1)
            else:
                tkMessageBox.showinfo(
                    title='thanks',
                    message='all the data annotation mission has finished~')

    def _selectPath(self):
        self.img_path = tkFileDialog.askdirectory()
        self.img_list = self._getImagList()
        if len(self.img_list) > 0:
            self.has_select_path = True
            self.num_count.config(max=len(self.img_list))
            self.num_count['value'] = str(0)
        else:
            self.has_select_path = False
            self.num_count['value'] = str(-1)
            self.num_count.config(max=-1)
            tkMessageBox.showwarning(
                'warning',
                'No available images detected! please re-select image path and start'
            )

    def _getImagList(self):
        img_list = []
        img_suffix = ['jpg', 'png', 'jpeg', 'bmp']
        for root, dirs, files in os.walk(self.img_path):
            for file_name in files:
                suffix = file_name.split('.')[-1]
                if suffix in img_suffix:
                    cur_img_path = os.path.join(root, file_name)
                    img_list.append(cur_img_path)
        return img_list
Beispiel #33
0
    def __init__(self, master, label=""):

        self.label = Label(master, text=label)
        self.entry = Entry(master)
        self.button = Button(master, text="Open", command=self.getLoadName)
        self.options = {}
Beispiel #34
0
    def init_gui(self):
        # create root window
        self.rootWindow = Tk()
        self.statusText = StringVar(value=self.statusStr)
        self.set_status_str("Simulation not yet started")

        self.rootWindow.wm_title(self.titleText)
        self.rootWindow.protocol('WM_DELETE_WINDOW', self.quit_gui)
        self.rootWindow.geometry('550x700')
        self.rootWindow.columnconfigure(0, weight=1)
        self.rootWindow.rowconfigure(0, weight=1)

        self.frameSim = Frame(self.rootWindow)

        self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP)
        self.status = Label(self.rootWindow,
                            width=40,
                            height=3,
                            relief=SUNKEN,
                            bd=1,
                            textvariable=self.statusText)
        self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO)

        self.runPauseString = StringVar()
        self.runPauseString.set("Run")
        self.buttonRun = Button(self.frameSim,
                                width=30,
                                height=2,
                                textvariable=self.runPauseString,
                                command=self.run_event)
        self.buttonRun.pack(side=TOP, padx=5, pady=5)

        self.show_help(
            self.buttonRun,
            "Runs the simulation (or pauses the running simulation)")
        self.buttonStep = Button(self.frameSim,
                                 width=30,
                                 height=2,
                                 text="Step Once",
                                 command=self.step_once)
        self.buttonStep.pack(side=TOP, padx=5, pady=5)
        self.show_help(self.buttonStep, "Steps the simulation only once")
        self.buttonReset = Button(self.frameSim,
                                  width=30,
                                  height=2,
                                  text="Reset",
                                  command=self.reset_model)
        self.buttonReset.pack(side=TOP, padx=5, pady=5)
        self.show_help(self.buttonReset, "Resets the simulation")

        for param in self.model.params:
            var_text = self.param_gui_names.get(param, param)
            can = Canvas(self.frameSim)
            lab = Label(can,
                        width=25,
                        height=1 + var_text.count('\n'),
                        text=var_text,
                        anchor=W,
                        takefocus=0)
            lab.pack(side='left')
            ent = Entry(can, width=11)
            val = getattr(self.model, param)
            if isinstance(val, bool):
                val = int(val)  # Show 0/1 which can convert back to bool
            ent.insert(0, str(val))
            ent.pack(side='left')
            can.pack(side='top')
            self.param_entries[param] = ent
        if self.param_entries:
            self.buttonSaveParameters = Button(
                self.frameSim,
                width=50,
                height=1,
                command=self.save_parameters_cmd,
                text="Save parameters to the running model",
                state=DISABLED)
            self.show_help(
                self.buttonSaveParameters,
                "Saves the parameter values.\n Not all values may take effect "
                "on a running model\n A model reset might be required.")
            self.buttonSaveParameters.pack(side='top', padx=5, pady=5)
            self.buttonSaveParametersAndReset = Button(
                self.frameSim,
                width=50,
                height=1,
                command=self.save_parameters_and_reset_cmd,
                text="Save parameters to the model and reset the model")
            self.show_help(
                self.buttonSaveParametersAndReset,
                "Saves the given parameter values and resets the model")
            self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5)

        can = Canvas(self.frameSim)
        lab = Label(can,
                    width=25,
                    height=1,
                    text="Step size ",
                    justify=LEFT,
                    anchor=W,
                    takefocus=0)
        lab.pack(side='left')
        self.stepScale = Scale(can,
                               from_=1,
                               to=500,
                               resolution=1,
                               command=self.change_step_size,
                               orient=HORIZONTAL,
                               width=25,
                               length=150)
        self.stepScale.set(self.stepSize)
        self.show_help(
            self.stepScale,
            "Skips model redraw during every [n] simulation steps\n" +
            " Results in a faster model run.")
        self.stepScale.pack(side='left')
        can.pack(side='top')

        can = Canvas(self.frameSim)
        lab = Label(can,
                    width=25,
                    height=1,
                    text="Step visualization delay in ms ",
                    justify=LEFT,
                    anchor=W,
                    takefocus=0)
        lab.pack(side='left')
        self.stepDelay = Scale(can,
                               from_=0,
                               to=max(2000, self.timeInterval),
                               resolution=10,
                               command=self.change_step_delay,
                               orient=HORIZONTAL,
                               width=25,
                               length=150)
        self.stepDelay.set(self.timeInterval)
        self.show_help(
            self.stepDelay, "The visualization of each step is " +
            "delays by the given number of " + "milliseconds.")
        self.stepDelay.pack(side='left')
        can.pack(side='top')
Beispiel #35
0
class GUI:
    def __init__(self,
                 model,
                 title='PyCX Simulator',
                 interval=0,
                 step_size=1,
                 param_gui_names=None):
        self.model = model
        self.titleText = title
        self.timeInterval = interval
        self.stepSize = step_size
        self.param_gui_names = param_gui_names
        if param_gui_names is None:
            self.param_gui_names = {}
        self.param_entries = {}
        self.statusStr = ""
        self.running = False
        self.modelFigure = None
        self.currentStep = 0

        self.init_gui()

    def init_gui(self):
        # create root window
        self.rootWindow = Tk()
        self.statusText = StringVar(value=self.statusStr)
        self.set_status_str("Simulation not yet started")

        self.rootWindow.wm_title(self.titleText)
        self.rootWindow.protocol('WM_DELETE_WINDOW', self.quit_gui)
        self.rootWindow.geometry('550x700')
        self.rootWindow.columnconfigure(0, weight=1)
        self.rootWindow.rowconfigure(0, weight=1)

        self.frameSim = Frame(self.rootWindow)

        self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP)
        self.status = Label(self.rootWindow,
                            width=40,
                            height=3,
                            relief=SUNKEN,
                            bd=1,
                            textvariable=self.statusText)
        self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO)

        self.runPauseString = StringVar()
        self.runPauseString.set("Run")
        self.buttonRun = Button(self.frameSim,
                                width=30,
                                height=2,
                                textvariable=self.runPauseString,
                                command=self.run_event)
        self.buttonRun.pack(side=TOP, padx=5, pady=5)

        self.show_help(
            self.buttonRun,
            "Runs the simulation (or pauses the running simulation)")
        self.buttonStep = Button(self.frameSim,
                                 width=30,
                                 height=2,
                                 text="Step Once",
                                 command=self.step_once)
        self.buttonStep.pack(side=TOP, padx=5, pady=5)
        self.show_help(self.buttonStep, "Steps the simulation only once")
        self.buttonReset = Button(self.frameSim,
                                  width=30,
                                  height=2,
                                  text="Reset",
                                  command=self.reset_model)
        self.buttonReset.pack(side=TOP, padx=5, pady=5)
        self.show_help(self.buttonReset, "Resets the simulation")

        for param in self.model.params:
            var_text = self.param_gui_names.get(param, param)
            can = Canvas(self.frameSim)
            lab = Label(can,
                        width=25,
                        height=1 + var_text.count('\n'),
                        text=var_text,
                        anchor=W,
                        takefocus=0)
            lab.pack(side='left')
            ent = Entry(can, width=11)
            val = getattr(self.model, param)
            if isinstance(val, bool):
                val = int(val)  # Show 0/1 which can convert back to bool
            ent.insert(0, str(val))
            ent.pack(side='left')
            can.pack(side='top')
            self.param_entries[param] = ent
        if self.param_entries:
            self.buttonSaveParameters = Button(
                self.frameSim,
                width=50,
                height=1,
                command=self.save_parameters_cmd,
                text="Save parameters to the running model",
                state=DISABLED)
            self.show_help(
                self.buttonSaveParameters,
                "Saves the parameter values.\n Not all values may take effect "
                "on a running model\n A model reset might be required.")
            self.buttonSaveParameters.pack(side='top', padx=5, pady=5)
            self.buttonSaveParametersAndReset = Button(
                self.frameSim,
                width=50,
                height=1,
                command=self.save_parameters_and_reset_cmd,
                text="Save parameters to the model and reset the model")
            self.show_help(
                self.buttonSaveParametersAndReset,
                "Saves the given parameter values and resets the model")
            self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5)

        can = Canvas(self.frameSim)
        lab = Label(can,
                    width=25,
                    height=1,
                    text="Step size ",
                    justify=LEFT,
                    anchor=W,
                    takefocus=0)
        lab.pack(side='left')
        self.stepScale = Scale(can,
                               from_=1,
                               to=500,
                               resolution=1,
                               command=self.change_step_size,
                               orient=HORIZONTAL,
                               width=25,
                               length=150)
        self.stepScale.set(self.stepSize)
        self.show_help(
            self.stepScale,
            "Skips model redraw during every [n] simulation steps\n" +
            " Results in a faster model run.")
        self.stepScale.pack(side='left')
        can.pack(side='top')

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

    def set_status_str(self, new_status):
        self.statusStr = new_status
        self.statusText.set(self.statusStr)

    # model control functions
    def change_step_size(self, val):
        self.stepSize = int(val)

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

    def save_parameters_cmd(self):
        for param, entry in self.param_entries.items():
            val = entry.get()
            if isinstance(getattr(self.model, param), bool):
                val = bool(int(val))
            setattr(self.model, param, val)
            # See if the model changed the value (e.g. clipping)
            new_val = getattr(self.model, param)
            if isinstance(new_val, bool):
                new_val = int(new_val)
            entry.delete(0, END)
            entry.insert(0, str(new_val))
        self.set_status_str("New parameter values have been set")

    def save_parameters_and_reset_cmd(self):
        self.save_parameters_cmd()
        self.reset_model()

    def run_event(self):
        if not self.running:
            self.running = True
            self.rootWindow.after(self.timeInterval, self.step_model)
            self.runPauseString.set("Pause")
            self.buttonStep.configure(state=DISABLED)
            if self.param_entries:
                self.buttonSaveParameters.configure(state=NORMAL)
                self.buttonSaveParametersAndReset.configure(state=DISABLED)
        else:
            self.stop_running()

    def stop_running(self):
        self.running = False
        self.runPauseString.set("Continue Run")
        self.buttonStep.configure(state=NORMAL)
        self.draw_model()
        if self.param_entries:
            self.buttonSaveParameters.configure(state=NORMAL)
            self.buttonSaveParametersAndReset.configure(state=NORMAL)

    def step_model(self):
        if self.running:
            if self.model.step() is True:
                self.stop_running()
            self.currentStep += 1
            self.set_status_str("Step " + str(self.currentStep))
            self.status.configure(foreground='black')
            if self.currentStep % self.stepSize == 0:
                self.draw_model()
            self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize),
                                  self.step_model)

    def step_once(self):
        self.running = False
        self.runPauseString.set("Continue Run")
        self.model.step()
        self.currentStep += 1
        self.set_status_str("Step " + str(self.currentStep))
        self.draw_model()
        if self.param_entries:
            self.buttonSaveParameters.configure(state=NORMAL)
        self.currentStep += 1

    def reset_model(self):
        self.running = False
        self.runPauseString.set("Run")
        self.model.reset()
        self.currentStep = 0
        self.set_status_str("Model has been reset")
        self.draw_model()

    def get_point_color(self, data):
        point_colors = []
        for i in data:
            point_colors.append([0, 0, 0, i / self.model.k])
        return point_colors

    def draw_model(self):

        if self.modelFigure is None:
            self.modelFigure = plt.figure()

            ax = self.modelFigure.add_subplot(111)
            xax = ax.xaxis
            xax.tick_top()

            points = self.init_values()

            ax.axis([0, len(points[0]) + 1, 0, 100])
            ax.invert_yaxis()

            plt.scatter(points[0],
                        points[1],
                        c=self.get_point_color(points[2]),
                        s=5,
                        marker='s')
            plt.gray()
            plt.ion()
            dpi = self.modelFigure.get_dpi()
            self.modelFigure.set_size_inches(550.0 / float(dpi),
                                             550.0 / float(dpi))
            self.modelFigure.canvas.manager.window.resizable("false", "false")
            plt.show()

        if sys.platform == 'darwin':
            self.modelFigure.canvas.manager.show()
        else:
            points = self.init_values()
            plt.scatter(points[0],
                        points[1],
                        c=self.get_point_color(points[2]),
                        s=5,
                        marker='s')
            self.modelFigure.canvas.manager.window.update()

    def init_values(self):
        data = self.model.draw()
        x = []
        point_value = 1
        for _ in data:
            x.append(point_value)
            point_value += 1

        t = np.empty(len(x))
        t.fill(self.currentStep)
        return [x, t, data]

    def start(self):
        if self.model.step.__doc__:
            self.show_help(self.buttonStep, self.model.step.__doc__.strip())

        self.model.reset()
        self.draw_model()
        self.rootWindow.mainloop()

    def quit_gui(self):
        plt.close('all')
        self.rootWindow.quit()
        self.rootWindow.destroy()

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

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

        widget.bind("<Enter>", lambda e: set_text(self))
        widget.bind("<Leave>", lambda e: show_help_leave(self))
Beispiel #36
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master

        # self.master.protocol("WM_DELETE_WINDOW", self.onWindowClose)

        # Load defaults from the config file
        self.configFilename = os.path.expanduser('~/.trainingparser')
        self.config = self.readConfig(self.configFilename)
        self.templateFileName = self.config['TemplateFile']
        self.programFileName = self.config['ProgramFile']
        self.maxFileName = self.config['MaxFile']

        self.pack()
        self.createWidgets()

    # def onWindowClose(self):
    #     if self.master:
    #         print 'DESTROYING'
    #         self.master.destroy()

    def readConfig(self, filename):
        config = {}
        if os.path.exists(filename):
            with open(filename) as f:
                return json.load(f)
        else:
            return {
                'TemplateFile': None,
                'ProgramFile': None,
                'MaxFile': None,
                'OutputDirectory': os.path.expanduser('~'),
            }

    def writeConfig(self, config, filename):
        with open(filename, 'w') as f:
            json.dump(config, f, indent=2)

    def createWidgets(self):

        self.menuBar = Menu(self.master)
        self.fileMenu = Menu(self.menuBar, tearoff=0)
        self.fileMenu.add_command(label="Exit", command=self.master.destroy)
        self.menuBar.add_cascade(label="File", menu=self.fileMenu)
        self.master.config(menu=self.menuBar)

        self.openProgramButton = Button(self, text='Open Program File', command=self.openProgramFile)
        self.openProgramButton.grid(row=0, column=0, sticky=W)
        self.programLabelText = StringVar()
        self.programLabelText.set('No Program File' if self.programFileName is None else self.programFileName)
        self.programLabel = Label(self, textvariable=self.programLabelText)
        self.programLabel.grid(row=0, column=1, sticky=W)

        self.openMaxButton = Button(self, text='Open Max File', command=self.openMaxFile)
        self.openMaxButton.grid(row=1, column=0, sticky=W)
        self.maxLabelText = StringVar()
        self.maxLabelText.set('No Max File' if self.maxFileName is None else self.maxFileName)
        self.maxLabel = Label(self, textvariable=self.maxLabelText)
        self.maxLabel.grid(row=1, column=1, sticky=W)

        self.openTemplateButton = Button(self, text='Open Template File', command=self.openTemplateFile)
        self.openTemplateButton.grid(row=2, column=0, sticky=W)
        self.templateLabelText = StringVar()
        self.templateLabelText.set('No Template File' if self.templateFileName is None else self.templateFileName)
        self.templateLabel = Label(self, textvariable=self.templateLabelText)
        self.templateLabel.grid(row=2, column=1, sticky=W)

        self.programNameLabel = Label(self, text='Program Name')
        self.programNameLabel.grid(row=3, column=0, sticky=W)
        self.programNameField = Entry(self, width=60)
        self.programNameField.insert(END, "Waxman's Gym Programming")
        self.programNameField.grid(row=3, column=1, sticky=W)

        self.openMaxButton = Button(self, text='Generate!', command=self.generate)
        self.openMaxButton.grid(row=4, column=0, columnspan=2)

        self.statusText = Text(self)
        self.statusText.grid(row=5, column=0, columnspan=2)

    def quit(self):
        self.master.destroy()

    def generate(self):
        try:
            self.statusText.insert(END, 'Parsing max file...')
            with open(self.maxFileName) as maxFile:
                maxes = trainingparser.parseMaxes(maxFile)
            self.statusText.insert(END, 'Success!\n')
        except RuntimeError as e:
            self.statusText.insert(END, 'Failed!\n')
            self.statusText.insert(END, e.message)
            return
        except Exception as e:
            self.statusText.insert(END, 'Failed!\n')
            self.statusText.insert(END, 'Unknown Error! Please send Rand your input and max files, and the following message:\n')
            self.statusText.insert(END, str(e) + '\n')
            return

        try:
            self.statusText.insert(END, 'Parsing input file...')
            with open(self.programFileName) as programFile:
                program = trainingparser.parseTraining(programFile, maxes)
            self.statusText.insert(END, 'Success!\n')
        except RuntimeError as e:
            self.statusText.insert(END, 'Failed!\n')
            self.statusText.insert(END, e.message)
            return
        except Exception as e:
            self.statusText.insert(END, 'Failed!\n')
            self.statusText.insert(END, 'Unknown Error! Please send Rand your input and max files, and the following message:\n')
            self.statusText.insert(END, str(e) + '\n')
            return

        try:
            self.statusText.insert(END, 'Generating output HTML file...')
            outFileName = tkFileDialog.asksaveasfilename(message='Output HTML')
            with open(outFileName, 'w') as outfile:
                trainingparser.writeJinja(program=program, out=outfile, template=self.templateFile)
            self.statusText.insert(END, 'Success!\n')
        except Exception as e:
            self.statusText.insert(END, 'Failed!\n')
            self.statusText.insert(
                END, 'Unknown Error! Please send Rand your input, template and max files, and the following message:\n')
            self.statusText.insert(END, str(e) + '\n')
            return

    def openProgramFile(self):
        Tk().withdraw()
        self.programFileName = tkFileDialog.askopenfilename(parent=self)
        self.config['ProgramFile'] = self.programFileName
        self.writeConfig(self.config, self.configFilename)
        self.programLabelText.set(self.programFileName)
        self.statusText.insert(END, 'Opened input file: {}\n'.format(self.programFileName))

    def openTemplateFile(self):
        Tk().withdraw()
        self.templateFileName = tkFileDialog.askopenfilename(parent=self)
        self.config['TemplateFile'] = self.templateFileName
        self.writeConfig(self.config, self.configFilename)
        self.templateLabelText.set(self.templateFileName)
        self.statusText.insert(END, 'Opened template file: {}\n'.format(self.templateFileName))

    def openMaxFile(self):
        Tk().withdraw()
        self.maxFileName = tkFileDialog.askopenfilename(parent=self)
        self.config['MaxFile'] = self.maxFileName
        self.writeConfig(self.config, self.configFilename)
        self.maxLabelText.set(self.maxFileName)
        self.statusText.insert(END, 'Opened max file: {}\n'.format(self.maxFileName))
def kali():
    p = float(str1.get())
    q = float(str2.get())
    r = p * q
    L.config(text=r)


def bagi():
    p = float(str1.get())
    q = float(str2.get())
    r = p / q
    L.config(text=r)


B1 = Button(my_app, text='+', command=tambah)
B1.grid(row=2, column=0)
B2 = Button(my_app, text='-', command=kurang)
B2.grid(row=2, column=1)
B3 = Button(my_app, text='x', command=kali)
B3.grid(row=2, column=2)
B4 = Button(my_app, text=':', command=bagi)
B4.grid(row=2, column=3)

L3 = Label(my_app, text='Hasil')
L3.grid(row=3, column=1)
L = Label(my_app, text='0')
L.grid(row=3, column=2)

my_app.mainloop()
class File_Entry(Frame):
    ''' Quite self explanatoy...
    creates a row in which is possible to search for a file'''
    def __init__(self, master=None, **kwargs):
        # this was a nice frame, but considering that needs
        # from popup import FilePopUp, was moved elsewere
        # meaning this is not as low level as tk_lib

        #if not master and options.get('parent'):
        #    master = options['parent']
        self.master = master
        Frame.__init__(self, master)

        self.entries_txt = None
        self.entries_val = None

        if 'e_txt' in kwargs.keys():
            self.entries_txt = kwargs['e_txt']
        if 'e_val' in kwargs.keys():
            self.entries_val = kwargs['e_val']

        # File extension
        if 'f_ext' in kwargs.keys():
            self.file_ext = kwargs['f_ext']
        else:
            self.file_ext = [
                '.' + self.entries_val.split('.')[-1],
            ]
        # File extension description
        if 'f_ext_d' in kwargs.keys():
            self.fex_description = kwargs['f_ext_d']
        else:
            self.fex_description = [
                self.entries_txt,
            ]

        # file icon image, part of the master's personal library
        self.file_img = self.master.img['file']
        # inner class object container
        self._entry = []
        self._button = []
        self._strvar = StringVar()

        self.createWidgets()

    def createWidgets(self):
        '''creates the row content and stores the
           objects
        '''
        # INIT
        file_row = Frame(self)
        fi_text = self.entries_txt
        _def_file_ = self.entries_val
        f_ext_txt = ()
        for i in range(len(self.file_ext)):
            f_ext_txt += ((self.fex_description[i], self.file_ext[i]), )

        # Building
        _f_labels = format_dec([file_row, fi_text], _pack_=False)

        self._entry = Entry(file_row, width=13, textvariable=self._strvar)
        self._entry.insert('end', _def_file_)

        self._entry.bind("<Key>", lambda e: "break")  # Magic

        self._entry.xview_moveto(1)
        self._button = Button(
            file_row,
            image=self.file_img,
            command=(lambda El=self._entry: self.browsefile(El, f_ext_txt)))

        # Just packing
        format_dec(_f_labels, _create_=False)
        self._entry.pack(side='left', expand='yes', fill='x')
        self._button.pack(side='right', padx=0, pady=0)
        file_row.pack(side='top', fill='x', pady=3)

    def browsefile(self, entry, ext=None):
        '''Browse a file <button> action binder'''

        pop = FilePopUp(master=self)
        if ext <> None and isinstance(ext, tuple):
            #print '--- ', ext, type(ext)
            pop.filetypes['filetypes'] = ext  #(("All","*"),) #
        filepath = pop.getfilepath()

        try:
            fito = open(filepath, "r")
            fito.close()
            entry.delete(0, 'end')
            entry.insert(0, filepath)
            entry.xview_moveto(1)
        except:
            if filepath not in ['', ()]:
                print "Could not open File: ", filepath
                print exc_info()[1]

    def setter(self, value):

        if value:
            self.enable_entr()
        else:
            self.disable_entr()

    def disable_entr(self):
        self._entry.configure(state='disabled')
        self._button.configure(state='disabled')

    def enable_entr(self):
        self._entry.configure(state='normal')
        self._button.configure(state='normal')
Beispiel #39
0
    def popupControls(self, tl=None):
        """
        Popup control panel for interval.
        """
        from direct.showbase import TkGlobal
        import math
        # I moved this here because Toontown does not ship Tk
        from Tkinter import Toplevel, Frame, Button, LEFT, X
        import Pmw
        from direct.tkwidgets import EntryScale
        if tl == None:
            tl = Toplevel()
            tl.title('Interval Controls')
        outerFrame = Frame(tl)

        def entryScaleCommand(t, s=self):
            s.setT(t)
            s.pause()

        self.es = es = EntryScale.EntryScale(
            outerFrame,
            text=self.getName(),
            min=0,
            max=math.floor(self.getDuration() * 100) / 100,
            command=entryScaleCommand)
        es.set(self.getT(), fCommand=0)
        es.pack(expand=1, fill=X)
        bf = Frame(outerFrame)

        # Jump to start and end
        def toStart(s=self, es=es):
            s.clearToInitial()
            es.set(0, fCommand=0)

        def toEnd(s=self):
            s.pause()
            s.setT(s.getDuration())
            es.set(s.getDuration(), fCommand=0)
            s.pause()

        jumpToStart = Button(bf, text='<<', command=toStart)

        # Stop/play buttons
        def doPlay(s=self, es=es):
            s.resume(es.get())

        stop = Button(bf, text='Stop', command=lambda s=self: s.pause())
        play = Button(bf, text='Play', command=doPlay)
        jumpToEnd = Button(bf, text='>>', command=toEnd)
        jumpToStart.pack(side=LEFT, expand=1, fill=X)
        play.pack(side=LEFT, expand=1, fill=X)
        stop.pack(side=LEFT, expand=1, fill=X)
        jumpToEnd.pack(side=LEFT, expand=1, fill=X)
        bf.pack(expand=1, fill=X)
        outerFrame.pack(expand=1, fill=X)

        # Add function to update slider during setT calls
        def update(t, es=es):
            es.set(t, fCommand=0)

        if not hasattr(self, "setTHooks"):
            self.setTHooks = []
        self.setTHooks.append(update)

        # Clear out function on destroy
        def onDestroy(e, s=self, u=update):
            if u in s.setTHooks:
                s.setTHooks.remove(u)

        tl.bind('<Destroy>', onDestroy)
Beispiel #40
0
class Processor:
    def __init__(self, master):
        self.master = master
        master.geometry('500x500')
        master.title("Operation Processor")

        """ Prima problema """
        self.prob1 = Label(master, text="PROBLEMA 1:", font=("Helvetica bold", 10))
        self.prob1.pack()
        self.add_button = Button(master, text="Determine smallest number", fg = "blue", bg="white", command=lambda: self.update("prec"))
        self.min_no = IntVar()
        self.min_label = Label(master, textvariable=self.min_no)
        self.min_label.pack()

        """ A doua problema """
        self.prob2 = Label(master, text="PROBLEMA 2.1:", font=("Helvetica bold", 10))
        self.prob2.pack()
        self.add_button2 = Button(master, text="Check sum associativity", fg="blue", bg="white", command=lambda: self.update("assoc"))
        self.min_no2 = IntVar()
        self.min_label2 = Label(master, textvariable=self.min_no2)
        self.min_label2.pack()

        """ Al doilea subpunct - Problema 2"""
        self.prob22 = Label(master, text="PROBLEMA 2.2:", font=("Helvetica bold", 10))
        self.prob22.pack()
        self.add_button22 = Button(master, text="Determine element", fg="blue", bg="white", command=lambda: self.update("el"))
        self.min_no3 = IntVar()
        self.min_label3 = Label(master, textvariable=self.min_no3)
        self.min_label3.pack()

        """ A treia problema """
        self.prob3 = Label(master, text="PROBLEMA 3:", font=("Helvetica bold", 10))
        self.prob3.pack()
        self.prob31 = Label(master, text="Input n value:", font=("Helvetica bold", 10))
        self.prob31.pack()
        self.n_min = Entry(master)
        self.n_min.pack()

        # LAYOUT
        self.prob1.grid(row=0, column=0, sticky=W, pady = (20, 20))
        self.add_button.grid(row=0, column=1)
        self.min_label.grid(row=0, column=2)

        self.prob2.grid(row=2, column=0, sticky=W, pady = (20, 20))
        self.add_button2.grid(row=2, column=1)
        self.min_label2.grid(row=2, column=2)

        self.prob22.grid(row=4, column=0, sticky=W, pady = (20, 20))
        self.add_button22.grid(row=4, column=1)
        self.min_label3.grid(row=4, column=2)

        self.prob3.grid(row=6, column=0, sticky=W, pady = (5, 5))
        self.prob31.grid(row=7, column=0, sticky=W)
        self.n_min.grid(row=7, column=1, sticky=W)

    def update(self, method):
        if method == "prec":
            self.min_no.set(machine_precision_sum()[1])
        if method == "assoc":
            self.min_no2.set(check_non_associativity())
        if method == "el":
            self.min_no3.set(check_multiplication_associativity()[0])
Beispiel #41
0
REGU = 'regu'

SIGNS = {
    'do not enter ': CRIT,
    'railroad crossing': WARN,
    '55\nspeed limit': REGU,
    'wrong way': CRIT,
    'merging traffic': WARN,
    'one way': REGU
}

critCB = lambda: showerror('Error', "Error Button Pressed!")
warnCB = lambda: showwarning('Warnning', 'Warnning Button Pressed!')
infoCB = lambda: showinfo('Info', 'Info Button Pressed!')

top = Tk()
top.title('Road Signs')
Button(top, text='QUIT', command=top.quit, bg='red', fg='black').pack()

MyButton = pto(Button, top)
CritButton = pto(MyButton, command=critCB, bg='white', fg='red')
WarnButton = pto(MyButton, command=warnCB, bg='goldenrod1')
ReguButton = pto(MyButton, command=infoCB, bg='white')

for eachSign in SIGNS:
    signType = SIGNS[eachSign]
    cmd = '%sButton(text=%r%s).pack(fill=X,expand=True)' % (signType.title(
    ), eachSign, '.upper()' if signType == CRIT else '.title()')
    eval(cmd)

top.mainloop()
Beispiel #42
0
    def __init__(self, master):

        def center(win):
            win.update_idletasks()
            width = win.winfo_width()
            height = win.winfo_height()
            x = (win.winfo_screenwidth() // 4) - (width // 2) + 40
            y = (win.winfo_screenheight() // 4) - (height // 2) + 40
            win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

        def callback(event):
            event.widget.focus_set()
            print "clicked at", event.x, event.y

            if self.add_tasks_flg.get() == 1:
                self.enter_task(event)


        master.title("Map Interface")
        master.minsize(width=1000, height=750)
        master.maxsize(width=1000, height=750)
        master.config(bg=BKG_COLOUR)
        self.master = master

        # Canvas for overlaying map
        self.map_canvas = Canvas(master, width=CANVAS_W, height=CANVAS_H, bg='gray85', highlightthickness=0)
        self.map_canvas.pack(side='right',padx=50)
        self.map_canvas.bind("<Button-1>", callback)
        global CANVAS_PTR
        CANVAS_PTR = self.map_canvas
        self.master.update()
        w = self.map_canvas.winfo_width()
        h = self.map_canvas.winfo_height()
        # Overlay a grid
        for i in range(0,w,SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(i,0,i,h,dash=1)
        for i in range(0,h,SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(0,i,w,i,dash=1)


        # Load in flame icon from flame.gif
        self.flame_icon = PhotoImage(file="flame.gif")
        # Load in the drone icon from drone.gif
        global DRONE_ICON
        DRONE_ICON = PhotoImage(file="drone.gif")

        buttons_frame = Canvas(master, width=163, height=140, bg=BUTTONS_BKG_COLOUR, highlightthickness=1, highlightbackground='dim grey')
        buttons_frame.place(x=40,y=230)

        # Define UI buttons
        self.add_tasks_flg = IntVar()
        self.add_tasks_b = Checkbutton(master, text="Add Tasks", variable=self.add_tasks_flg, highlightbackground=BUTTONS_BKG_COLOUR, background=BUTTONS_BKG_COLOUR)
        self.add_tasks_b.place(x=77,y=270)

        self.clear_wp_b = Button(master, text='Clear Tasks', command=self.clear_wp, highlightbackground=BUTTONS_BKG_COLOUR)
        self.clear_wp_b.config(width=10)
        self.clear_wp_b.place(x=65, y=300)
        
        '''
        self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR)
        self.gen_wp_file_b.config(width=20)
        self.gen_wp_file_b.place(x=20, y=250)
        '''

        '''
        self.land_b = Button(master, text='Land', command=self.land, highlightbackground=BUTTONS_BKG_COLOUR)
        self.land_b.config(width=10)
        self.land_b.place(x=65, y=350)
        '''


        # Set up coordinate system conversion and display corners of room:
        file_obj  = open('antenna_locations.txt', 'r')
        anchors = []
        for line in file_obj:
            cur_anchors = map(float, line.split())
            anchors.append(cur_anchors)
        file_obj.close()
        anchors = (np.array(anchors)).T

        # Find largest (abs) x and y values to use a reference for conversion ratio
        x_vals = anchors[0]
        largest_x_val = x_vals[np.argmax(abs(x_vals))]
        y_vals = anchors[1]
        largest_y_val = y_vals[np.argmax(abs(y_vals))]

        if largest_x_val > largest_y_val:
            largest_y_val = largest_x_val
        else:
            largest_x_val = largest_y_val

        global m_per_pixel_x
        m_per_pixel_x = float(largest_x_val/(CANVAS_W/2))
        global m_per_pixel_y
        m_per_pixel_y = float(largest_y_val/(CANVAS_H/2))

        # Place antenna (anchors) on UI
        anchors = anchors.T
        for cur_anchor in anchors:
            x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W/2
            y_pixel_loc = -1*(cur_anchor[1] / m_per_pixel_y) + CANVAS_H/2

            # Draw antenna @ location
            global ANTENNA_LIST
            antenna_id = self.map_canvas.create_oval(x_pixel_loc-15,y_pixel_loc-15,x_pixel_loc+15,y_pixel_loc+15,fill='red')
       

        self.master.update()
Beispiel #43
0
 def __init__(self,master,position,onClick):
     self.master=master
     self.position = position
     self.photo = PhotoImage(file="Assets/circle.gif")
     self.UiOption = Button(self.master, image=self.photo, background="white", command=lambda: onClick(position))
     self.UiOption.grid(row=position.Row, column=position.Column)
    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()
if sys.version_info < (3, 0):
    from Tkinter import Tk, Label, Button, LEFT, RIGHT
else:
    from tkinter import Tk, Label, Button, LEFT, RIGHT


def exit_btn_callback(evt):
    """Callback function to handle the button click event.

    :param Event evt: the instance of class Event from tkinter module.
    """
    print("Inside exit_btn_callback. Event object is: {0}".format(evt))


if __name__ == '__main__':

    # Create the main window or Tk instance
    mainwin = Tk()
    mainwin.geometry("140x40")

    # Create a label widget and 'pack' it in a row (or column)
    lbl = Label(mainwin, text="Hello World!", bg='yellow')
    lbl.pack(side=LEFT)
    exit_button = Button(mainwin, text='Exit')

    # Bind the button click event to function exit_btn_callback
    exit_button.bind("<Button-1>", exit_btn_callback)
    exit_button.pack(side=RIGHT)
    mainwin.mainloop()
Beispiel #46
0
def xit():
    root.destroy()
    exit(0)


root = Tk()
root.geometry("320x240")
root.title("RESULTS GENERATOR V2  -- KAILASH RAMESH")

dl = Label(root, text="Enter DOB: ")
de = Entry(root)
ll = Label(root, text="Enter the Lower Limit: ")
le = Entry(root)
ul = Label(root, text="Enter the Upper Limit: ")
ue = Entry(root)
sub = Button(root, text="GENERATE!", command=operation)
xyt = Button(root, text="EXIT", command=xit)
mod = Button(root, text="Adjust Delays", command=dly)

dl.place(x=20, y=40)
de.place(x=160, y=40)
ll.place(x=20, y=80)
le.place(x=160, y=80)
ul.place(x=20, y=120)
ue.place(x=160, y=120)
sub.place(x=80, y=170)
xyt.place(x=165, y=170)
mod.place(x=210, y=170)
root.mainloop()
Beispiel #47
0
class MapUI:
    
    def __init__(self, master):

        def center(win):
            win.update_idletasks()
            width = win.winfo_width()
            height = win.winfo_height()
            x = (win.winfo_screenwidth() // 4) - (width // 2) + 40
            y = (win.winfo_screenheight() // 4) - (height // 2) + 40
            win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

        def callback(event):
            event.widget.focus_set()
            print "clicked at", event.x, event.y

            if self.add_tasks_flg.get() == 1:
                self.enter_task(event)


        master.title("Map Interface")
        master.minsize(width=1000, height=750)
        master.maxsize(width=1000, height=750)
        master.config(bg=BKG_COLOUR)
        self.master = master

        # Canvas for overlaying map
        self.map_canvas = Canvas(master, width=CANVAS_W, height=CANVAS_H, bg='gray85', highlightthickness=0)
        self.map_canvas.pack(side='right',padx=50)
        self.map_canvas.bind("<Button-1>", callback)
        global CANVAS_PTR
        CANVAS_PTR = self.map_canvas
        self.master.update()
        w = self.map_canvas.winfo_width()
        h = self.map_canvas.winfo_height()
        # Overlay a grid
        for i in range(0,w,SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(i,0,i,h,dash=1)
        for i in range(0,h,SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(0,i,w,i,dash=1)


        # Load in flame icon from flame.gif
        self.flame_icon = PhotoImage(file="flame.gif")
        # Load in the drone icon from drone.gif
        global DRONE_ICON
        DRONE_ICON = PhotoImage(file="drone.gif")

        buttons_frame = Canvas(master, width=163, height=140, bg=BUTTONS_BKG_COLOUR, highlightthickness=1, highlightbackground='dim grey')
        buttons_frame.place(x=40,y=230)

        # Define UI buttons
        self.add_tasks_flg = IntVar()
        self.add_tasks_b = Checkbutton(master, text="Add Tasks", variable=self.add_tasks_flg, highlightbackground=BUTTONS_BKG_COLOUR, background=BUTTONS_BKG_COLOUR)
        self.add_tasks_b.place(x=77,y=270)

        self.clear_wp_b = Button(master, text='Clear Tasks', command=self.clear_wp, highlightbackground=BUTTONS_BKG_COLOUR)
        self.clear_wp_b.config(width=10)
        self.clear_wp_b.place(x=65, y=300)
        
        '''
        self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR)
        self.gen_wp_file_b.config(width=20)
        self.gen_wp_file_b.place(x=20, y=250)
        '''

        '''
        self.land_b = Button(master, text='Land', command=self.land, highlightbackground=BUTTONS_BKG_COLOUR)
        self.land_b.config(width=10)
        self.land_b.place(x=65, y=350)
        '''


        # Set up coordinate system conversion and display corners of room:
        file_obj  = open('antenna_locations.txt', 'r')
        anchors = []
        for line in file_obj:
            cur_anchors = map(float, line.split())
            anchors.append(cur_anchors)
        file_obj.close()
        anchors = (np.array(anchors)).T

        # Find largest (abs) x and y values to use a reference for conversion ratio
        x_vals = anchors[0]
        largest_x_val = x_vals[np.argmax(abs(x_vals))]
        y_vals = anchors[1]
        largest_y_val = y_vals[np.argmax(abs(y_vals))]

        if largest_x_val > largest_y_val:
            largest_y_val = largest_x_val
        else:
            largest_x_val = largest_y_val

        global m_per_pixel_x
        m_per_pixel_x = float(largest_x_val/(CANVAS_W/2))
        global m_per_pixel_y
        m_per_pixel_y = float(largest_y_val/(CANVAS_H/2))

        # Place antenna (anchors) on UI
        anchors = anchors.T
        for cur_anchor in anchors:
            x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W/2
            y_pixel_loc = -1*(cur_anchor[1] / m_per_pixel_y) + CANVAS_H/2

            # Draw antenna @ location
            global ANTENNA_LIST
            antenna_id = self.map_canvas.create_oval(x_pixel_loc-15,y_pixel_loc-15,x_pixel_loc+15,y_pixel_loc+15,fill='red')
       

        self.master.update()

    global SQ_SIZE 
    SQ_SIZE = 20
    global BKG_COLOUR
    BKG_COLOUR = 'gray95'
    global BUTTONS_BKG_COLOUR
    BUTTONS_BKG_COLOUR = 'grey66'
    global CANVAS_W
    CANVAS_W = 700
    global CANVAS_H
    CANVAS_H = 700
    global TASK_LIST
    TASK_LIST = None
    global m_per_pixel_x
    m_per_pixel_x = None
    global m_per_pixel_y
    m_per_pixel_y = None
    global NEW_TASK_FLAG
    NEW_TASK_FLAG = False
    global ANTENNA_LIST
    ANTENNA_LIST = None
    global DRONE_ICON 
    DRONE_ICON = None


    flame_icon = None
    ui_wp_list = None
    add_wp_flag = False
    task_id = 0
    add_tasks_flg = None
    

    def add_tasks(self):
        print "adding tasks"
        # function imp here
        self.add_wp_flag = True
        self.map_canvas.config(cursor='pencil')


    def clear_wp(self):
        print "clear tasks"
        global TASK_LIST
        TASK_LIST = None
        for element_id in self.ui_wp_list:
            self.map_canvas.delete(element_id[0])
        self.ui_wp_list = None

    '''
    def gen_wp_file(self):
        print "generate wp file"
        # function imp here
    '''

    def land(self):
        # Send a new task with position (0,0,0) z=0 tells drone to land
        print("land")



    def enter_task(self, event):
        # Determine square (top left corner coords):
        w_start = event.x - event.x%SQ_SIZE
        h_start = event.y - event.y%SQ_SIZE

        #Translate pixel location to physical location
        x_pixel = event.x
        y_pixel = event.y
        # Find out how many pixels from center:
        x_pixel = x_pixel - CANVAS_W/2
        x_physical = x_pixel*m_per_pixel_x

        #vertical case, note this is flipped
        y_pixel = y_pixel - CANVAS_W/2
        y_pixel = -1*y_pixel
        y_physical = y_pixel*m_per_pixel_y

        try:
        	# Add to task list
	        global TASK_LIST
	        if TASK_LIST == None:
	            TASK_LIST = [[self.task_id, x_physical, y_physical]]
	            TASK_LIST = [[self.task_id, x_physical, y_physical]]
	            global NEW_TASK_FLAG
	            NEW_TASK_FLAG = True
	        else:
	            TASK_LIST.append([self.task_id, x_physical, y_physical])
	            global NEW_TASK_FLAG
	            NEW_TASK_FLAG = True

	        # Indicate task in UI
	        element_id = self.map_canvas.create_image(event.x, event.y, image=self.flame_icon)
	        if self.ui_wp_list == None:
	            self.ui_wp_list = [[element_id]]
	        else:
	            self.ui_wp_list.append([element_id])
       	except:
       		print("Invalid Task Entry")



        self.map_canvas.config(cursor='arrow')
        self.add_wp_flag = False

        print(TASK_LIST)
        
        self.task_id = self.task_id + 1
        

    def cancel_task(self):
        self.top.destroy()
Beispiel #48
0
    # remove unnecessary folders and files
    shutil.rmtree(foldername)
    shutil.rmtree('build')
    shutil.rmtree('dist')
    os.remove("main.spec")

    root.quit()


def incorrect_version():
    print 'Build process is cancelled because of incorrect version number'
    root.quit()


version_title = Label(root,
                      text='Glider-task-converter %s' % version,
                      font=("Helvetica", 30))
question = Label(root,
                 text="Is this the correct version number?",
                 font=("Helvetica", 12))
stop = Button(root, command=incorrect_version, text='no')
go_on = Button(root, command=correct_version, text='yes')

version_title.grid(row=0, column=0, columnspan=2)
question.grid(row=1, column=0, columnspan=2)
stop.grid(row=2, column=0, sticky=E)
go_on.grid(row=2, column=1, sticky=W)

root.mainloop()
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])
     def __init__(self, master): ##Inititilize Main
          self.master = master ##Define master
          master.title ("GUI Name") ##Create Title for GUI Window
          master.geometry("816x504") ##Define Window Size
          master.resizable (width = False, height = False)##Disable Max Button on Window

          master.columnconfigure(0,minsiz=187,weight=1) ##Column Definition (size)
          master.columnconfigure(1,minsiz=306,weight=1) ##Column Definition (size)
          master.columnconfigure(2,minsiz=160.3536,weight=1) ##Column Definition (size)
          master.columnconfigure(3,minsiz=160.3536,weight=1) ##Column Definition (size)

          master.rowconfigure(0,minsiz=98.2464,weight=1) ##Row Definition (size)
          master.rowconfigure(1,minsiz=323.2512,weight=1) ##Row Definition (size)
          master.rowconfigure(2,minsiz=56.6784,weight=1) ##Row Definition (size)
          master.rowconfigure(3,minsiz=39.3216,weight=1) ##Row Definition (size)

          self.projectNameLabel=projectNameLabel=Label(master,text='Project Name:',font=('BoldCourier',16)) ##Label Widget for projectNameEntry Box
          projectNameLabel.grid(row=0,column=0) ##Grid Label

          self.projectNameEntry=projectNameEntry=Entry(master,text='Enter Name Of Project',font=('Courier',16)) ##Entry Widget for Entering Name Of Project
          projectNameEntry.grid(row=0,column=1) ##Gid Entry Widget
          projectNameEntry.focus() ##Set Curser To Entry Widget

          self.includeStartingFilesVariable=includeStartingFilesVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.includeStartingFiles=includeStartingFiles=Checkbutton(master,text='Include\nStarting Files',borderwidth=2,relief='groove',variable=includeStartingFilesVariable,font=('Courier',16)) ##Checkbutton Widget for Including Starting Files
          includeStartingFiles.grid(row=0,column=2, columnspan=2) ##Grid Checkbutton Widget

          self.folderFrame=folderFrame=Frame(master,width=462, height=342, borderwidth=2,relief='groove') ##Frame Widget to Create Better GUI Layout
          folderFrame.grid(row=1,column=0,rowspan=2,columnspan=2) ##Grid Frame Widget

          folderFrame.columnconfigure(0,minsize=156,weight=1) ##Column Definition (size)
          folderFrame.columnconfigure(1,minsize=12.9984,weight=1) ##Column Definition (size)
          folderFrame.columnconfigure(2,minsize=149.0016,weight=1) ##Column Definition (size)
          folderFrame.columnconfigure(3,minsize=144,weight=1) ##Column Definition (size)

          folderFrame.rowconfigure(0,minsize=36,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(1,minsize=34.6656,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(2,minsize=42,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(3,minsize=12.9984,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(4,minsize=42,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(5,minsize=12.9984,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(6,minsize=42,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(7,minsize=12.9984,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(8,minsize=42,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(9,minsize=12.9984,weight=1) ##Row Definition (size)
          folderFrame.rowconfigure(10,minsize=49.872,weight=1) ##Row Definition (size)

          self.folderFrameLabel=folderFrameLabel=Label(folderFrame,text='Folders To Include',font=('BoldCourier',16)) ##Label Widget for Frame
          folderFrameLabel.grid(row=0,column=0,columnspan=4) ##Grid Label Widget

          self.mainFolderLabel=mainFolderLabel=Label(folderFrame,text='Main Folders',font=('BoldCourier',12)) ##Label Widget for Main Folders
          mainFolderLabel.grid(row=1,column=0) ##Grid Label Widget

          self.divider0=divider0=Frame(folderFrame,width=2,height=280,borderwidth=1,relief='sunken') ##Frame to act as Divider for Better GUI Layout
          divider0.grid(row=1,column=1,rowspan=10) ##Grid Divider

          self.subFolderLabel=subFolderLabel=Label(folderFrame,text='Sub-Folders',font=('BoldCourier',12)) ##Label Widget for Sub-Folders
          subFolderLabel.grid(row=1,column=2,columnspan=2) ##Grid Label Widget

          self.firmwareMainVariable=firmwareMainVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.firmwareMain=firmwareMain=Checkbutton(folderFrame,width=10,text='Firmware',borderwidth=2,relief='groove',anchor='w',variable=firmwareMainVariable,font=('Courier',12)) ##Checkbutton Widget for Firmware Main Folder
          firmwareMain.grid(row=2,column=0) ##Grid Ceckbutton Widget

          self.firmwareResourcesVariable=firmwareResourcesVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.firmwareResources=firmwareResources=Checkbutton(folderFrame,width=12,text='Resources',borderwidth=2,relief='groove',anchor='w',variable=firmwareResourcesVariable,font=('Courier',12)) ##Checkbutton Widget for Firmware-Resources Sub-Folder
          firmwareResources.grid(row=2,column=2) ##Grid Ceckbutton Widget

          self.firmwareArchiveVariable=firmwareArchiveVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.firmwareArchive=firmwareArchive=Checkbutton(folderFrame,width=8,text='Archive',borderwidth=2,relief='groove',anchor='w',variable=firmwareArchiveVariable,font=('Courier',12)) ##Checkbutton Widget for Firmware-Archive Sub-Folder
          firmwareArchive.grid(row=2,column=3) ##Grid Ceckbutton Widget

          self.divider1=divider1=Frame(folderFrame,width=400,height=2,borderwidth=1,relief='sunken') ##Frame to act as Divider for Better GUI Layout
          divider1.grid(row=3,column=0,columnspan=4) ##Grid Divider

          self.hardwareMainVariable=hardwareMainVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.hardwareMain=hardwareMain=Checkbutton(folderFrame,width=10,text='Hardware',borderwidth=2,relief='groove',anchor='w',variable=hardwareMainVariable,font=('Courier',12)) ##Checkbutton Widget for Hardware Main Folder
          hardwareMain.grid(row=4,column=0) ##Grid Ceckbutton Widget

          self.hardwarePartsVariable=hardwarePartsVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.hardwareParts=hardwareParts=Checkbutton(folderFrame,width=12,text='Parts',borderwidth=2,relief='groove',anchor='w',variable=hardwarePartsVariable,font=('Courier',12)) ##Checkbutton Widget for Hardware-Parts Sub-Folder
          hardwareParts.grid(row=4,column=2) ##Grid Ceckbutton Widget

          self.hardwareArchiveVariable=hardwareArchiveVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.hardwareArchive=hardwareArchive=Checkbutton(folderFrame,width=8,text='Archive',borderwidth=2,relief='groove',anchor='w',variable=hardwareArchiveVariable,font=('Courier',12)) ##Checkbutton Widget for Hardware-Archive Sub-Folder
          hardwareArchive.grid(row=4,column=3) ##Grid Ceckbutton Widget

          self.divider2=divider2=Frame(folderFrame,width=400,height=2,borderwidth=1,relief='sunken') ##Frame to act as Divider for Better GUI Layout
          divider2.grid(row=5,column=0,columnspan=4) ##Grid Divider

          self.resourcesMainVariable=resourcesMainVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.resourcesMain=resourcesMain=Checkbutton(folderFrame,width=10,text='Resources',borderwidth=2,relief='groove',anchor='w',variable=resourcesMainVariable,font=('Courier',12)) ##Checkbutton Widget for Resources Main Folder
          resourcesMain.grid(row=6,column=0) ##Grid Ceckbutton Widget

          self.resourcesDatasheetsVariable=resourcesDatasheetsVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.resourcesDatasheets=resourcesDatasheets=Checkbutton(folderFrame,width=12,text='Datasheets',borderwidth=2,relief='groove',anchor='w',variable=resourcesDatasheetsVariable,font=('Courier',12)) ##Checkbutton Widget for Resources-Datasheets Sub-Folder
          resourcesDatasheets.grid(row=6,column=2) ##Grid Ceckbutton Widget

          self.resourcesArchiveVariable=resourcesArchiveVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.resourcesArchive=resourcesArchive=Checkbutton(folderFrame,width=8,text='Archive',borderwidth=2,relief='groove',anchor='w',variable=resourcesArchiveVariable,font=('Courier',12)) ##Checkbutton Widget for Resources-Archive Sub-Folder
          resourcesArchive.grid(row=6,column=3) ##Grid Ceckbutton Widget

          self.divider3=divider3=Frame(folderFrame,width=400,height=2,borderwidth=1,relief='sunken') ##Frame to act as Divider for Better GUI Layout
          divider3.grid(row=7,column=0,columnspan=4) ##Grid Divider

          self.softwareMainVariable=softwareMainVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.softwareMain=softwareMain=Checkbutton(folderFrame,text='Software',width=10,borderwidth=2,relief='groove',anchor='w',variable=softwareMainVariable,font=('Courier',12)) ##Checkbutton Widget for Software Main Folder
          softwareMain.grid(row=8,column=0) ##Grid Ceckbutton Widget

          self.softwareResourcesVariable=softwareResourcesVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.softwareResources=softwareResources=Checkbutton(folderFrame,width=12,text='Resources',borderwidth=2,relief='groove',anchor='w',variable=softwareResourcesVariable,font=('Courier',12)) ##Checkbutton Widget for Software-Resources Sub-Folder
          softwareResources.grid(row=8,column=2) ##Grid Ceckbutton Widget

          self.softwareArchiveVariable=softwareArchiveVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.softwareArchive=softwareArchive=Checkbutton(folderFrame,width=8,text='Archive',borderwidth=2,relief='groove',anchor='w',variable=softwareArchiveVariable,font=('Courier',12)) ##Checkbutton Widget for Software-Archive Sub-Folder
          softwareArchive.grid(row=8,column=3) ##Grid Ceckbutton Widget

          self.divider4=divider4=Frame(folderFrame,width=400,height=2,borderwidth=1,relief='sunken') ##Frame to act as Divider for Better GUI Layout
          divider4.grid(row=9,column=0,columnspan=4) ##Grid Divider

          self.archiveMainVariable=archiveMainVariable=BooleanVar() ##Boolean to Hold Value of Checkbutton
          self.archiveMain=archiveMain=Checkbutton(folderFrame,width=10,text='Archive',borderwidth=2,relief='groove',anchor='w',variable=archiveMainVariable,font=('Courier',12)) ##Checkbutton Widget for Archive Main Folder
          archiveMain.grid(row=10,column=0) ##Grid Ceckbutton Widget

          self.instructionFrame=instructionFrame=Frame(master,width=300,height=288,borderwidth=2,relief='groove') ##Frame for Instructions
          instructionFrame.grid(row=1,column=2,columnspan=2) ##Grid Frame

          self.instuctionLabel=instructionLabel=Label(instructionFrame,text='Project Name will\nbe used as Folder Name.\r\nFolder can be found on\nDesktop after Creation.',font=('BoldCourier',16)) ##Label Holding Instructions
          instructionLabel.grid(row=0,column=0,pady=80,padx=30) ##Grid Label

          self.cancelButton=cancelButton=Button(master,text='Cancel', width=42,height=108,font=('BoldCourier',16),foreground='red',command=self.CancelCommand) ##Button Widget to Cancel/Close Program
          cancelButton.grid(row=2,column=2,padx=10) ##Grid Button Widget

          self.createButton=createButton=Button(master,text='Create',width=42,height=108,font=('BoldCourier',16),foreground='green',command=self.CreateCommand) ##Button Widget to Create Folder Structure
          createButton.grid(row=2,column=3,padx=10) ##Grid Button Widget

          self.versionNumber=versionNumber=Label(text='Ver. 0.1') ##Label to Display Version Number
          versionNumber.grid(row=3,column=3) ##Grid Label Widget
        f = open(fn, 'U')
    except IOError, e:
        from cStringIO import StringIO
        f = StringIO(DEMO)
        en.delete(0, 'end')
        if fn.lower() == 'demo':
            en.insert(0,fn)
        else:
            import os
            en.insert(0,r"DEMO (can't open %s: %s)" % (os.path.join(os.getcwd(), fn), str(e)))
        en.update_idletasks()
    txt2ppt(line.rstrip() for line in f)
    f.close()

if __name__ == '__main__':
    tk = Tk()
    lb = Label(tk, text='Enter file [or "DEMO"]:')
    lb.pack()
    en = Entry(tk)
    en.bind('<Return>', _start)
    en.pack()
    en.focus_set()
    quit = Button(tk, text='QUIT', command=tk.quit, fg='white', bg='red')
    quit.pack(fill='x', expand=True)
    tk.mainloop()





Beispiel #52
0
    def _init_widgets(self):

        ## CEBALERT: now we can have multiple operations at the same time,
        ## status bar could be improved to show all tasks?

        # CEBALERT
        self.messageBar = self.status

        self.some_area = DockManager(self)
        self.some_area.pack(fill="both", expand=1)

        ### Balloon, for pop-up help
        self.balloon = tk.Balloon(self.content)

        ### Top-level (native) menu bar
        #self.menubar = tk.ControllableMenu(self.content)
        self.configure(menu=self.menubar)

        #self.menu_balloon = Balloon(topo.tkgui.root)

        # no menubar in tile yet
        # http://news.hping.org/comp.lang.tcl.archive/4679.html

        self.__simulation_menu()
        self.__create_plots_menu()
        self.refresh_plots_menu()
        self.__help_menu()

        ### Running the simulation
        run_frame = Frame(self.content)
        run_frame.pack(side='top', fill='x', padx=4, pady=8)

        self.run_frame = run_frame

        Label(run_frame, text='Run for: ').pack(side=LEFT)

        self.run_for_var = DoubleVar()
        self.run_for_var.set(1.0)

        run_for = tk.TaggedSlider(run_frame,
                                  variable=self.run_for_var,
                                  tag_width=11,
                                  slider_length=150,
                                  bounds=(0, 20000))
        self.balloon.bind(
            run_for,
            "Duration to run the simulation, e.g. 0.0500, 1.0, or 20000.")
        run_for.pack(side=LEFT, fill='x', expand=YES)
        run_for.tag.bind("<Return>", self.run_simulation)

        # When return is pressed, the TaggedSlider updates itself...but we also want to run
        # the simulation in this case.
        run_frame.optional_action = self.run_simulation

        go_button = Button(run_frame, text="Go", command=self.run_simulation)
        go_button.pack(side=LEFT)

        self.balloon.bind(go_button,
                          "Run the simulation for the specified duration.")

        self.step_button = Button(run_frame,
                                  text="Step",
                                  command=self.run_step)
        self.balloon.bind(
            self.step_button,
            "Run the simulation through the time at which the next events are processed."
        )
        self.step_button.pack(side=LEFT)

        self.sizeright()
Beispiel #53
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()
Beispiel #54
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
Beispiel #55
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()
    def __init__(self):
        self.img_Wid = 500
        self.img_Hei = 500
        self.win_wid = self.img_Wid + 200
        self.win_Hei = self.img_Hei

        # init state control variable
        self.has_select_path = False  # sign has select image path(to do data annotation) or not
        self.img_path = ''
        self.img_list = []

        # create main window
        self.mainWin = Tkinter.Tk()
        self.mainWin.geometry(str(self.win_wid) + 'x' +
                              str(self.win_Hei))  # init the size of window
        self.mainWin.title("data annotation tool")
        self.mainWin.tk.eval('package require Tix')
        # bind the key press event(space to pass, d to delete, q to quit)
        self.mainWin.bind('<KeyPress>', self._keyPressEvent)

        # create init image(a black background)
        self.img = Image.new("RGB", (self.img_Wid, self.img_Hei), (0, 0, 0))
        self.photo_img = ImageTk.PhotoImage(self.img)

        # create Canvas control
        self.cv = Canvas(self.mainWin,
                         bg='white',
                         width=self.img_Wid,
                         height=self.img_Hei)
        self.cv.create_image((0, 0), anchor=Tkinter.NW, image=self.photo_img)
        self.cv.pack(side=Tkinter.LEFT, expand=True)

        # create total Frame to lay out all components
        self.frame = Frame(self.mainWin)
        self.frame.pack(fill=Tkinter.X, expand=Tkinter.YES, side=Tkinter.LEFT)

        # create text control
        root_save_path = './data_annotation_result'
        self.entry = Entry(self.frame, state='normal')
        self.entry.pack(side=Tkinter.TOP, fill=Tkinter.X)
        self.entry.insert(0, root_save_path)
        # mkdir of annotation result
        self.categoryList = ['Pass', 'Remove']
        self.category_savepath_list = []
        for category in self.categoryList:
            cur_category_save_path = os.path.join(root_save_path, category)
            self.category_savepath_list.append(cur_category_save_path)
            if os.path.exists(cur_category_save_path) == False:
                os.mkdir(cur_category_save_path)

        # create 'START' button
        self.btn_start = Button(self.frame,
                                text='START',
                                command=self._selectPath,
                                activeforeground='blue',
                                activebackground='white',
                                bg='blue',
                                fg='white')
        self.btn_start.pack(side=Tkinter.TOP, pady=30)

        # create data annotation label button
        self.btn_dog = Button(self.frame,
                              text='Pass',
                              command=lambda: self._labelButtonClick('Pass'),
                              activeforeground='black',
                              activebackground='blue',
                              bg='white',
                              fg='black')
        self.btn_dog.pack(side=Tkinter.TOP, pady=10)

        # create data annotation label button
        self.btn_cat = Button(self.frame,
                              text='Remove',
                              command=lambda: self._labelButtonClick('Remove'),
                              activeforeground='black',
                              activebackground='blue',
                              bg='white',
                              fg='black')
        self.btn_cat.pack(side=Tkinter.TOP, pady=10)

        #NumericUpDown控件
        self.num_count = Control(self.frame,
                                 integer=True,
                                 max=-1,
                                 min=-1,
                                 value=-1,
                                 step=1,
                                 label='current Image:',
                                 command=self._showImage)
        self.num_count.label.config(font='Helvetica -14 bold')
        self.num_count.pack(side=Tkinter.TOP, pady=50)

        # create 'QUIT' button
        self.btn_quit = Button(self.frame,
                               text='QUIT',
                               command=self.mainWin.quit,
                               activeforeground='blue',
                               activebackground='white',
                               bg='red',
                               fg='white')
        self.btn_quit.pack(side=Tkinter.BOTTOM, pady=10)
Beispiel #57
0
class TopoConsole(tk.AppWindow, tk.TkParameterized):
    """
    Main window for the Tk-based GUI.
    """
    def _getmenubar(self):
        return self.master.menubar

    menubar = property(_getmenubar)

    def __getitem__(self, menu_name):
        """Allow dictionary-style access to the menu bar."""
        return self.menubar[menu_name]

    def __init__(self, root, exit_on_quit=True, **params):
        tk.AppWindow.__init__(self, root, status=True)
        tk.TkParameterized.__init__(self, root, **params)

        # Instead of displaying tracebacks on the commandline, try to display
        # them on the originating window.
        # CEBALERT: on destroy(), ought to revert this
        Tkinter.Misc._report_exception = _tkinter_report_exception

        self.exit_on_quit = exit_on_quit
        self.auto_refresh_panels = []
        self._init_widgets()
        self.title(
            topo.sim.name
        )  # If -g passed *before* scripts on commandline, this is useless.
        # So topo.misc.commandline sets the title as its last action (if -g)

        # catch click on the 'x': offers choice to quit or not
        self.protocol("WM_DELETE_WINDOW", self.quit_topographica)

        ##########
        ### Make cascade menus open automatically on linux when the mouse
        ### is over the menu title.
        ### [Tkinter-discuss] Cascade menu issue
        ### http://mail.python.org/pipermail/tkinter-discuss/2006-August/000864.html
        if topo.tkgui.system_platform is 'linux':
            activate_cascade = """\
            if {[%W cget -type] != {menubar} && [%W type active] == {cascade}} {
                %W postcascade active
               }
            """
            self.bind_class("Menu", "<<MenuSelect>>", activate_cascade)
        ##########

        # Install warning and message handling
        from param.parameterized import Parameterized
        self.__orig_P_warning = Parameterized.warning
        #self.__orig_P_message = Parameterized.message
        type.__setattr__(Parameterized, 'warning', self.gui_warning)
        #type.__setattr__(Parameterized,'message',self.gui_message)

    def gui_warning(self, *args):
        stat = self.__get_status_bar()
        s = string.join(args, ' ')
        stat.warn(s)
        self.__orig_P_warning(self, *args)

    def gui_message(self, *args):
        stat = self.__get_status_bar()
        s = string.join(args, ' ')
        stat.message(s)
        self.__orig_P_message(self, *args)

    def title(self, t=None):
        newtitle = "Topographica"
        if t: newtitle += ": %s" % t
        tk.AppWindow.title(self, newtitle)

    def _init_widgets(self):

        ## CEBALERT: now we can have multiple operations at the same time,
        ## status bar could be improved to show all tasks?

        # CEBALERT
        self.messageBar = self.status

        self.some_area = DockManager(self)
        self.some_area.pack(fill="both", expand=1)

        ### Balloon, for pop-up help
        self.balloon = tk.Balloon(self.content)

        ### Top-level (native) menu bar
        #self.menubar = tk.ControllableMenu(self.content)
        self.configure(menu=self.menubar)

        #self.menu_balloon = Balloon(topo.tkgui.root)

        # no menubar in tile yet
        # http://news.hping.org/comp.lang.tcl.archive/4679.html

        self.__simulation_menu()
        self.__create_plots_menu()
        self.refresh_plots_menu()
        self.__help_menu()

        ### Running the simulation
        run_frame = Frame(self.content)
        run_frame.pack(side='top', fill='x', padx=4, pady=8)

        self.run_frame = run_frame

        Label(run_frame, text='Run for: ').pack(side=LEFT)

        self.run_for_var = DoubleVar()
        self.run_for_var.set(1.0)

        run_for = tk.TaggedSlider(run_frame,
                                  variable=self.run_for_var,
                                  tag_width=11,
                                  slider_length=150,
                                  bounds=(0, 20000))
        self.balloon.bind(
            run_for,
            "Duration to run the simulation, e.g. 0.0500, 1.0, or 20000.")
        run_for.pack(side=LEFT, fill='x', expand=YES)
        run_for.tag.bind("<Return>", self.run_simulation)

        # When return is pressed, the TaggedSlider updates itself...but we also want to run
        # the simulation in this case.
        run_frame.optional_action = self.run_simulation

        go_button = Button(run_frame, text="Go", command=self.run_simulation)
        go_button.pack(side=LEFT)

        self.balloon.bind(go_button,
                          "Run the simulation for the specified duration.")

        self.step_button = Button(run_frame,
                                  text="Step",
                                  command=self.run_step)
        self.balloon.bind(
            self.step_button,
            "Run the simulation through the time at which the next events are processed."
        )
        self.step_button.pack(side=LEFT)

        self.sizeright()

    def __simulation_menu(self):
        """Add the simulation menu options to the menubar."""
        simulation_menu = ControllableMenu(self.menubar, tearoff=0)

        self.menubar.add_cascade(label='Simulation', menu=simulation_menu)

        simulation_menu.add_command(label='Run script',
                                    command=self.run_script)
        simulation_menu.add_command(label='Save script',
                                    command=self.save_script_repr)
        simulation_menu.add_command(label='Load snapshot',
                                    command=self.load_snapshot)
        simulation_menu.add_command(label='Save snapshot',
                                    command=self.save_snapshot)
        #simulation_menu.add_command(label='Reset',command=self.reset_network)
        simulation_menu.add_command(label='Test Pattern',
                                    command=self.open_test_pattern)

        simulation_menu.add_command(label='Model Editor',
                                    command=self.open_model_editor)
        simulation_menu.add_command(label='Quit',
                                    command=self.quit_topographica)

    def open_test_pattern(self):
        return open_plotgroup_panel(TestPattern)

    def __create_plots_menu(self):
        """
        Add the plot menu to the menubar, with Basic plots on the menu itself and
        others in cascades by category (the plots come from plotgroup_templates).
        """
        plots_menu = ControllableMenu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label='Plots', menu=plots_menu)

    # CEBALERT: should split other menus in same way as plots (create/refresh)
    def refresh_plots_menu(self):
        plots_menu = self['Plots']
        plots_menu.delete(0, 'end')

        # create menu entries, and get list of categories
        entries = OrderedDict(
        )  # keep the order of plotgroup_templates (which is also KL)
        categories = []
        for label, plotgroup in plotgroups.items():
            entries[label] = PlotsMenuEntry(plotgroup)
            categories.append(plotgroup.category)
        categories = sorted(set(categories))

        # The Basic category items appear on the menu itself.
        assert 'Basic' in categories, "'Basic' is the category for the standard Plots menu entries."
        for label, entry in entries.items():
            if entry.plotgroup.category == 'Basic':
                plots_menu.add_command(label=label, command=entry.__call__)

        categories.remove('Basic')

        plots_menu.add_separator()

        # Add the other categories to the menu as cascades, and the plots of each category to
        # their cascades.
        for category in categories:
            category_menu = ControllableMenu(plots_menu, tearoff=0)
            plots_menu.add_cascade(label=category, menu=category_menu)

            # could probably search more efficiently than this
            for label, entry in entries.items():
                if entry.plotgroup.category == category:
                    category_menu.add_command(label=label,
                                              command=entry.__call__)

        plots_menu.add_separator()

        plots_menu.add_command(
            label="Help",
            command=(lambda x=plotting_help_locations: self.open_location(x)))

    def __help_menu(self):
        """Add the help menu options."""

        help_menu = ControllableMenu(self.menubar, tearoff=0, name='help')
        self.menubar.add_cascade(label='Help', menu=help_menu)

        help_menu.add_command(label='About', command=self.new_about_window)
        help_menu.add_command(
            label="User Manual",
            command=(lambda x=user_manual_locations: self.open_location(x)))

        help_menu.add_command(
            label="Tutorials",
            command=(lambda x=tutorials_locations: self.open_location(x)))

        help_menu.add_command(label="Examples",
                              command=self.run_example_script)

        help_menu.add_command(
            label="Reference Manual",
            command=(
                lambda x=reference_manual_locations: self.open_location(x)))

        help_menu.add_command(
            label="Topographica.org",
            command=(lambda x=topo_www_locations: self.open_location(x)))

        help_menu.add_command(
            label="Python documentation",
            command=(lambda x=python_doc_locations: self.open_location(x)))

    def quit_topographica(self, check=True, exit_status=0):
        """Quit topographica."""
        if not check or (check
                         and tk.askyesno("Quit Topographica", "Really quit?")):
            self.destroy()

            # matplotlib's tk backend starts its own Tk instances; we
            # need to close these ourselves (at least to avoid error
            # message about 'unusual termination' in Windows).
            try:  # not that there should be an error, but just in case...
                import matplotlib._pylab_helpers
                for figman in matplotlib._pylab_helpers.Gcf.get_all_fig_managers(
                ):
                    figman.destroy()
            except:
                pass

            self.message("Quit selected%s" %
                         ("; exiting" if self.exit_on_quit else ""))

            # Workaround for obscure problem on some UNIX systems
            # as of 4/2007, probably including Fedora Core 5.
            # On these systems, if Topographica is started from a
            # bash prompt and then quit from the Tkinter GUI (as
            # opposed to using Ctrl-D in the terminal), the
            # terminal would suppress echoing of all future user
            # input.  stty sane restores the terminal to sanity,
            # but it is not clear why this is necessary.
            # For more info:
            # http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d0f33c8eb2e02d
            if topo.tkgui.system_platform == "linux" and os.getenv(
                    'EMACS') != 't':
                try:
                    os.system("stty sane")
                except:
                    pass
            # CEBALERT: re. above. Shouldn't we be able to store the
            # output of "stty --save" before starting the gui, then
            # ensure that when the gui exits (however badly it
            # happens) run "stty saved_settings"?

            # CEBALERT: there was no call to self.master.destroy()
            if self.exit_on_quit:
                sys.exit(exit_status)

    def run_script(self):
        """
        Dialog to run a user-selected script

        The script is exec'd in __main__.__dict__ (i.e. as if it were specified on the commandline.)
        """
        script = askopenfilename(initialdir=normalize_path(),
                                 filetypes=SCRIPT_FILETYPES)
        if script in (
                '', (), None
        ):  # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('Run canceled')
        else:
            execfile(script, __main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)

    # CEBALERT: duplicates most of run_script()
    def run_example_script(self):

        script = askopenfilename(
            initialdir=topo.misc.genexamples.find_examples(),
            filetypes=SCRIPT_FILETYPES)

        if script in (
                '', (), None
        ):  # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('No example opened')
        else:
            execfile(script, __main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)

    def save_script_repr(self):
        script_name = asksaveasfilename(filetypes=SCRIPT_FILETYPES,
                                        initialdir=normalize_path(),
                                        initialfile=topo.sim.basename() +
                                        "_script_repr.ty")

        if script_name:
            topo.command.save_script_repr(script_name)
            self.messageBar.response('Script saved to ' + script_name)

    def load_snapshot(self):
        """
        Dialog to load a user-selected snapshot (see topo.command.load_snapshot() ).
        """
        snapshot_name = askopenfilename(initialdir=normalize_path(),
                                        filetypes=SAVED_FILETYPES)

        if snapshot_name in ('', (), None):
            self.messageBar.response('No snapshot loaded.')
        else:
            self.messageBar.dynamicinfo(
                'Loading snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.load_snapshot(snapshot_name)
            self.messageBar.response('Loaded snapshot ' + snapshot_name)
            self.title(topo.sim.name)

        self.auto_refresh()

    def save_snapshot(self):
        """
        Dialog to save a snapshot (see topo.command.save_snapshot() ).

        Adds the file extension .typ if not already present.
        """
        snapshot_name = asksaveasfilename(filetypes=SAVED_FILETYPES,
                                          initialdir=normalize_path(),
                                          initialfile=topo.sim.basename() +
                                          ".typ")

        if snapshot_name in ('', (), None):
            self.messageBar.response('No snapshot saved.')
        else:
            if not snapshot_name.endswith('.typ'):
                snapshot_name = snapshot_name + SAVED_FILE_EXTENSION

            self.messageBar.dynamicinfo(
                'Saving snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.save_snapshot(snapshot_name)
            self.messageBar.response('Snapshot saved to ' + snapshot_name)

    def auto_refresh(self, update=True):
        """
        Refresh all windows in auto_refresh_panels.

        Panels can add and remove themselves to the list; those in the list
        will have their refresh() method called whenever this console's
        autorefresh() is called.
        """
        for win in self.auto_refresh_panels:
            win.refresh(update)

        self.set_step_button_state()
        self.update_idletasks()

    ### CEBERRORALERT: why doesn't updatecommand("display=True") for an
    ### orientation preference map measurement work with the
    ### hierarchical example? I guess this is the reason I thought the
    ### updating never worked properly (or I really did break it
    ### recently - or I'm confused)...
    def refresh_activity_windows(self):
        """
        Update any windows with a plotgroup_key ending in 'Activity'.

        Used primarily for debugging long scripts that present a lot of activity patterns.
        """
        for win in self.auto_refresh_panels:
            if re.match('.*Activity$', win.plotgroup.name):
                win.refresh()
                self.update_idletasks()

    def open_model_editor(self):
        """Start the Model editor."""
        return ModelEditor(self)

    def new_about_window(self):
        win = tk.AppWindow(self)
        win.withdraw()
        win.title("About Topographica")
        text = Label(win, text=topo.about(display=False), justify=LEFT)
        text.pack(side=LEFT)
        win.deiconify()
        #self.messageBar.message('state', 'OK')

    def open_location(self, locations):
        """
        Try to open one of the specified locations in a new window of the default
        browser. See webbrowser module for more information.

        locations should be a tuple.
        """
        # CB: could have been a list. This is only here because if locations is set
        # to a string, it will loop over the characters of the string.
        assert isinstance(locations, tuple), "locations must be a tuple."

        for location in locations:
            try:
                existing_location = resolve_path(location)
                webbrowser.open(existing_location, new=2, autoraise=True)
                self.messageBar.response('Opened local file ' +
                                         existing_location + ' in browser.')
                return  ###
            except:
                pass

        for location in locations:
            if location.startswith('http'):
                try:
                    webbrowser.open(location, new=2, autoraise=True)
                    self.messageBar.response('Opened remote location ' +
                                             location + ' in browser.')
                    return  ###
                except:
                    pass

        self.messageBar.response("Could not open any of %s in a browser." %
                                 locations)

    # CEBALERT: need to take care of removing old messages automatically?
    # (Otherwise callers might always have to pass 'ok'.)
    def status_message(self, m):
        self.messageBar.response(m)

    def run_simulation(self, event=None):  # event=None allows use as callback
        """
        Run the simulation for the duration specified in the
        'run for' taggedslider.
        """
        fduration = self.run_for_var.get()
        self.open_progress_window(timer=topo.sim.timer)
        topo.sim.run_and_time(fduration)
        self.auto_refresh()

    # CEBERRORALERT: Step button does strange things at time==0.
    # E.g. for lissom_oo_or, nothing appears to happen. For
    # hierarchical, runs to time==10.
    def run_step(self):

        if not topo.sim.events:
            # JP: step button should be disabled if there are no events,
            # but just in case...
            return

        # JPALERT: This should really use .run_and_time() but it doesn't support
        # run(until=...)
        topo.sim.run(until=topo.sim.events[0].time)
        self.auto_refresh()

    def set_step_button_state(self):
        if topo.sim.events:
            self.step_button.config(state=NORMAL)
        else:
            self.step_button.config(state=DISABLED)

    def __get_status_bar(self, i=2):
        # Hack to find appropriate status bar: Go back through frames
        # until a widget with a status bar is found, and return it.
        try:
            while True:
                f = sys._getframe(i)
                if hasattr(f, 'f_locals'):
                    if 'self' in f.f_locals:
                        o = f.f_locals['self']
                        # (temporary hack til ScrolledFrame cleaned up)
                        if o.__class__.__name__ != 'ScrolledFrame':
                            if hasattr(o, 'messageBar'):
                                return o.messageBar
                            elif hasattr(o, 'status'):
                                return o.status
                    i += 1
        except:
            pass

        #print "GUI INTERNAL WARNING: failed to determine window on which to display message."
        return self.messageBar

    def open_progress_window(self, timer, title=None):
        """
        Provide a convenient link to progress bars.
        """
        stat = self.__get_status_bar()
        return stat.open_progress_window(timer=timer, sim=topo.sim)
Beispiel #58
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
Beispiel #59
0
 def home(self):
     self.frame1 = Frame(self.root,
                         width=750,
                         height=350,
                         padx=250,
                         bg="black")
     self.frame2 = Frame(self.root,
                         height=250,
                         width=750,
                         bg="black",
                         padx=25)
     self.root.wm_minsize(width=750, height=666)
     self.root.configure(bg="black")
     self.frame1.pack_propagate(0)
     self.frame1.update()
     self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
     logo = PhotoImage(file="logo.gif")
     starth = Button(self.frame1,
                     text="Hard",
                     bg="orange",
                     padx=25,
                     pady=5,
                     font=Font(family="comic sans MS", size=10),
                     command=lambda: self.callgame(40))
     startm = Button(self.frame1,
                     text="Medium",
                     bg="teal",
                     padx=25,
                     pady=5,
                     font=Font(family="comic sans MS", size=10),
                     command=lambda: self.callgame(60))
     starte = Button(self.frame1,
                     text="Easy",
                     bg="orange",
                     padx=25,
                     pady=5,
                     font=Font(family="comic sans MS", size=10),
                     command=lambda: self.callgame(75))
     self.frame2.pack_propagate(0)
     exp = """        This is a game in which
     the arrow keys are used
     to move the snake around
     and to get points"""
     exf = Font(family="comic sans MS", size=20)
     Label(self.frame2, image=logo, bg="black", text=exp,
           padx=10).pack(side="right")
     Label(self.frame2,
           fg="white",
           bg="black",
           text=exp,
           justify="left",
           font=exf).pack(side="left")
     starte.grid(row=0, columnspan=2)
     startm.grid(row=0, columnspan=2, column=4, padx=18)
     starth.grid(row=0, columnspan=2, column=8)
     head = Font(family="comic sans MS", size=30)
     self.H = Label(self.root,
                    text="SNAKES",
                    font=head,
                    fg="orange",
                    bg="black",
                    pady=10)
     self.H.pack()
     self.frame2.pack(expand=True)
     self.frame1.pack(expand=True)
     self.root.mainloop()
Beispiel #60
-1
class Recherche(Vue):
    """
    Vue principal
    """
    def __init__(self, fenetre):
        """
        Constructeur de la fenetre
        """
        self.parent = fenetre
        self.frame = Frame(self.parent, borderwidth=1, relief='groove', width=100)
        self.frame.pack_configure(side='top', fill='both')
        self.frame.pack()
        self.titre = Label(self.frame, text=GT_('Url'), font=(20))
        self.titre.pack()
        self.img = PhotoImage(file="%slogo.gif" % RESSOURCES_PATH)
        self.logo = Label(self.frame, image=self.img)
        self.logo.pack(pady=(0, 20), side="left")
        self.brand = Label(self.frame, text=GT_('WebForge %s' % VERSION), font=(20))
        self.brand.pack(pady=(10, 20), padx=(0, 20), side="left")
        self.txt_recherche = Entry(self.frame, font=(22))
        self.txt_recherche.pack(pady=(0, 20), expand='yes', fill='both', side='left')
        self.btn_go = Button(self.frame, text="GO")
        self.btn_go.pack(pady=(0, 20), side='right')
        self.btn_erase = Button(self.frame, text="X")
        self.btn_erase.pack(pady=(0, 20), side='right')

    def set_url(self, url):
        """
        Set a new url value to the field
        """
        self.txt_recherche.insert(0, url)