Example #1
0
def MCQ():
    master = Tk()
    master.maxsize(700, 500)
    master.minsize(700, 500)
    master.geometry("500x500")
    master.title("Entering MCQ")
    global e0, e1, e2, e3, e4, e5, e6, e7, e8, e9
    Label(
        master,
        text=
        "Enter Questions. Press submit to enter in \n database and SAVE to finalize it \n",
        font=(None, 15),
        pady=20,
    ).grid(row=0, columnspan=2)
    Label(master, text="Question Number: ", font="arial").grid(row=1,
                                                               column=0,
                                                               sticky=E)
    e0 = Entry(master, bg="white", fg="black", width=30)
    e0.grid(row=1, column=1, sticky=W)
    e1 = "MCQ"
    Label(
        master,
        text="Quiz Id: ",
        font="arial",
    ).grid(row=2, column=0, sticky=E)
    e2 = Entry(master, bg="white", fg="black", width=30)
    e2.grid(row=2, column=1, sticky=W)
    Label(master, text="Course Name: ", font="arial").grid(row=3,
                                                           column=0,
                                                           sticky=E)
    e3 = Entry(master, bg="white", fg="black", width=30)
    e3.grid(row=3, column=1, sticky=W)
    Label(master, text="Question Statment: ", font="arial").grid(row=4,
                                                                 column=0,
                                                                 sticky=E)
    e4 = Entry(master, bg="white", fg="black", width=30)
    e4.grid(row=4, column=1, sticky=W)
    Label(master, text="Option 1: ", font="arial").grid(row=5,
                                                        column=0,
                                                        sticky=E)
    e5 = Entry(master, bg="white", fg="black", width=30)
    e5.grid(row=5, column=1, sticky=W)
    Label(master, text="Option 2: ", font="arial").grid(row=6,
                                                        column=0,
                                                        sticky=E)
    e6 = Entry(master, bg="white", fg="black", width=30)
    e6.grid(row=6, column=1, sticky=W)
    Label(master, text="Option 3: ", font="arial").grid(row=7,
                                                        column=0,
                                                        sticky=E)
    e7 = Entry(master, bg="white", fg="black", width=30)
    e7.grid(row=7, column=1, sticky=W)
    Label(master, text="Option 4: ", font="arial").grid(row=8,
                                                        column=0,
                                                        sticky=E)
    e8 = Entry(master, bg="white", fg="black", width=30)
    e8.grid(row=8, column=1, sticky=W)
    Label(master, text="Correct Answer: ", font="arial").grid(row=9,
                                                              column=0,
                                                              sticky=E)
    e9 = Entry(master, bg="white", fg="black", width=30)
    e9.grid(row=9, column=1, sticky=W)
    Button(master, text="SAVE", command=stor_data, font="arial",
           bg="white").grid(row=11, column=0)
    Button(master, text="Submit", command=sub_data, font="arial",
           bg="white").grid(row=11, column=1)

    master.grid_columnconfigure(0, weight=1)
    master.grid_columnconfigure(1, weight=1)
Example #2
0
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk


in_tmp = "xxx"
in_tmp = "xxx"
in_tmp = "xxx"
in_tmp = "xxx"
in_tmp = "xxx"
in_tmp = "xxx"
in_tmp = "sign_up_procedure"



# https://pypi.org/project/stringcase/
copy_to_clipboard = False

if copy_to_clipboard:
  r = Tk()
  r.withdraw()
  r.clipboard_clear()
  r.clipboard_append('i can has clipboardz?')
  r.update() # now it stays on the clipboard after the window is closed
  r.destroy()

out_tmp_snakecase = stringcase.snakecase(in_tmp)
out_tmp_sentencecase = stringcase.sentencecase(in_tmp)

print("\n\n"+out_tmp_snakecase+"\n\n")
print("\n\n"+out_tmp_sentencecase+"\n\n")
Example #3
0
def PT(F):

    Time = strftime("%Y-%m-%d %H%M%S", gmtime())

    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-v",
                    "--video",
                    default='Endoscope Test Video.mp4',
                    help="path to the (optional) video file")
    ap.add_argument("-b",
                    "--buffer",
                    type=int,
                    default=10,
                    help="max buffer size")
    ap.add_argument("-f",
                    "--filename",
                    default='20% 1 CREEP 1min.avi',
                    help="filename to process")
    args = vars(ap.parse_args())

    root = Tk()
    root.withdraw()
    #file = tkFileDialog.askopenfilename()

    Run = 1
    Setup = 1
    Create = 1
    camera = cv2.VideoCapture(F)
    pts = deque(maxlen=args["buffer"])
    counter = 0
    FirstInitial = 0
    SecondInitial = 0
    FirstPoint = 0
    SecondPoint = 0
    (d1, d2) = (0, 0)
    Difference = 0
    Delta = 0
    PixelToMetric = 0
    DotRadius = 4  #4mm dot diameter
    MeasuredRadius = 0
    RadiusMeasure = 1

    TotalPixels = 0

    MaxProportion = 0
    MinProportion = 0

    hul = 0
    huh = 179
    sal = 0
    sah = 255
    val = 0
    vah = 255

    #determine video file name

    head, tail = os.path.split(F)

    print("File Selected is: " + tail)

    #fourcc = cv2.cv.CV_FOURCC(*'XVID')
    #outCROP = cv2.VideoWriter(F + '_OUTPUT.avi',fourcc, 24.0, (175,150))

    if os.path.isfile("SliderVals.txt"):
        f = open("SliderVals.txt", 'r')
        hul = int(f.readline())
        huh = int(f.readline())
        sal = int(f.readline())
        sah = int(f.readline())
        val = int(f.readline())
        vah = int(f.readline())
        f.close()

    def nothing(x):
        pass

    while True:
        if os.path.isfile(F):

            if (Setup == 1):

                #cv2.namedWindow('setupimage')
                #cv2.namedWindow('frame')

                if (Create == 1):

                    (grabbed, frame) = camera.read()

                    # Crop Frame to remove side irregularities
                    #Endoscope Resolution = 640x480
                    frame = frame[100:275, 250:400]

                    #easy assigments
                    #hh='Hue High'
                    #hl='Hue Low'
                    #sh='Saturation High'
                    #sl='Saturation Low'
                    #vh='Value High'
                    #vl='Value Low'

                    #cv2.createTrackbar(hl, 'setupimage',hul,179,nothing)
                    #cv2.createTrackbar(hh, 'setupimage',huh,179,nothing)
                    #cv2.createTrackbar(sl, 'setupimage',sal,255,nothing)
                    #cv2.createTrackbar(sh, 'setupimage',sah,255,nothing)
                    #cv2.createTrackbar(vl, 'setupimage',val,255,nothing)
                    #cv2.createTrackbar(vh, 'setupimage',vah,255,nothing)

                    Create = 0

                    #print("Press Esc when trackbars are configured")

                #frame=imutils.resize(frame, width=600)
                hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

                #print ("Total Pixels = " + str(TotalPixels))

                #read trackbar positions for all
                #hul=cv2.getTrackbarPos(hl, 'setupimage')
                #huh=cv2.getTrackbarPos(hh, 'setupimage')
                #sal=cv2.getTrackbarPos(sl, 'setupimage')
                #sah=cv2.getTrackbarPos(sh, 'setupimage')
                #val=cv2.getTrackbarPos(vl, 'setupimage')
                #vah=cv2.getTrackbarPos(vh, 'setupimage')

                #make array for final values
                HSVLOW = np.array([hul, sal, val])
                HSVHIGH = np.array([huh, sah, vah])

                #apply the range on a mask
                mask = cv2.inRange(hsv, HSVLOW, HSVHIGH)
                res = cv2.bitwise_and(frame, frame, mask=mask)

                #Find Total Number of Pixels in the Cropped Video
                TotalPixels = 123200

                #cv2.imshow('frame', res)

                k = cv2.waitKey(10) & 0xFF

                Setup = 0
                cv2.destroyWindow('setupimage')
                #f = open("SliderVals.txt", "w")
                #f.write(str(hul) + '\n' )
                #f.write(str(huh) + '\n' )
                #f.write(str(sal) + '\n' )
                #f.write(str(sah) + '\n' )
                #f.write(str(val) + '\n' )
                #f.write(str(vah) + '\n' )
                #f.close()
                pass
        else:
            print('Invalid File Name')
            break

        if (Setup == 0):

            (grabbed, frame) = camera.read()

            # if no frame,then end of the video
            if args.get("video") and not grabbed:
                print('No Video')

                #f = open(tail + ".txt", "a")

                f = open("Combined.txt", "a")

                f.write('\n' + '\n' + "Maximum Proportion = " +
                        str(MaxProportion) + '\t' + "Minimum Proportion = " +
                        str(MinProportion) + '\n')
                f.close()

                break

            # Crop Frame to remove side irregularities
            #Endoscope Resolution = 640x480
            frame = frame[100:320, 40:600]

            #frame=imutils.resize(frame, width=600)
            ##blurred = cv2.GaussianBlur(frame, (11, 11), 0)
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            mask = cv2.inRange(hsv, HSVLOW, HSVHIGH)
            #####mask = cv2.erode(mask, None, iterations=2)
            ######mask = cv2.dilate(mask, None, iterations=2)

            WhiteVal = cv2.countNonZero(mask)
            BlackVal = TotalPixels - WhiteVal

            ProportionVal = ((float(BlackVal) / float(TotalPixels)) * 100)

            if counter == 1:

                MaxProportion = ProportionVal
                MinProportion = ProportionVal

                #Create text file with headers

                #f = open(tail + ".txt", "a")

                f = open("Combined.txt", "a")

                f.write(tail + '\n' + Time + '\n' +
                        "Black Pixel Initial Total" + '\t' + str(BlackVal) +
                        '\n' + "Initial Proportion Percentage" + '\t' +
                        str(ProportionVal) + '\n' + "Total Pixels = " +
                        str(TotalPixels) + '\n' + "|Frame|" + '\t' +
                        "|BlackPixelVal|" + '\t' + "|Proportion|" + '\n')
                f.close()

            if counter >= 2:

                if ProportionVal > MaxProportion:
                    MaxProportion = ProportionVal

                if ProportionVal < MinProportion:
                    MinProportion = ProportionVal

                #Open new text file with new timestamp
                #f = open(tail + ".txt", "a")

                f = open("Combined.txt", "a")

                f.write(
                    str(counter) + '\t' + str(BlackVal) + '\t' +
                    str(ProportionVal) + '\n')
                f.close()

            ##res = cv2.bitwise_and(frame,frame, mask =mask)
            #outFULL.write(mask)
            #outFULL.release

            #Find Size of Cropped Frame
            #width, height = frame.shape[:2]

            #print "height " + str(height)
            #print "width " + str(width)

            #outCROP.write(mask)
            #outCROP.release
            #cv2.imshow('frame', mask)
            counter += 1

            k = cv2.waitKey(10) & 0xFF

            if k == 27:
                #f = open(tail + ".txt", "a")
                f = open("Combined.txt", "a")

                f.write('\n' + '\n' + "Maximum Proportion = " +
                        str(MaxProportion) + '\t' + + "Minimum Proportion = " +
                        str(MinProportion) + '\n')
                f.close()
                break
Example #4
0
    def initGUI(self):
        # create root window
        self.rootWindow = Tk()
        self.statusText = StringVar(value=self.statusStr)
        self.setStatusStr("Simulation not yet started")

        self.rootWindow.wm_title(self.titleText)
        self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI)
        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.runEvent)
        self.buttonRun.pack(side=TOP, padx=5, pady=5)

        self.showHelp(self.buttonRun,
                      "Runs the simulation (or pauses the running simulation)")
        self.buttonStep = Button(self.frameSim, width=30, height=2,
                                 text="Step Once", command=self.stepOnce)
        self.buttonStep.pack(side=TOP, padx=5, pady=5)
        self.showHelp(self.buttonStep, "Steps the simulation only once")
        self.buttonReset = Button(self.frameSim, width=30, height=2,
                                  text="Reset", command=self.resetModel)
        self.buttonReset.pack(side=TOP, padx=5, pady=5)
        self.showHelp(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.saveParametersCmd,
                                               text="Save parameters to the running model", state=DISABLED)
            self.showHelp(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.saveParametersAndResetCmd,
                                                       text="Save parameters to the model and reset the model")
            self.showHelp(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.changeStepSize, orient=HORIZONTAL,
                               width=25, length=150)
        self.stepScale.set(self.stepSize)
        self.showHelp(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.changeStepDelay,
                               orient=HORIZONTAL, width=25, length=150)
        self.stepDelay.set(self.timeInterval)
        self.showHelp(self.stepDelay, "The visualization of each step is " +
                      "delays by the given number of " +
                      "milliseconds.")
        self.stepDelay.pack(side='left')
        can.pack(side='top')
Example #5
0
#
# In this exercise you must create a Graphical User
# Interface using Tkinter.  The program should create
# a window containing a label and a button.  The label
# displays a number and each time the button is pressed
# the number in the label should decrease by 1 until
# it reaches zero, at which some other value can be
# displayed.  This will give you practice at both
# creating widgets and getting them to interact.
#

# Import the necessary Tkinter functions
from Tkinter import Tk, Button, Label

# Create a window
countdown_window = Tk()

# Give the window a title
countdown_window.title('Countdown')


##### PUT YOUR CODE HERE

# 1. Define a function to be called when the button is
#    pressed which will change the label's value

countdown = 10 

def button_pressed():
    if Label["text"] == "10":
        Label["text"] == "9"
Example #6
0
def error_and_exit(title, main_text):
    """
    Show a pop-up window and sys.exit() out of Python.

    :param title: the short error description
    :param main_text: the long error description
    """
    # NOTE: We don't want to load all of these imports normally.
    #       Otherwise we will have these unused GUI modules loaded in the main process.
    from Tkinter import Tk, Canvas, DISABLED, INSERT, Label, Text, WORD

    root = Tk()
    root.wm_title("Tribler: Critical Error!")
    root.wm_minsize(500, 300)
    root.wm_maxsize(500, 300)
    root.configure(background='#535252')

    # Place the window at the center
    root.update_idletasks()
    w = root.winfo_screenwidth()
    h = root.winfo_screenheight()
    size = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
    x = w / 2 - 250
    y = h / 2 - 150
    root.geometry("%dx%d+%d+%d" % (size + (x, y)))

    Canvas(root,
           width=500,
           height=50,
           bd=0,
           highlightthickness=0,
           relief='ridge',
           background='#535252').pack()
    pane = Canvas(root,
                  width=400,
                  height=200,
                  bd=0,
                  highlightthickness=0,
                  relief='ridge',
                  background='#333333')
    Canvas(pane,
           width=400,
           height=20,
           bd=0,
           highlightthickness=0,
           relief='ridge',
           background='#333333').pack()
    Label(pane,
          text=title,
          width=40,
          background='#333333',
          foreground='#fcffff',
          font=("Helvetica", 11)).pack()
    Canvas(pane,
           width=400,
           height=20,
           bd=0,
           highlightthickness=0,
           relief='ridge',
           background='#333333').pack()

    main_text_label = Text(pane,
                           width=45,
                           height=6,
                           bd=0,
                           highlightthickness=0,
                           relief='ridge',
                           background='#333333',
                           foreground='#b5b5b5',
                           font=("Helvetica", 11),
                           wrap=WORD)
    main_text_label.tag_configure("center", justify='center')
    main_text_label.insert(INSERT, main_text)
    main_text_label.tag_add("center", "1.0", "end")
    main_text_label.config(state=DISABLED)
    main_text_label.pack()

    pane.pack()

    root.mainloop()

    # Exit the program
    sys.exit(1)
Example #7
0
    print 'pngout nao instalado ou nao definido em PATH.'
    raw_input("Pressione ENTER para sair...")
    exit(-1)

os.system('cls' if os.name == 'nt' else 'clear')
print 'RES Builder'
print '----------------------------------------------------------'
print 'Densidades: '
for den in dpis_str:
    print den + ' ',

print '\n'

files = glob.glob('*.svg')
files += glob.glob('*/*.svg')
Tk().withdraw()
path = askdirectory().encode('utf8')
print 'Output Dir: ' + path

for svg in files:

    tree = ET.parse(svg)
    root = tree.getroot()
    width = int(root.attrib['width'])
    height = int(root.attrib['height'])

    for index in range(len(dpis)):
        dpi = dpis[index]
        dpi_str = dpis_str[index]

        current_path = path + '/drawable-' + dpi_str + '/'
from functools import partial as pto
from Tkinter import Tk, Button, X, Y
from tkMessageBox import showinfo, showwarning, showerror
WARN = 'warn'
CRIT = 'crit'
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('Warning', 'Warning 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='white').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()')
    print cmd
    eval(cmd)
top.mainloop()
Example #9
0
 def setUpClass(cls):
     requires('gui')
     from Tkinter import Tk, Text
     cls.Text = Text
     cls.root = Tk()
Example #10
0
 def __init__(self, master=None, **kw):
     if master is None:
         master = Tk()
     Frame.__init__(self, master, **kw)
     self.labels = {}
Example #11
0
def main():
    print "Please select a video file(now only support .avi)..."
    Tk().withdraw()
    filename = askopenfilename(
    )  # show an "Open" dialog box and return the path to the selected file
    print(filename)
    fname = getName(str(os.path.basename(filename)))
    if len(filename) < 1:
        print "Error - please select a file."
        return

    cap = cv2.VideoCapture()
    cap.open(filename)

    if not cap.isOpened():
        print "Fatal error - could not open video %s. Please use avi video files." % filename
        return
    else:
        print "Parsing video %s..." % filename
        width = 64  #cap.get(3)
        widthMid = 32  #int(width/2)
        height = 64  #cap.get(4)
        heightMid = 32  #int(height/2)
        frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
        print "Video Resolution is reduced to: %d x %d" % (width, height)
        print "There are %d frames from video." % frame_count
        S = raw_input(
            "Please select a method to find video transitions:\n A: Copying Pixels\n B: Histogram Differences\n"
        )
        print "Processing..."
        if (S == 'A' or S == 'a'):
            #Copying Pixels
            STI_column = np.zeros((int(height), int(frame_count), 3))
            STI_row = np.zeros((int(width), int(frame_count), 3))
            i = 0
            while True:
                (rv, im) = cap.read(
                )  # im is a valid image if and only if rv is true
                if not rv:
                    break
                im = cv2.resize(
                    im, (64, 64),
                    interpolation=cv2.INTER_CUBIC)  # resize to 64*64
                mid_column = im[:, widthMid]
                mid_row = im[heightMid, :]
                STI_column[:, i] = mid_column
                STI_row[:, i] = mid_row
                i = i + 1
            extra = "CP"
            cv2.imwrite(fname + '_STI_column_' + extra + '.png', STI_column)
            cv2.imwrite(fname + '_STI_row_' + extra + '.png', STI_row)
            plt.figure(1)
            plt.imshow(STI_column, cmap="gray")
            plt.xticks([]), plt.yticks([])
            plt.title('STI_column')

            plt.figure(2)
            plt.imshow(STI_row, cmap="gray")
            plt.xticks([]), plt.yticks([])
            plt.title('STI_row')
            plt.show(block=False)
            cap.release()
            raw_input("Process complete. Hit any key to exit...")
        elif (S == 'B' or S == 'b'):
            #Histogram differences
            histo = np.zeros(
                (int(frame_count), 2, int(height)))  #[[x1,x2],[y1,y2]]
            numbins = 1 + math.log(int(height), 2)
            bins = np.linspace(0, 1, numbins)
            frame = 0
            H_column = np.zeros((int(width), int(frame_count),
                                 int(numbins) - 1, int(numbins) - 1))
            H_row = np.zeros((int(height), int(frame_count), int(numbins) - 1,
                              int(numbins) - 1))
            STI_column = np.zeros((int(height), int(frame_count)))
            STI_row = np.zeros((int(width), int(frame_count)))
            while True:
                (rv, im) = cap.read(
                )  # im is a valid image if and only if rv is true
                if not rv:
                    break
                im = cv2.resize(
                    im, (64, 64),
                    interpolation=cv2.INTER_CUBIC)  # resize to 64*64
                #get STI for all columns
                for index in range(int(width)):
                    column = im[:, index]
                    histX = np.zeros(int(height), dtype=np.float)
                    histY = np.zeros(int(height), dtype=np.float)
                    for i in range(int(height)):
                        R, G, B = column[i]
                        RGB = int(R) + int(G) + int(B)
                        if (RGB) != 0:
                            r = R / float(RGB)
                            g = G / float(RGB)
                        else:
                            r = 0
                            g = 0
                        #print str(r) + " " + str(g) + " and the original RGB is: " + str(R) + " " + str(G) + " " + str(B)
                        histX[i] = r
                        histY[i] = g
                    H_column[index][frame], xedges, yedges = np.histogram2d(
                        histX, histY, bins, normed=True)
                #get STI for all rows
                for index in range(int(height)):
                    row = im[index, :]
                    histX = np.zeros(int(width), dtype=np.float)
                    histY = np.zeros(int(width), dtype=np.float)
                    for i in range(int(width)):
                        R, G, B = row[i]
                        RGB = int(R) + int(G) + int(B)
                        if (RGB) != 0:
                            r = R / float(RGB)
                            g = G / float(RGB)
                        else:
                            r = 0
                            g = 0
                        #print str(r) + " " + str(g) + " and the original RGB is: " + str(R) + " " + str(G) + " " + str(B)
                        histX[i] = r
                        histY[i] = g
                    H_row[index][frame], xedges, yedges = np.histogram2d(
                        histX, histY, bins, normed=True)
                frame = frame + 1
            standard = histogram_intersection(H_column[0][0], H_column[0][0],
                                              int(numbins))
            p = raw_input(
                "Please enter a threshold percentage(0-100, suggest 70-95): ")
            while isanumber(p):
                p = float(p)
                if (p >= 0) and (p <= 100):
                    thre = standard * p / 100
                else:
                    print "Invalid number, exiting..."
                    return
                for i in range(int(height)):
                    for j in range(int(frame_count)):
                        if j == 0:
                            STI_column[i][j] = threshold(
                                histogram_intersection(H_row[i][j],
                                                       H_row[i][j],
                                                       int(numbins)), thre)
                        else:
                            STI_column[i][j] = threshold(
                                histogram_intersection(H_row[i][j],
                                                       H_row[i][j - 1],
                                                       int(numbins)), thre)
                for i in range(int(width)):
                    for j in range(int(frame_count)):
                        if j == 0:
                            STI_row[i][j] = threshold(
                                histogram_intersection(H_column[i][j],
                                                       H_column[i][j],
                                                       int(numbins)), thre)
                        else:
                            STI_row[i][j] = threshold(
                                histogram_intersection(H_column[i][j],
                                                       H_column[i][j - 1],
                                                       int(numbins)), thre)
                find_column = findTrans(STI_column)
                find_row = findTrans(STI_row)
                extra = "HD_" + str(p)
                cv2.imwrite(fname + '_STI_column_' + extra + '.png',
                            STI_column)
                cv2.imwrite(fname + '_STI_row_' + extra + '.png', STI_row)
                plt.figure(1)
                plt.imshow(STI_column, cmap="gray")
                plt.xticks([]), plt.yticks([])
                plt.title('STI_column')

                plt.figure(2)
                plt.imshow(STI_row, cmap="gray")
                plt.xticks([]), plt.yticks([])
                plt.title('STI_row')
                plt.show(block=False)
                cap.release()
                #if find_column.size != 0:
                print "Here is the frame which contains the transition from column:"
                print find_column
                #if find_row.size != 0:
                print "Here is the frame which contains the transition from row:"
                print find_row
                p = raw_input(
                    "Process complete. Enter another number between 0-100 to try another threshold. Or Hit any other key to exit..."
                )
        else:
            print "Invalid option, program ending..."
            return
Example #12
0
    for o, a in opts:
        if o == "-c":
            component_name = a
        if o == "-g":
            window_geometry = a

    try:
        filename = args[0]
    except:
        usage()
        sys.exit(1)

    if component_name is None:
        component_name = os.path.splitext(os.path.basename(filename))[0]

    pyvcp0 = Tk()
    pyvcp0.title(component_name)
    if window_geometry:
        pyvcp0.geometry(window_geometry)

    vcpparse.filename = filename
    pycomp = vcpparse.create_vcp(compname=component_name, master=pyvcp0)
    pycomp.ready()

    try:
        try:
            pyvcp0.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
    finally:
        pycomp.exit()
Example #13
0
def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()
Example #14
0
def fet_quiz(test1, q0, q1):
    marks = 0
    master = Tk()
    master.maxsize(700, 500)
    master.minsize(700, 500)
    master.geometry("500x500")
    id = int(q0)
    cn = str(q1).upper()

    try:
        sql = "select * from question where qid=%s and _cour=%s"
        cursor.execute(sql, (id, cn))
        results = cursor.fetchall()
        x = [0, 0]
        answer = [0, 0]

        def nex():
            if x[0] > 0:
                print x[1]
                if answer[0].get() == answer[1]:
                    x[1] += 1
                    print x[1]
            if x[0] > (len(results) - 1):
                master.destroy()
                tkMessageBox.showinfo("Title", (
                    "Quiz is finished. No more attempts are available. Marks Obtained: %s"
                    % x[1]))
                typ = str(x[1])
                add_marks(typ)
                return
            y = Label(master,
                      text="Question: %s " % results[x[0]][2],
                      justify=LEFT,
                      anchor=W,
                      font=("arial", 12))
            y.pack()
            z = Label(master, text="1) %s" % results[x[0]][3])
            z.pack()
            a = Label(master, text="2) %s" % results[x[0]][4])
            a.pack()
            b = Label(master, text="3) %s" % results[x[0]][5])
            b.pack()
            c = Label(master, text="4) %s" % results[x[0]][6])
            c.pack()
            var = StringVar()
            ans = Entry(master, textvariable=var)
            ans.pack()
            answer[0] = ans
            answer[1] = results[x[0]][7]
            # print type(int(ans.get()))f
            # if (ans.get()==results[x[0]][7]):
            #   x[1]+=1
            # print var.get()
            # sub=Button(master,text="Submit",command=sequence(nex,mar))
            sub = Button(master,
                         text="Submit",
                         command=nex,
                         bg="white",
                         font="arial")
            sub.pack()
            # chk(results[x[0][7]],var.get())

            x[0] += 1

        nex()
        # scrollbar.config(command=listbox.yview)
        # marks=112
        # tkMessageBox.showinfo("Title",marks)

        # while(x<len(results)):
    except:
        print "Cannot locate data"
Example #15
0
 def make_widgets(self):
     self.root = Tk()
     self.root.title("Simple Prog")
Example #16
0
from sys import argv, exit
from Tkinter import Tk

try:
    tkObj = Tk()
except Exception as e:
    print "Failed to create the Tkinter object: " + str(e)

cssPath = tkObj.clipboard_get()
print "The CSS path retrieved from your clipboard is:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + str(
    cssPath)

#if len(argv)!=2:
#	exit("Something went wrong! Give CSS Path as an argument enclused in quotes")
#if argv[1]=="" or len(argv[1])<10:
#	exit("Are you sure the CSS Path is corect?")
#cssPath = argv[1]

# List of symbols, tags and elements to remove from the CSS path
graveList = [
    " >", ".ng-scope", ".ng-isolate-scope", ".ng-include", ".ng-view",
    ".ng-animate"
]

for mark in graveList:
    cssPath = cssPath.replace(mark, "")

print "\n\nThe modified CSS path sent to your clipboard is:"
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print cssPath
Example #17
0
def main():

    if len(sys.argv) == 2:
        configFileName = sys.argv[1]
    else:
        configFileName = "freeworld.config"

    cfgReader = ConfigFileReader.ConfigFileReader(configFileName)

    ret, height, width, numRobots, R, baseX, baseY, initLocs, obstacles = cfgReader.readCfg(
    )
    if ret == -1:
        print 'readCfg() Unsuccessful!'
        sys.exit(-1)
    else:
        print 'Read the config file', configFileName

    k = 2
    T = 100000

    # algo = Faigl.Faigl(height, width, obstacles, numRobots, initLocs, T)
    # algo = FrontierClusters.FrontierClusters(height, width, obstacles, numRobots, initLocs, T)
    algo = CAC.CAC(height, width, obstacles, numRobots, initLocs, T)
    # algo = Yamauchi.Yamauchi(height, width, obstacles, numRobots, initLocs, T)
    # algo = Burgard.Burgard(height, width, obstacles, numRobots, initLocs, T)

    # algo.printGrid()
    # print ''
    # print ''
    # cfgc = algo.generateCfgcPopulation()

    # for j in range(T):
    # 	algo.runOneIterV2()

    # timeTaken = algo.printVisitedStatus()
    # if timeTaken == 0:
    # 	return T
    # return timeTaken

    # Code that takes care of the GUI
    if height <= 10:
        xoffset = 300
    else:
        xoffset = 100
    if width <= 10:
        yoffset = 300
    else:
        yoffset = 100

    maxScreenHeight = 700
    cellSize = int(floor(maxScreenHeight / (height + 2)))

    root = Tk()

    gui = GridUI.GridUI(root, height, width, cellSize, algo.gridworld,
                        algo.robots, algo.frontier)
    guiHeight = str((height + 2) * cellSize)
    guiWidth = str((width + 2) * cellSize)
    xOffset = str(xoffset)
    yOffset = str(yoffset)
    geometryParam = guiWidth + 'x' + guiHeight + '+' + xOffset + '+' + yOffset
    root.geometry(geometryParam)

    # Runs one iteration of the algorithm and updates the GUI
    def run():

        algo.runOneIter()
        gui.redraw(height, width, cellSize, algo.gridworld, algo.robots,
                   algo.frontier)
        root.after(1, run)

    root.after(1, run)
    root.mainloop()
Example #18
0
def main():

    root = Tk()
    #root.geometry("350x300+300+300")
    Example(root)
    root.mainloop()
Example #19
0
 def _tk_setup(self):
     self._root = Tk()
     self._root.bind('<<nvim_redraw>>', self._tk_nvim_redraw)
     self._root.bind('<<nvim_detach>>', self._tk_nvim_detach)
     self._root.bind('<Key>', self._tk_key)
Example #20
0
    def setup_layout(self):
        self.container.grid_rowconfigure(1, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(4, weight=1)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.info_label.grid(row=0, column=0, columnspan=5, sticky='nsew')
        self.r1.grid(row=1, column=0)
        self.r2.grid(row=1, column=2)
        self.r3.grid(row=1, column=4)
        self.r4.grid(row=4, column=2)
        self.r5.grid(row=4, column=0)

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

    # Handle Events
    def radio_btn_pressed(self):
        self.entrar_choza(self.var.get())


if __name__ == "__main__":

    mainwin = Tk()
    WIDTH = 1280
    HEIGHT = 700
    mainwin.geometry("%sx%s" % (WIDTH, HEIGHT))
    mainwin.resizable(0, 0)
    mainwin.title("Ataca a los orcos V 2.0.0 - El Videojuego")
    game_app = JuegoChozas(mainwin)
    mainwin.mainloop()
Example #21
0
import xlrd, os, re, sys
from time import sleep
from Tkinter import Tk
from tkFileDialog import askopenfilename, asksaveasfile, asksaveasfilename

Tk().withdraw(
)  # we don't want a full GUI, so keep the root window from appearing

xlsfile = askopenfilename()
book = xlrd.open_workbook(xlsfile, 'rb')

print "Opening the file ..."

jil_file = asksaveasfile(mode='wb', defaultextension=".jil")

sheet = book.sheet_by_index(0)


def auto_restart(row):
    #auto_restart

    auto_restart_tuple = ("auto_restart", "AUTO_RESTART", "Auto Restart",
                          "Auto Restart", "auto restart", "AUTO RESTART")
    for columns in range(sheet.ncols):

        for rows in range(sheet.nrows):

            if unicode(sheet.cell_value(
                    rows - 1, columns)).lower() in auto_restart_tuple:
                unicode(sheet.cell_value(row, columns)).strip()
                if sheet.cell_value(row, columns) != "" and sheet.cell_value(
Example #22
0
from Tkinter import Tk

Tk().mainloop(
)  # we don't want a full GUI, so keep the root window from appearing
Example #23
0
 def setUpClass(cls):
     requires('gui')
     cls.root = Tk()
     cls.root.withdraw()
     cls.text = Text(cls.root)
     cls.editwin = DummyEditwin(cls.text)
Example #24
0
def __tkinter_canvas(width, height):
    """This function creates a new Tkinter canvas."""
    w = Canvas(Tk(), width=width, height=height)
    w.pack()
    return w
Example #25
0
                self.browser.find_element_by_id("addPassengerForm:psdetail:" +
                                                str(index) +
                                                ":psgnGender").send_keys(
                                                    self.values["Gender" +
                                                                str(index)])
                self.browser.find_element_by_id(
                    "addPassengerForm:mobileNo").send_keys(
                        self.values["MobileNo"])
            self.browser.find_element_by_id("nlpAnswer").send_keys("")
            time.sleep(10)
            self.browser.find_element_by_id("COD").click()
            self.browser.find_elements_by_css_selector(
                "input[type='radio'][value='100']")[0].click()
            self.browser.find_element_by_id("validate").click()
            exit(0)
        except BaseException as error:
            raise error


if __name__ == '__main__':
    FIELDS = [
        "UserID", "Password", "TrainNo", "FromStation", "ToStation", "Date",
        "Class", "Quota", "MobileNo", "PassengersDetail:", "Name", "Age",
        "Gender"
    ]
    ROOT = Tk()
    BOOKING = BookingGui(ROOT, FIELDS)
    BOOKING.main_gui()
    BOOKING.pack(side=LEFT)
    ROOT.mainloop()
Example #26
0
from Tkinter import *
from Tkinter import Tk
import Tkinter as tk
import random
import time
import os
from Tkinter import Canvas, Label, Frame, Button, Tk, Entry, Toplevel
from graphviz import Digraph

global master
master = Tk()

master.title('SLR Parser')

canvas = Canvas(master,
                width=master.winfo_screenwidth(),
                height=master.winfo_screenheight())

u1_entry = Entry(canvas)
canvas.create_window(220, 200, window=u1_entry, height=150, width=300)

u2_entry = Entry(canvas)
canvas.create_window(220, 430, window=u2_entry, height=100, width=300)

grammars = open("grammar2.txt")
G = {}
C = {}
I = {}
J = {}

inputstring = ""
Example #27
0
    def __init__(self, statement, entry):
        """
            instantiate a transaction window
        """
        self.rules = statement.rules

        self.root = Tk()
        self.root.title('Manual Annotation')
        t = Frame(self.root, bd=2 * self.BORDER)

        # top stack: input file name
        f = Frame(t)
        caption = "File: " + statement.filename + ", line: " + \
            str(statement.file_line)
        Label(f, text=caption).pack()
        f.pack(pady=self.PADDING)

        # middle stack: entry details
        f = Frame(t)
        f1 = LabelFrame(f, text="Date")
        self.date = Label(f1, text=entry.date)
        self.date.pack(padx=self.PADDING, pady=self.PADDING)
        f1.pack(side=LEFT, padx=self.PADDING)

        f1 = LabelFrame(f, text="Amount")
        self.amount = Label(f1, text=entry.amount)
        self.amount.pack(padx=self.PADDING, pady=self.PADDING)
        f1.pack(side=LEFT, padx=self.PADDING)

        f1 = LabelFrame(f, text="Account")
        self.acct = Text(f1, height=1, width=self.ACCT_WID)
        if entry.account is not None:
            self.acct.insert(END, entry.account)
        self.acct.pack(padx=self.PADDING, pady=self.PADDING)
        f1.pack(side=LEFT, padx=self.PADDING)

        f1 = LabelFrame(f, text="Description")
        self.desc = Text(f1, height=1, width=self.DESC_WID)
        self.desc.insert(END, entry.description)
        self.desc.pack(padx=self.PADDING, pady=self.PADDING)
        f1.pack(side=LEFT, padx=self.PADDING)
        f.pack(pady=self.PADDING)

        # bottom stack: action buttons
        f = Frame(t)
        b = Button(f, text="Accept", command=self.accept)
        b.pack(side=LEFT, padx=self.PADDING)

        # account selection menu
        self.account = StringVar(f)
        self.account.set(entry.account)
        m = OptionMenu(f,
                       self.account,
                       *sorted(statement.acc_list),
                       command=self.chooseAcct)
        m.pack(side=LEFT, padx=self.PADDING)

        # aggregate description selection menu
        self.description = StringVar(f)
        self.menu = OptionMenu(f,
                               self.description,
                               *sorted(statement.agg_list),
                               command=self.chooseDesc)
        self.menu.pack(side=LEFT, padx=self.PADDING)

        b = Button(f, text="Delete", command=self.delete)
        b.pack(side=LEFT, padx=self.PADDING)
        f.pack(padx=self.PADDING, pady=self.PADDING)

        # finalize
        t.pack(side=TOP)
        self.entry = entry  # default: return what we got
Example #28
0
def main():

    root = Tk()
    root.geometry("850x500+500+500")
    app = Reader(root)
    root.mainloop()
Example #29
0
import ttk
from Tkinter import Tk
from ttk import *
from Tkinter import *
from PIL import Image, ImageTk

# root = Tk()
# ttk.Button(root, text='Hi!').grid()
# root.mainloop()




root = Tk()
root.title('Steps to Meters')

mainframe = ttk.Frame(root, padding="3 3 12 12", borderwidth=10, relief='raised')
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

onevar = BooleanVar()
twovar = BooleanVar()
onevar.set(True)
twovar.set(False)
one = ttk.Checkbutton(mainframe, text='one', variable=onevar, onvalue=True)
two = ttk.Checkbutton(mainframe, text='two', variable=twovar, onvalue=True)



steps = StringVar()
def copy_to_clipboard(text):
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append(text)
    r.destroy()