Esempio n. 1
0
    def create_tree_bar(self, test, window, depth, row):
        """Create progress bar for a test in an hierarchical form."""
        name = test.data.name
        if test.IS_COMPLEX:
            total = test._expected_time

        else:
            avg_time = test._expected_time
            if avg_time:
                total = int(avg_time) * 10

            else:
                total = 10
                name += " (No statistics)"

        label = tkinter.Label(window, text=name, height=1)
        style = Style()
        style.theme_use('clam')
        style_name = "{}.Horizontal.TProgressbar".format(test.identifier)
        style.configure(style_name, foreground='red', background='red')
        progress = Progressbar(window,
                               orient=tkinter.HORIZONTAL,
                               maximum=total,
                               length=self.BAR_WIDTH,
                               mode='determinate',
                               style=style_name)

        test.progress_bar = ProgressContainer(test, progress, style_name)

        label.grid(column=depth, row=row)
        progress.grid(column=depth + 1, row=row)
Esempio n. 2
0
 def __init__(self, frame, options, stringvar=None, width=20, height=21):
     self.text_font = ('Microsoft Sans Serif', '10')
     combostyle = Style()
     combostyle.theme_create('combostyle',
                             parent='alt',
                             settings={
                                 "TCombobox": {
                                     "configure": {
                                         "selectbackground": "#F7A5D2",
                                         "fieldbackground": "#F7A5D2",
                                         "background": "#C0C0C0",
                                         "selectforeground": "black",
                                         "bordercolor": "#C0C0C0"
                                     }
                                 }
                             })
     combostyle.theme_use('combostyle')
     Combobox.__init__(self,
                       frame,
                       values=options,
                       textvariable=stringvar,
                       width=width,
                       height=height,
                       state="readonly",
                       font=self.text_font)
     frame.root.option_add('*TCombobox*Listbox.font', self.text_font)
     self.bind("<<ComboboxSelected>>", self.do)
Esempio n. 3
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.centerWindow(500, 500)

    def initUI(self, width=300, height=300):
        self.parent.title("Simple")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x_loc = (sw - width) / 2
        y_loc = (sh - height) / 2
        ww = self.winfo_screenwidth()
        wh = self.winfo_screenheight()
        buttonWidth = 100
        buttonHeight = 50
        x_but_loc = (ww - buttonWidth) / 2
        y_but_loc = (wh - buttonHeight) / 2
        self.parent.geometry("%dx%d+%d+%d" % (width, height, x_loc, y_loc))
        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=x_but_loc, y=y_but_loc)

    def centerWindow(self, width=300, height=300):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x_loc = (sw - width) / 2
        y_loc = (sh - height) / 2
        self.parent.geometry("%dx%d+%d+%d" % (width, height, x_loc, y_loc))
Esempio n. 4
0
class Example(Frame):    
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Torrent Downloader")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()
        self.style = Style()
        self.style.theme_use("alt")
        self.pack(fill=BOTH, expand=1)
        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=50, y=50)
 
    def centerWindow(self):
        w = 290
        h = 150
 
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
Esempio n. 5
0
class Exemple(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.style = Style()
        self.style.theme_use("default")

        self.master.title("convertisseur")
        self.pack(fill = BOTH, expand = 1)

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


        bouton = Button(self, text = "Quit",
                        command = self.quit)
        bouton.pack(side = RIGHT, padx = 5, pady = 5)
        bouton1 = Button(self, text = "stay")
        bouton1.pack(side = RIGHT, padx = 5, pady = 5)

        self.var = BooleanVar()
        cb = Checkbutton(self, text = "Montre le titre",
                         variable = self.var, command = self.onClick)
        self.var.set(True)
        cb.pack(side = LEFT, padx = 5, pady = 5)

    def onClick(self):
        if self.var.get() == True:
            self.master.title("convertisseur")
        else:
            self.master.title("")
Esempio n. 6
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
Esempio n. 7
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=True)

        self.scale = Scale(self, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0, column=0, padx=10, pady=10, sticky=E + W)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.grid(row=0, column=1, sticky=W, padx=10)

        self.grid_columnconfigure(0, weight=1)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
Esempio n. 8
0
    def __init__(self, window, initial=' ', options=[], instance=str, command=None, width=None):

        if initial not in options:
            raise RuntimeError('DropDown menu: Not valid initial value ({0}).'.format(initial))

        self.variable = StringVar(window.root, value=initial)
        self.instance = instance
        self.command = command

        try:

            combostyle = Style()
            combostyle.theme_create('combostyle', parent='alt',
                                    settings={'TCombobox': {'configure':
                                                                {'selectbackground': 'white',
                                                                 'fieldbackground': 'white',
                                                                 'background': 'white'}}})
            combostyle.theme_use('combostyle')

        except:
            pass
        if width:
            widget = Combobox(window.main_frame, textvariable=self.variable, state='readonly', width=width)
        else:
            widget = Combobox(window.main_frame, textvariable=self.variable, state='readonly', width=int(window.log.entries_width * 0.8))

        options = [str(ff) for ff in options]
        widget['values'] = tuple(options)

        widget.bind('<<ComboboxSelected>>', self.internal_command)

        HOPSWidget.__init__(self, window, widget, 'DropDown')
Esempio n. 9
0
class MainWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.grid()
        self.init_ui()
        self.wallhandler = WallHandler()
        self.reddit = Reddit()

    def init_ui(self):
        self.parent.title("Papers")
        self.style = Style()
        self.style.theme_use("clam")
        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.grid(row=0, column=0)
        label = Label(frame, text="Change Wallpaper")
        label.grid(row=0, column=0)
        button = Button(frame, text="Change", command=self.change)
        button.grid(row=1, column=0)
        label = Label(frame, text="Fetch Wallpapers")
        label.grid(row=2, column=0)
        button = Button(frame, text="Fetch", command=self.fetch)
        button.grid(row=3, column=0)

    def change(self):
        self.wallhandler.run()

    def fetch(self):
        self.reddit.run()
Esempio n. 10
0
class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Buttons")
        self.style = Style()
        self.style.theme_use("default")

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

        self.pack(fill=BOTH, expand=True)

        closeButton = Button(self, text="Close")
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)
        resetButton = Button(self, text="Reset")
        resetButton.pack(side=LEFT, padx=5)
class Window(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.style = Style()
        self.style.theme_use("default")
        self.master.title("Quit Button Example")
        self.pack(fill=BOTH, expand=1)

        self.centerWindow()
        self.widget()

    def centerWindow(self):

        w = 290
        h = 150

        sw = self.master.winfo_screenwidth()
        sh = self.master.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2

        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def widget(self):

        quitButton = Button(self, text="quit", command=self.quit)
        quitButton.place(x=50, y=50)
Esempio n. 12
0
class DarkVen0m(tk.Tk):
    
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
        self.title("DarkVenom")
        self.style = Style()
        self.style.theme_use("default")
        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo, PageThree, PageFour, PageFive, PageSix):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
Esempio n. 13
0
 def __init__(self, title="", message="", button="Ok", image=None,
              checkmessage="", style="clam", **options):
     """
         Create a messagebox with one button and a checkbox below the button:
             parent: parent of the toplevel window
             title: message box title
             message: message box text
             button: message displayed on the button
             image: image displayed at the left of the message
             checkmessage: message displayed next to the checkbox
             **options: other options to pass to the Toplevel.__init__ method
     """
     Tk.__init__(self, **options)
     self.resizable(False, False)
     self.title(title)
     s = Style(self)
     s.theme_use(style)
     if image:
         Label(self, text=message, wraplength=335,
               font="Sans 11", compound="left",
               image=image).grid(row=0, padx=10, pady=(10, 0))
     else:
         Label(self, text=message, wraplength=335,
               font="Sans 11").grid(row=0, padx=10, pady=(10, 0))
     b = Button(self, text=button, command=self.destroy)
     b.grid(row=2, padx=10, pady=10)
     self.var = BooleanVar(self)
     c = Checkbutton(self, text=checkmessage, variable=self.var)
     c.grid(row=1, padx=10, pady=0, sticky="e")
     self.grab_set()
     b.focus_set()
     self.wait_window(self)
Esempio n. 14
0
    def LandingPage(self, frame):
        h = lambda: controlers.shiftpage(self, frame, function=navigation)
        self.geometry('300x500+600+300')
        self.resizable(0, 0)
        #editControls()

        label = tkinter.Label(
            self,
            text='Welcome to wincode \n A custom text editor for python',
            foreground='blue')
        label.pack()
        main.img = ImageTk.PhotoImage(Image.open("images.jpg"))
        #canvas.create_image(20, 20, anchor='nw', image=main.img)
        lab = tkinter.Label(self, image=main.img)
        lab.pack(pady='40')
        button = tkinter.Button(self, text='Start Programming', command=h)
        button.pack(pady='40')
        yearlabel = tkinter.Label(text='November 2018')
        yearlabel.pack()
        #testing messagebox
        #messagebox.showerror("Error", "Error message")
        #messagebox.showwarning("Warning","Warning message")
        #messagebox.showinfo("Information","Informative message")
        #main.waiting(self, frame)
        s = Style()
        s.theme_use('clam')
Esempio n. 15
0
    def create_playlist_widgets(self):
        """
        Initialises widgets related to searching through playlists for a song. Does not display the playlist results listbox and label.
        """
        playlist_search = tk.Frame(self.main_frame)
        playlist_search.grid(row=4,
                             column=0,
                             columnspan=2,
                             rowspan=3,
                             pady=(0, 10))

        self.playlist_search_btn = tk.Button(playlist_search,
                                             text="Search Playlists For Song",
                                             command=self.search_playlists,
                                             state=tk.DISABLED)
        self.playlist_search_btn.grid(row=0, column=0, columnspan=2, pady=5)

        # Will be displayed at later point
        self.playlist_label = tk.Label(playlist_search,
                                       text='Playlist Results')
        self.playlist_results = tk.Listbox(playlist_search, width=50)

        # Loading Bar
        loading_style = Style()
        loading_style.theme_use('alt')
        loading_style.configure('TProgressbar', thickness=10)
        self.playlist_loading = Progressbar(self.main_frame,
                                            style='TProgressbar',
                                            mode='indeterminate',
                                            length=150,
                                            maximum=50)
Esempio n. 16
0
class About:
    def __init__(self, parent):
        self.parent = parent

        self.style = Style()
        self.style.theme_use('clam')

        self.root = Toplevel()
        self.root.title('pyEdit - About')
        self.root.resizable(False, False)
        self.root.minsize(200, 50)
        self.root.columnconfigure(0, weight=1)

        self.root.bind('<Expose>', lambda e: Utils.on_expose(self))
        self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self))

        self.label_app_name = Label(self.root, text='pyEdit (Lightweight IDE)')
        self.label_app_name.grid(column=0, row=0, sticky='nsew', ipadx=5, ipady=5)

        self.label_author = Label(self.root, text='Author: Marek Kouřil')
        self.label_author.grid(column=0, row=1, sticky='nsew', ipadx=5, ipady=5)

        self.label_year = Label(self.root, text='2016')
        self.label_year.grid(column=0, row=2, sticky='nsew', ipadx=5, ipady=5)

        self.label_course = Label(self.root, text='\'URO\' course')
        self.label_course.grid(column=0, row=3, sticky='nsew', ipadx=5, ipady=5)
Esempio n. 17
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.frame = Frame(height=10, width=100, relief=SUNKEN)
        self.frame.pack(fill=X, expand=1)
        self.frame.grid_columnconfigure(0, weight=1)

        self.scale = Scale(self.frame, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0,
                        column=0,
                        columnspan=2,
                        padx=10,
                        pady=10,
                        sticky=E + W)
        #scale.pack(fill=X, padx=15, expand=1)
        #scale.pack(fill=X, padx=15)

        self.var = IntVar()
        self.label = Label(self.frame, text=0, textvariable=self.var)
        self.label.grid(row=0, column=2, sticky=W, padx=10)
        # self.label.pack(side=LEFT)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
class Window(Tk, Frame):
    def __init__(self):
        Tk.__init__(self)

        self.style = Style()
        self.title("vRABlueprintTool")
        self.style.theme_use("default")

        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (ConnectPage, MainPage, DownloadPage, UploadPage):
            pageName = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[pageName] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("ConnectPage")

    def show_frame(self, pageName):
        frame = self.frames[pageName]
        frame.tkraise()
Esempio n. 19
0
 def _style(self) -> tuple[str, Style]:
     name = f'{self.id}.customtable.Treeview'
     tk_style = Style()
     style = self.style
     tk_style.theme_use(style.ttk_theme)
     font = style.font
     tk_style.configure(name,
                        rowheight=self.row_height or style.char_height)
     cfg_keys = ('font', 'foreground', 'background', 'fieldbackground')
     bg = style.bg.default
     if base := {
             k: v
             for k, v in zip(cfg_keys, (font, style.fg.default, bg, bg))
             if v is not None
     }:
         tk_style.configure(name, **base)
         if (selected_row_color :=
                 self.selected_row_color) and ('foreground' in base
                                               or 'background' in base):
             for i, color in enumerate(('foreground', 'background')):
                 if color in base and selected_row_color[i] is not None:
                     tk_style.map(
                         name, **{
                             color:
                             _fixed_style_map(tk_style, name, color,
                                              selected_row_color)
                         })
Esempio n. 20
0
    def __init__(self,
                 parent,
                 lf_text,
                 mess_text,
                 def_text="",
                 colour='brown',
                 mod=False):
        self.parent = parent
        self.lf_text = lf_text
        self.mess_text = mess_text
        self.mod = mod

        self.out_var = StringVar()
        self.out_var.set(def_text)

        self.farbe = farbe = {
            'blue': 'light blue',
            'brown': '#EDEF77',
            'green': 'light green',
            'pink': '#EAAFBF'
        }

        colour = colour if colour in farbe else 'brown'

        self.colour = colour

        st1 = Style()
        st1.theme_use('default')

        st1.configure(colour + '.TLabelframe', background='#C9B99B')
        st1.configure(colour + '.TLabelframe.Label', background=farbe[colour])
        st1.configure(colour + '.TCheckbutton', background=farbe[colour])
        st1.configure('brown.TLabel', background='#EDEF77')

        self.construct()
Esempio n. 21
0
class OPEN(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.master.title("PyMP3")
        self.style = Style()
        self.style.theme_use("default")

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

        self.pack(fill=BOTH, expand=True)

        closeButton = Button(self, text="CLOSE", command=window.destroy)
        closeButton.pack(side=RIGHT, padx=5, pady=5)

        Button2 = Button(self, text="STOP", command=stop)
        Button2.pack(side=RIGHT, padx=5, pady=5)

        Button4 = Button(self, text="UNPAUSE", command=unpause)
        Button4.pack(side=RIGHT, padx=5, pady=5)

        Button3 = Button(self, text="PAUSE", command=pause)
        Button3.pack(side=RIGHT, padx=5, pady=5)

        Button1 = Button(self, text="PLAY", command=play)
        Button1.pack(side=RIGHT, padx=5, pady=5)
Esempio n. 22
0
class Ventana(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.style = Style()
        self.style.theme_use("default")

        self.master.title("Órdenes de impresión")
        self.pack(fill=BOTH, expand=1)


        label1 = Label(raiz, text="Ingresa la ubicación del archivo de órdenes de impresión").place(x=10, y=10)
        caja_ingresa_ubicacion=Entry(self, textvariable=entrada).place(x=30, y=80)

        #Boton para procesar la informacion
        processButton = Button(raiz, text="Hallar orden",
            command = leer_datos_boton)
        processButton.place(x = 0, y = 350)

        quitButton = Button(self, text="Salir",
            command=self.quit)
        quitButton.place(x=300, y=350)
Esempio n. 23
0
    def __init__(self, fra, csvFile, csvDelimiter=',', renew=False):
        self.fra = fra
        self.csvFile = csvFile
        self.csvDelimiter = csvDelimiter
        self.renew = renew
        s = Style()
        s.theme_use('clam')
        def_font = font.nametofont('TkDefaultFont')
        font_family = def_font.actual()['family']
        font_size = def_font.actual()['size'] + 3
        s.configure('font.Treeview.Heading',
                    font=(font_family, font_size, 'bold'))
        fact = font.Font(font="TkDefaultFont").metrics('linespace')
        s.configure('font.Treeview',
                    rowheight=fact,
                    font=font.nametofont("TkDefaultFont"))
        self.treeColumns = []
        self.treeData = []
        if renew:
            del self.treeColumns[:]
            del self.treeData[:]

        with open(self.csvFile, newline='', encoding='utf-8-sig') as csvfile:
            treeCsv = csv.reader(csvfile, delimiter=csvDelimiter)

            for ix, row in enumerate(treeCsv):
                if ix == 0:
                    self.treeColumns = row
                else:
                    self.treeData.append(row)

        self.build_tree()
Esempio n. 24
0
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.info = {}
        self.window = None
        self.size = (640, 480)
        self.fields = []
        self.init_ui()

    def init_ui(self):
        self.parent.title("Node Writer")
        self.style = Style()
        self.style.theme_use("alt")
        self.pack(fill="both", expand=True)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        menubar.add_command(label="New", command=self.onNew)
        menubar.add_command(label="Show Info", command=self.get_info)
        menubar.add_command(label="Exit", command=self.quit)

        self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1])
        self.canvas.pack(fill="both", expand=1)
        self.canvas.bind("<Motion>", self.move_boxes)

    def move_boxes(self, event):
        print(event.x, event.y)
        """
        x, y = (event.x-1, event.y-1)
        x1, y1, x2, y2 = self.canvas.bbox("test")
        if x > x1 and y > y1 and x < x2 and y < y2:
            print("Hit")
        else:
            print("Missed")
        """

    def onNew(self):
        new = Node(self, "Node_entry")
        label = new.insert_entry_field("Labels")
        label2 = new.insert_entry_field("Labels2")
        text = new.insert_text_field("Text")
        new.ok_cancel_buttons()

    def get_info(self):
        x, y = (self.size[0]/2, self.size[1]/2)
        for i in self.info:
            label_frame= LabelFrame(self, text="name")
            label_frame.pack(fill="y")
            for entry in self.info[i]["Entry"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
            for text in self.info[i]["Text"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Text"][text], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
        window = self.canvas.create_window(x, y, window=label_frame, tag="test")
Esempio n. 25
0
class Example(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.master.title("Quit Button Application")
        self.pack(fill=BOTH, expand=1)
        self.centreWindow()
        self.quitButton()

    def centreWindow(self):

        width = 200
        height = 180

        sw = self.master.winfo_screenwidth()
        sh = self.master.winfo_screenheight()

        x = (sw - width) / 2
        y = (sh - height) / 2

        self.master.geometry('%dx%d+%d+%d' % (width, height, x, y))

    def quitButton(self):

        self.style = Style()
        self.style.theme_use("default")

        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=50, y=50)

    def quit(self):
        print("Quit Button Clicked!!!")
        sys.exit(1)
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.master.title("Recognition of a traffic situation in real-time")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame(self, relief=RAISED, borderwidth=3)
        frame.pack(fill=BOTH, expand=True)
        bard = Image.open("traffic.jpg")
        bardejov = ImageTk.PhotoImage(bard)
        label1 = Label(self, image=bardejov, borderwidth=3)
        label1.image = bardejov
        label1.place(x=0, y=0)

        self.pack(fill=BOTH, expand=True)

        closeButton = Button(self, text="Close", command=close_window)
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="Select file", command=Object_detect)
        okButton.pack(side=RIGHT)
Esempio n. 27
0
class MainWindow(Frame):
    """
    Macro class for the main program window
    """
    def __init__(self, parent):

        Frame.__init__(self, parent)

        self.parent = parent
        self.parent.title('PyNBTx %s' % __version__)

        self.style = Style()
        self.style.theme_use('default')
        self.style.configure('TButton', padding=0)

        self.pack(fill=BOTH, expand=1)

        self.menu = MainMenu(root)
        self.toolbar = ToolBar(self)
        self.tree = Treeview(self, height=20)
        self.tree_display = TreeDisplay(self.tree)

        self.ui_init()

    def ui_init(self):
        root['menu'] = self.menu
        self.toolbar.pack(anchor=NW, padx=4, pady=4)
        self.tree.column('#0', width=300)
        self.tree.pack(fill=BOTH, anchor=NW, padx=4, pady=4)
Esempio n. 28
0
def styling(root):
    # tell tcl where to find the awthemes packages
    root.tk.eval("""
    set base_theme_dir awthemes/

    package ifneeded awthemes 10.2.1 \
        [list source [file join $base_theme_dir awthemes.tcl]]
    package ifneeded colorutils 4.8 \
        [list source [file join $base_theme_dir colorutils.tcl]]
    package ifneeded awdark 7.11 \
        [list source [file join $base_theme_dir awdark.tcl]]   
    
    """)

    # remove maximize/mininize button
    root.resizable(0,0)

    # load the awdark and awlight themes
    root.tk.call("package", "require", 'awdark')
    # Initialising Style and loading in a dark thene
    style = Style()
    style.theme_use('awdark')

    #configure buttons
    style.configure("TButton", padding=6, relief="flat", font=menu_font)

    # button active/hover tweaks
    style.map("C.TButton",
    foreground=[('pressed', 'black'), ('active', 'black')],
    background=[('pressed', '!disabled', 'gray'), ('active', 'gray')]
    )
Esempio n. 29
0
 def create_frame(self):
     frame_style = Style()
     frame_style.theme_use('alt')
     frame_style.configure("TFrame", relief='raised')
     self.frame = Frame(self.window, style="frame_style.TFrame")
     self.frame.rowconfigure(1)
     self.frame.columnconfigure(1)
     self.frame.grid(row=0, column=0)
Esempio n. 30
0
def main():
    root = tk.Tk()
    style = Style()
    style.theme_use("classic")
    root.geometry("840x720+300+0")

    GUI.instance(root, "FACE RECOGNITION")
    root.mainloop()
Esempio n. 31
0
    def pressButton(self):
        link = self.entry.get()
        try:
            res = urllib2.urlopen(link)
            html = res.read().decode("iso-8859-1")
            soup = BeautifulSoup(html)
            tag = soup.find(
                'meta', property='og:video'
            )  #soup.body.find('meta', attrs={'property' : 'og:video:url'}).text
            vid_url = tag['content']
            file_name = vid_url.split('/')[-1].split('?')[
                0]  #vid_url[vid_url.rfind("/")+1:]

            s = Style()
            s.theme_use("classic")
            s.configure("green.Horizontal.TProgressbar",
                        foreground='green',
                        background='green')
            self.progress = Progressbar(self.main,
                                        style="green.Horizontal.TProgressbar",
                                        orient=HORIZONTAL,
                                        length=100,
                                        mode='determinate')
            self.progress.pack(pady=10)

            nhandler = urllib2.urlopen(vid_url)
            vid_file = open(file_name, 'wb')
            meta = nhandler.info()
            filesize = int(meta.getheaders("Content-Length")[0])
            filesizedown = 0
            blocksize = 10000
            self.message = Label(w,
                                 text='Download: %d / %d' %
                                 (filesizedown, filesize),
                                 font='Helvetica -13 bold',
                                 fg='#fcfcfc',
                                 bg='#3b5998')
            self.message.pack(padx=10, pady=10)
            while True:
                buffer = nhandler.read(blocksize)
                if not buffer:
                    break
                filesizedown += len(buffer)
                vid_file.write(buffer)
                percent = filesizedown * 100. / filesize
                self.progress['value'] = percent
                self.main.update_idletasks()
                self.message['text'] = 'Download: %d / %d' % (filesizedown,
                                                              filesize)
            self.message['text'] = 'Download Completed'
            self.message['fg'] = '#ccffcc'
        except Exception, e:
            self.label = Label(w,
                               text="Error: %s" % (e),
                               font='Helvetica -13 bold',
                               fg='#fcfcfc',
                               bg='#3b5998')
            self.label.pack()
Esempio n. 32
0
    def __init__(self, darkmode=True):
        self._darkMode = darkmode

        if self.isDark():
            s = Style()
            s.theme_settings("default", dark_theme())
            s.theme_use("default")
        else:
            raise NotImplementedError("Light mode is not supported")
Esempio n. 33
0
 def create_frame(self):
     frame_style = Style()
     frame_style.theme_use('alt')
     frame_style.configure("TFrame",
                           relief='raised')
     self.frame = Frame(self.window, style="frame_style.TFrame")
     self.frame.rowconfigure(1)
     self.frame.columnconfigure(1)
     self.frame.grid(row=0, column=0)
Esempio n. 34
0
 def __init__(self):
     self.stages = {}
     self.root = Tk()
     s = Style()
     s.theme_use("default")
     s.configure("TProgressbar",
                 thickness=25,
                 background="#5169ff",
                 pady=20,
                 padx=10)
Esempio n. 35
0
class poly_pocket(Frame):
    def __init__(self):
        window = Tk()
        self.parent = window
        window.geometry("800x600+50+50")
        Frame.__init__(self, window)
        self.baseline = 0
        self.initUI()
        window.mainloop()
    def initUI(self):
        # Initialize and name Window
        self.parent.title("Poly Pocket")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        def new_baseline():

            return
        def old_baseline():
            return
        def test(baseline):
            return
        def spark_connect():
            return
        def leap_connect():
            return
        def quit():
            self.parent.destroy()
            return

        welcome = "Welcome to Poly Pocket!"
        welcome_label = Label(self, text=welcome, font=("Helvetica", 24))
        welcome_label.place(x=5, y=5)
        welcome_label.pack()
        
        baseline_button = Button(self, text="New Baseline",
                command=new_baseline())
        recover_baseline_button = Button(self, text="Recover Baseline",
                command=old_baseline())
        test_button = Button(self, text="Conduct Test",
                command=test(self.baseline))
        connect_leap_button = Button(self, text="Establish Leap Connection",
                command=leap_connect)
        connect_spark_button = Button(self, text="Establish Spark Connection",
                command=spark_connect)
        exit_button = Button(self, text="Quit",
                command=quit)
        
        baseline_button.place(relx=0.5, rely=0.3, anchor=CENTER)
        recover_baseline_button.place(relx=0.5, rely=0.4, anchor=CENTER)
        test_button.place(relx=0.5, rely=0.5, anchor=CENTER)
        connect_leap_button.place(relx=0.5, rely=0.6, anchor=CENTER)
        connect_spark_button.place(relx=0.5, rely=0.7, anchor=CENTER)
        exit_button.place(relx=0.5, rely = 0.8, anchor=CENTER)
Esempio n. 36
0
class ChernobylStation(Frame):

    def __init__(self):
        super().__init__()

        self.frameMain = Frame(self, relief=RAISED, borderwidth=1)
        self.style = Style()

        self.valikko = ttk.Combobox(self.frameMain, values=list(sanakirja.keys()))
        self.label = tk.Label(self.frameMain, text="Select date from the drop down menu")
        self.closeButton = Button(self, text="Close", command=self.quit)
        self.searchButton = Button(self.frameMain, text="Search", command=lambda: self.plot())

        self.initUI()

    def plot(self):
        self.label.configure(text=self.valikko.get())

    def initUI(self):
        self.master.title("Chernobyl Control Station 1")
        self.style.theme_use("default")
        self.frameMain.pack(fill=BOTH, expand=True)
        self.label.place(x=100, y=80)
        self.valikko.place(x=80, y=120)
        self.searchButton.place(x=240, y=120)
        self.pack(fill=BOTH, expand=True)
        self.closeButton.pack(side=RIGHT, padx=5, pady=5)

    def rawTemp(self):
        f = open(tempSensor, 'r')
        lines = f.readlines()
        f.close()
        return lines

    def readTemp(self):
        lines = self.rawTemp()
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = self.rawTemp()
        tempOutput = lines[1].find('t=')
        if tempOutput != -1:
            tempString = lines[1].strip()[tempOutput + 2:]
            tempC = float(tempString) / 1000.0
            tempF = tempC * 9.0 / 5.0 + 32.0

        # print("Temperature in Celcius: ",tempC)
        # print("Temperature in Fahrenheit: ", tempF)

        return tempC

    def getDate(self):
        return self.date()

    def getTime(self):
        return self.time()
Esempio n. 37
0
class Help:
    def __init__(self, parent):
        self.parent = parent

        self.style = Style()
        self.style.theme_use('clam')

        self.root = Toplevel()
        self.root.title('pyEdit - Help')
        self.root.resizable(False, False)
        self.root.minsize(200, 50)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        self.root.bind('<Expose>', lambda e: Utils.on_expose(self))
        self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self))

        self.text = self.get_content()

        self.font = font.Font(family='Monospace', size=10, weight='normal')

        self.font_spacing = None
        self.font_spacing = self.font.metrics('descent')

        self.text_widget = Text(self.root,
                                relief='flat',
                                bd=0,
                                font=self.font)
        self.text_widget.grid(column=0, row=0, sticky='nsew')
        self.text_widget.delete('1.0', 'end')
        self.text_widget.insert('1.0', self.text)
        self.text_widget.config(state='disabled')

        self.scrollbar = Scrollbar(self.root, bd=0, orient='vertical', command=self.text_widget.yview)
        self.scrollbar.grid(column=1, row=0, sticky='nsew')
        self.text_widget.config(yscrollcommand=self.scrollbar.set)

    def get_content(self):
        text = ''
        try:
            file = open(self.parent.current_dir + '/help.txt', 'r')
            file.seek(0, 2)
            size = file.tell()
            file.seek(0, 0)
            text = file.read(size)
            file.close()
        except IOError:
            print('IOError while reading help text.')

        return text
Esempio n. 38
0
class PwRd(Frame):
    def __init__(self,parent):
        Frame.__init__(self, parent,background="white")
        self.parent = parent
        self.initUI()
        
    def initUI(self):
        self.parent.title("Start")
        self.style=Style()
        self.style.theme_use("default")
        frame = Frame(self,relief=RAISED,borderwidth=1,background="white")
        frame.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        closeButton = Button(self, text="Close",command=self.quit)
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)
Esempio n. 39
0
def setup(tk_instance):
    """Sets up all the custom styles.

    Args:
        Toplevel Tk instance.
    """
    style = Style(tk_instance)
    style.theme_use('default')
    style.configure(GRID_FRAME, background='#888')
    style.configure(BOX_FRAME, background='white')
    style.configure(GIVEN_FRAME, background='#ddd')
    style.configure(NUMBER_LABEL, background='white', font='Helvetica 24')
    style.configure(GIVEN_LABEL, background='#ddd', font='Helvetica 24 bold')
    style.configure(PENCIL_LABEL, background='white', font='Helvetica 8')
    style.configure(GREEN, background='green')
    style.configure(RED, background='red')
    style.configure(YELLOW, background='yellow')
Esempio n. 40
0
class MM_Window(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")   
         
        self.parent = parent
        self.parent.title("Centered window")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()
        self.initUI()
        
    def initUI(self):
        self.parent.title("Quit button")
        self.style = Style()
        self.style.theme_use("default")

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

        quitButton = Button(self, text="Quit",
            command=self.quit)
        quitButton.place(x=200, y=50)
        buttons_list = []
        g=0
        c=0
        for i in range(1,52):
            crnt_button = Label(self, text=str(i),background=FF0000)
            crnt_button.grid(row=g, column=c)
            buttons_list.append(crnt_button)
            c += 1
            if i%10 ==0:
                g +=1
                c=0
    def centerWindow(self):
      
        w = 290
        h = 150

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
Esempio n. 41
0
class GPACalc(Frame):

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

    def onPressCalc():
        print("Hello world")

    def initUI(self):
        self.parent.title("GPA Calculator")
        self.style = Style()
        self.style.theme_use("default")

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

        calculateButton = Button(self, text="Calculate", command=lambda: self.onPressCalc)
        calculateButton.pack(side=RIGHT, padx=5, pady=5)
Esempio n. 42
0
class Example(Frame):

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

        self.parent = parent

        self.initUI()


    def initUI(self):

        self.parent.title("Windows")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

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

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

        area = Text(self)
        area.grid(row=1, column=0, columnspan=2, rowspan=4,
            padx=5, sticky=E+W+S+N)

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

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

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

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
Esempio n. 43
0
class Example(Frame):
    # subclase Frame, this is a container.
    def __init__(self, parent):
        # create frame within parent
        Frame.__init__(self, parent)
        # call superclass initializer
        self.parent = parent  # parent window
        self.initUI()

    def initUI(self):
        self.parent.title("Press OK when done")
        # Set root window title

        self.style = Style()
        self.style.theme_use("default")
        # styles are 'clam' 'default' 'alt' or 'classic', but so far seem the same

        frame = Frame(self, relief=RAISED, borderwidth=1)
        # border width of one means the effect is subtle; it really just
        # puts a line between the top section and the bottom buttons
        frame.pack(fill=BOTH, expand=1)
        # this frame has nothing, but pushes buttons down

        self.pack(fill=BOTH, expand=1)

        closeButton = Button(self, text="Close", command=self.quit)
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)
        self.pack(fill=BOTH, expand=1)
        # pack geometry manager with expand in both directions

    def center_main_window(self, width=290, height=150):
        screen_width = self.parent.winfo_screenwidth()
        screen_height = self.parent.winfo_screenheight()

        new_x = (screen_width - width) // 2
        new_y = (screen_height - height) // 2
        self.parent.geometry('{}x{}+{}+{}'.format(width, height, new_x, new_y))
Esempio n. 44
0
class directview(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)

		self.parent = parent

		self.initUI()

	def initUI(self):
		self.parent.title("Windows")
		self.style = Style()
		self.style.theme_use("default")
		self.pack(fill = BOTH, expand = 1)

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

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

		area = Text(self)
		area.grid(row = 1, column = 0, columnspan = 2, rowspan = 4,
			padx = 5, sticky = E + W + S + N)

		selectbtn = Button(self, text ="Select")
		selectbtn.grid(row = 1, column = 3, pady = 4)

		backbtn = Button(self, text ="<<")
		backbtn.grid(row = 2, column = 3)

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

		closebtn = Button(self, text = "Close")
		closebtn.grid(row = 5, column = 3)
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("default")
        
        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=1)
        
        self.pack(fill=BOTH, expand=1)
        
        closeButton = Button(self, text="Close")
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)
Esempio n. 46
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.files = ["file1", "file2"]
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Windows")
        self.style = Style()
        self.style.theme_use("default")
        self.pack()
        
        self.filelistpanel = self.createfilelistpanel(self)
        self.filelistpanel.grid(row=0, column=0, rowspan=4, columnspan=2, padx=5, pady=5, sticky=N)
        
        self.console = self.createconsole(self)
        self.console.grid(row=0, column=2, columnspan=4, rowspan=4, padx=5, sticky=E + W + S + N)
        
        newfilebtn = Button(self, text="New File", command=self.addfile)
        newfilebtn.grid(row=4, column=0, padx=5, pady=5)
        
        resbtn = Button(self, text="Get Result")
        resbtn.grid(row=4, column=1, padx=5, pady=5)
        
        
#         buttonpanel.add(resbtn)

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

#         obtn = Button(self, text="OK")
#         obtn.grid(row=5, column=0)

    def createconsole(self, parent):
        console = Text(parent)
        return console
        
    def createfilelistpanel(self, parent):
        panel = PanedWindow(parent, orient=VERTICAL)
        for file in self.files:
            panel.add(self.createfilepanel(panel, file))
        return panel
        
    def createfilepanel(self, parent, file):
        panel = PanedWindow(parent)
        
        filelabel = Label(panel, text="File: ")
        filelabel.grid(row=0, column=0, padx=5, pady=5)
        
        fileentry = Entry(panel)
        fileentry.insert(0, file)
        fileentry.grid(row=0, column=1, pady=5, columnspan=3)
        
        condbtn = Button(panel, text="Condition", command=lambda: self.setcondition(file))
        condbtn.grid(row=1, column=0, padx=5, pady=5)
        
        delbtn = Button(panel, text="Delete")
        delbtn.grid(row=1, column=1, pady=5)
        
        upbtn = Button(panel, text="Up")
        upbtn.grid(row=1, column=2, pady=5)
        
        downbtn = Button(panel, text="Down")
        downbtn.grid(row=1, column=3, pady=5)
        
        return panel
    
    def setcondition(self, file):
        pass
    
    def addfile(self):
        print("dd")
        newfile = "new-file"
        
        self.files.append(newfile)
        newfilepanel = self.createfilepanel(self.filelistpanel, newfile)
        
        self.filelistpanel.add(newfilepanel)
Esempio n. 47
0
class MainFrame(Frame): 
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent 

        self.music_root = ''
        self.query_path = ''
        self.extractor = Extractor(n_frames=40, 
                                   n_blocks=100, 
                                   learning_rate=0.00053,
                                   verbose=True)

        self.style = Style()
        self.style.theme_use("default")
        
        padx = 2
        pady = 2

        root_select_button = Button(self, text="Select a directory")
        root_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        root_select_button.bind("<Button-1>", self.set_music_root)

        analyze_button = Button(self, text="Analyze")
        analyze_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        analyze_button.bind("<Button-1>", self.analyze)

        query_select_button = Button(self, text="Select a file")
        query_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        query_select_button.bind("<Button-1>", self.set_query_path)

        search_button = Button(self, text="Search similar songs")
        search_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        search_button.bind("<Button-1>", self.search_music)
 
        self.pack(fill=BOTH, expand=1)

    def set_music_root(self, event):
        self.music_root = filedialog.askdirectory()

    def analyze(self, event):
        if(self.music_root == ''):
            #TODO show error dialog 
            print("Set a music directory first")
            return

        print("Analyzing")
        path_feature_map, error = self.extractor.extract(self.music_root)

        print("Saving")
        filename = os.path.basename(self.music_root)
        jsonpath = os.path.join(jsondir, '{}.json'.format(filename))

        dump_json(path_feature_map, jsonpath)

    def set_query_path(self, event):
        self.query_path = filedialog.askopenfilename(initialdir=self.music_root)

    def search_music(self, event):
        if(self.query_path == ''):
            #TODO show error dialog 
            print("Set a music file first")
            return
    
        k_nearest = search(self.query_path)

        music_list = MusicList(self)
        for path, vector in k_nearest:
            music_list.append(path)
Esempio n. 48
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")   
         
        self.parent = parent
        self.initUI()

        self.addButtons()
        self.addMainContent()
        
    
    def initUI(self):
      
        self.parent.title("Brain GUI")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()

        # style
        self.style = Style()
        self.style.theme_use("default")

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

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


    def centerWindow(self):
      
        w = 500
        h = 300

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def addButtons(self):
        anatomyButton = Button(self, text="Open Anatomy",
            command=self.openAnatomy)
        anatomyButton.grid(row=0, column=0)

        boldButton = Button(self, text="Open Bold",
            command=self.openBold)
        boldButton.grid(row=1, column=0)

        quitButton = Button(self, text="Quit",
            command=self.quit)
        quitButton.grid(row=2, column=0)

    def addMainContent(self):
        anatomy_label = Label(self, text="Anatomy")
        anatomy_label.grid(row=0, column=1)

        bold_labal = Label(self, text="BOLD")
        bold_labal.grid(row=1, column=1)


    def onOpen(self, types):
      
        ftypes = types
        dlg = filedialog.Open(self, filetypes = ftypes)
        fl = dlg.show()
        
        if fl != '':
            return fl

    def openAnatomy(self):
        file = self.onOpen([('NIFTI files', '*.nii.gz'), ('All files', '*')])
        print("anatomy file: " + file)
        plotting.plot_anat(file, title='Anatomy')
        plt.show()

    def openBold(self):
        file = self.onOpen([('NIFTI files', '*.nii.gz'), ('All files', '*')])
        print("anatomy file: " + file)

        bold = image.index_img(file, 0)

        plotting.plot_glass_brain(bold, title='glass_brain',
    black_bg=True, display_mode='ortho')
        plt.show()
Esempio n. 49
0
class MainFrame(Frame):

    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.parent.title("InstaDjango")

        self.pack(fill=BOTH, expand=1)
        self.size_and_center_window()

        self.style = Style()
        self.style.theme_use("clam")
        self.style.configure("TFrame", background="#808080", foreground="white")
        self.style.configure("TButton", background="#808080", foreground="white")
        self.style.configure("high.TButton", background="#8FBC8B", foreground="white")
        self.style.configure("TLabel", background="#808080", foreground="white")
        self.style.map("TButton", background=[("pressed", "#404040"), ("active", "#A0A0A0")])

        frame = Frame(self, relief=FLAT, borderwidth=1)
        frame.pack(fill=BOTH, expand=1)

        subframe_0 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_0.pack(fill=X)
        lbl_0 = Label(subframe_0, text="App's machine-readable name (used for naming folders locally and remotely):", style="TLabel")
        lbl_0.pack(fill=BOTH, padx=10, pady=10)
        entry_0 = Entry(subframe_0)
        entry_0.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_0, "")

        subframe_1 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_1.pack(fill=X)
        lbl_1 = Label(
            subframe_1, text="Where to create the app's folder locally:", style="TLabel")
        lbl_1.pack(fill=BOTH, padx=10, pady=10)
        entry_1 = Entry(subframe_1)

        def action_1():
            cdir = filedialog.askdirectory(title="Please select a directory")
            if cdir:
                self.set_entry_text(entry_1, cdir)

        button_1 = Button(subframe_1, text="Choose", command=action_1, style="TButton")
        button_1.pack(side=RIGHT, padx=10, pady=0)
        entry_1.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_1, "")

        subframe_2 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_2.pack(fill=X)
        lbl_2 = Label(subframe_2, text="Remote host:", style="TLabel")
        lbl_2.pack(fill=BOTH, padx=10, pady=10)
        entry_2 = Entry(subframe_2)
        entry_2.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_2, "")

        subframe_3 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_3.pack(fill=X)
        lbl_3 = Label(
            subframe_3, text="Remote SSH port (empty will mean the default port):", style="TLabel")
        lbl_3.pack(fill=BOTH, padx=10, pady=10)
        entry_3 = Entry(subframe_3)
        entry_3.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_3, "")

        subframe_4 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_4.pack(fill=X)
        lbl_4 = Label(subframe_4, text="Remote user:"******"TLabel")
        lbl_4.pack(fill=BOTH, padx=10, pady=10)
        entry_4 = Entry(subframe_4)
        entry_4.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_4, "")

        subframe_5 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_5.pack(fill=X)
        lbl_5 = Label(
            subframe_5, text="Local path to the SSH private key:", style="TLabel")
        lbl_5.pack(fill=BOTH, padx=10, pady=10)
        entry_5 = Entry(subframe_5)

        def action_5():
            cdir = filedialog.askopenfilename(title="Please select a private key")
            if cdir:
                self.set_entry_text(entry_5, cdir)

        button_5 = Button(subframe_5, text="Choose", command=action_5, style="TButton")
        button_5.pack(side=RIGHT, padx=10, pady=0)
        entry_5.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_5, "")

        subframe_6 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_6.pack(fill=X)
        lbl_6 = Label(
            subframe_6, text="Where to create the app's folder remotely (should not be owned by root):", style="TLabel")
        lbl_6.pack(fill=BOTH, padx=10, pady=10)
        entry_6 = Entry(subframe_6)
        entry_6.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_6, "/var/www")

        subframe_7 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_7.pack(fill=X)
        lbl_7 = Label(subframe_7, text="Sudo password:"******"TLabel")
        lbl_7.pack(fill=BOTH, padx=10, pady=10)
        entry_7 = Entry(subframe_7, show="*")
        entry_7.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_7, "")

        subframe_8 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_8.pack(fill=X)
        lbl_8 = Label(subframe_8, text="Database password:"******"TLabel")
        lbl_8.pack(fill=BOTH, padx=10, pady=10)
        entry_8 = Entry(subframe_8, show="*")
        entry_8.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_8, "")

        subframe_9 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_9.pack(fill=X)
        lbl_9 = Label(subframe_9, text="Domain:", style="TLabel")
        lbl_9.pack(fill=BOTH, padx=10, pady=10)
        entry_9 = Entry(subframe_9)
        entry_9.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_9, "dev.example.com")

        subframe_10 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_10.pack(fill=X)
        lbl_10 = Label(subframe_10, text="Django installation type (local, production, staging):", style="TLabel")
        lbl_10.pack(fill=BOTH, padx=10, pady=10)
        entry_10 = Entry(subframe_10)
        entry_10.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_10, "local")

        def go():
            setup_django_project(
                proj=entry_0.get(),
                proj_local_parent_dir=entry_1.get(),
                host=entry_2.get(),
                port=entry_3.get(),
                user=entry_4.get(),
                ssh_key=entry_5.get(),
                proj_remote_parent_dir=entry_6.get(),
                sudo_pass=entry_7.get(),
                db_pass=entry_8.get(),
                domain=entry_9.get(),
                insta_type=entry_10.get())
            self.quit()
        inst_button = Button(self, text="Go", command=go, style="high.TButton")
        inst_button.pack(side=RIGHT, padx=10, pady=10)

        quit_button = Button(self, text="Quit", command=self.quit, style="TButton")
        quit_button.pack(side=RIGHT, pady=10)

    def size_and_center_window(self):
        w = 640
        h = 850
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))

    @staticmethod
    def set_entry_text(e, text):
        e.delete(0, END)
        e.insert(0, text)
Esempio n. 50
0
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.window = None
        self.size = (4096, 2160)
        self.width = self.size[0]
        self.height = self.size[1]
        self.canvasi = []
        self.db = DataBase()
        self.init_ui()

    def init_ui(self):
        self.parent.title("Node Writer")
        self.style = Style(self)                  # This doesn't seem to
        self.style.theme_use("alt")               # do anything in Windows.
        self.pack(fill="both", expand=True)

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

    def onNew(self):
        node = Node(self, numerate("Name"))
        node.insert_entry_field("Name", focus=True)
        node.ok_cancel_buttons()
        node.entries["Entry"]["Name"].bind("<Return>", lambda x : node.save())

    def save_info(self, name_id, entries, *args):
        if "Name" in name_id:
            name = "".join(entries["Entry"]["Name"])
            self.canvasi.append(Canv(self, name))
            self.canvas_switch(name)
            self.menubar.add_button("show", name, self.canvas_switch)

    def canvas_switch(self, name):
        for canv in self.canvasi:
            if name == canv.name:
                canv.pack(fill="both", expand=True)
                self.parent.title(canv.name)
            else:
                canv.pack_forget()

    def save(self):
        self.db = DataBase()
        for canv in self.canvasi:
            self.db.add_npc(canv.name)
            for stick in canv.stickies:
                node = {canv.stickies[stick].name:{"tags":[], "text":"", "links":{}, "coords":{}}}
                node[canv.stickies[stick].name]["tags"] = [field.get() for field in canv.stickies[stick].entries]
                node[canv.stickies[stick].name]["text"] = "".join([text.get("1.0", "end-1c") for text in canv.stickies[stick].text])
                node[canv.stickies[stick].name]["links"] = canv.stickies[stick].links
                node[canv.stickies[stick].name]["coords"] = canv.stickies[stick].pos
                self.db.add_node(canv.name, node)
        fname = filedialog.asksaveasfile(parent=self, mode='w', title='Choose a filename', initialdir="./data")
        self.db.save(fname.name)

    def load(self):
        fname = filedialog.askopenfile(parent=self, mode='rb', title='Choose a file', initialdir="./data")
        self.db.load(fname.name)
        for canvas in self.canvasi:
            self.menubar.remove_item(canvas.name)
            canvas.delete("all")
            canvas.destroy()
        self.canvasi = []
        for name in self.db.names:
            num = 0
            canv = Canv(self, name)
            self.canvasi.append(canv)
            self.canvas_switch(name)
            self.menubar.add_button("show", name, self.canvas_switch)
            for node in self.db.nodes[name]:
                cur = int(node[-1])
                if cur > num:
                    num = cur
                n = {}
                n[node] = {}
                n[node]["tags"] = self.db.tags[node].copy()
                n[node]["text"] = self.db.text[node]
                n[node]["coords"] = self.db.coords[node]
                n[node]["links"] = self.db.links[node].copy()
                canv.insert_sticker(node, n)
            for i in range(num):
                noname = numerate("Node")
            for sticky in canv.stickies:
                for other in canv.stickies[sticky].links:
                    canv.stickies[sticky].connect2box(other, True)

    def save_image(self):
        for num, canv in enumerate(self.canvasi):
            x1, y1, x2, y2 = canv.bbox("all")
            canv.postscript(file="filetest{}.ps".format(num), colormode='color', x=x1-25, y=y1-25, width=x2+25, height=y2+25)
            print("Writing filetest{}.ps...".format(num))


    # Test function, to be removed.
    def get_info(self):
        for canv in self.canvasi:
            ca_dict = canv.config()
            print("{}{}".format(ca_dict["height"], ca_dict["width"]))
Esempio n. 51
0
class GUITournament(Frame):

    poeng = {"vinner": 1, "taper": 0, "uavgjort": 0.5}

    def __init__(self, parent, motspiller):
        Frame.__init__(self, parent)
        self.parent = parent
        self.spiller = motspiller
        self.resultat = []
        self.resultat_label = StringVar()
        self.resultat_label.set("Beskrivelse av siste spill kommer her")
        self.style = Style()
        self.fig = None

    def setup_gui(self):
        self.parent.title("Stein - Saks - Papir")
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        # Label for rapportering
        label = Label(self.parent, textvariable=self.resultat_label)
        label.place(x=800, y=50)
        # Buttons
        # Disse fyrer av metoden self.arranger_enkeltspill som er
        # definert i klassen. Denne metoden tar aksjonen til mennesket
        # som startup, og gjennomfoerer spillet
        # Samme type oppfoersel for de tre aksjons-knappene
        rock_button = Button(self, text="Stein",
                             command=lambda: self.arranger_enkeltspill(Aksjon("Stein")))
        rock_button.place(x=800, y=400)
        scissors_button = Button(self, text="Saks",
                                 command=lambda: self.arranger_enkeltspill(Aksjon("Saks")))
        scissors_button.place(x=900, y=400)
        paper_button = Button(self, text="Papir",
                              command=lambda: self.arranger_enkeltspill(Aksjon("Papir")))
        paper_button.place(x=1000, y=400)
        # quit_button avslutter GUI'et naar den trykkes
        quit_button = Button(self, text="Quit", command=self.quit)
        quit_button.place(x=1000, y=450)
        # Embedde en graf i vinduet for aa rapportere fortloepende score
        self.fig = FigureCanvasTkAgg(pylab.figure(), master=self)
        self.fig.get_tk_widget().grid(column=0, row=0)
        self.fig.show()

    def arranger_enkeltspill(self, bruker_aksjon):
        bruker_navn = "Bruker"

        ai_aksjon = self.spiller.velg_aksjon()
        ai_aksjonliste = {"you": ai_aksjon, "enemy": bruker_aksjon}

        if ai_aksjon > bruker_aksjon:
            self.spiller.motta_resultat(ai_aksjonliste, self.poeng["vinner"])
            self.resultat.append(self.poeng["taper"])

            self.resultat_label.set("{spiller1}: {aksjon1} {spiller2}: {aksjon2} -> {spiller1} vant".format(
                spiller1=self.spiller.oppgi_navn(),
                spiller2=bruker_navn,
                aksjon1=str(ai_aksjon),
                aksjon2=str(bruker_aksjon),
            ))

        elif bruker_aksjon > ai_aksjon:
            self.spiller.motta_resultat(ai_aksjonliste, self.poeng["taper"])
            self.resultat.append(self.poeng["vinner"])

            self.resultat_label.set("{spiller1}: {aksjon1} {spiller2}: {aksjon2} -> {spiller2} vant".format(
                spiller1=self.spiller.oppgi_navn(),
                spiller2=bruker_navn,
                aksjon1=str(ai_aksjon),
                aksjon2=str(bruker_aksjon),
            ))

        else:
            self.spiller.motta_resultat(ai_aksjonliste, self.poeng["uavgjort"])
            self.resultat.append(self.poeng["uavgjort"])

            self.resultat_label.set("{spiller1}: {aksjon1} {spiller2}: {aksjon2} -> Uavgjort".format(
                spiller1=self.spiller.oppgi_navn(),
                spiller2=bruker_navn,
                aksjon1=str(ai_aksjon),
                aksjon2=str(bruker_aksjon),
            ))

        plt.figure(self.fig.figure.number)  # Handle til figuren
        plt.ion()
        plt.plot(range(1, len(self.resultat) + 1), 100 * cumsum(self.resultat) / range(1, len(self.resultat) + 1), 'b-', lw=4)
        plt.ylim([0, 100])
        plt.xlim([1, max(1.1, len(self.resultat))])
        plt.plot(plt.xlim(), [50, 50], 'k--', lw=2)
        plt.grid(b=True, which='both', color='0.65', linestyle='-')
        self.fig.show()
Esempio n. 52
0
class Application(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)

        #========================================================================
        # Fast Fourier Transform
        self.processor = FFTVoiceAnalyzer(path_to_examples, np.fft.fft, WavFile(path_to_silence))
        # Fast Fourier Transform
        #========================================================================

        #========================================================================
        # Naive Bayes Classifier
        self.nbc = NBC()
        self.nbc.initialize()
        # Naive Bayes Classifier
        #========================================================================

        #========================================================================
        # SPro 5 (MFCC classifierd)
        self.s = SPro5()
        self.s.learn()
        # SPro 5 (MFCC classifierd)
        #========================================================================

        #get general properties
        self.title = cf.get("general", "title")
        self.author = cf.get("general", "author")
        self.link_color = cf.get("general", "link_color")
        self.link_cursor = cf.get("general", "link_cursor")
        self.font_family = cf.get("general", "font_family")
        self.author_email = cf.get("general", "author_email")
        self.copyright_year = cf.get("general", "copyright_year")
        self.author_google_plus = cf.get("general", "author_google_plus")
        self.license_agree_link = cf.get("general", "license_agree_link")
        #get general properties

        #get program properties
        self.min_audio_time = int(cf.get("program", "min_audio_time"))
        self.max_audio_time = int(cf.get("program", "max_audio_time"))
        self.default_audio_time = int(cf.get("program", "default_audio_time"))
        self.min_test_audio_time = int(cf.get("program", "min_test_audio_time"))
        self.max_test_audio_time = int(cf.get("program", "max_test_audio_time"))
        self.default_test_audio_time = int(cf.get("program", "default_test_audio_time"))
        #get program properties

        self.root = root
        self.root.title(self.title)
        self.root.resizable(FALSE, FALSE)
        self.root.protocol("WM_DELETE_WINDOW", self.close)
        root.wm_iconbitmap(bitmap=cf.get("main_window", "icon_file"))

        self.top_frame = None
        self.main_frame = None
        self.bottom_frame = None

        self.init_ui()
        self.pack()

    def init_ui(self):
        """
        initialize all GUI
        """
        self.style = Style()
        self.style.theme_use('default')

        self.init_menu()
        self.init_top_frame()

        self.main_frame = Frame(self, relief=SUNKEN)
        self.make_main_frame()

        self.init_bottom_frame()

    def init_menu(self):
        """
        initialize menu (now menu has only 'About' element)
        """
        menu_bar = Menu(self.root)
        help_menu = Menu(menu_bar, tearoff=0)
        help_menu.add_command(label="About", command=self.about)
        menu_bar.add_cascade(label="Help", menu=help_menu)
        self.root.config(menu=menu_bar)

    def about(self):
        """
        makes simple GUI of About window
        """
        window = "about_window"
        ok_hover_bg = cf.get(window, "ok_hover_bg")
        ok_default_bg = cf.get(window, "ok_default_bg")
        font = Font(family=self.font_family, size=10)

        #main frame
        top = Toplevel(self)
        top.resizable(FALSE, FALSE)
        top.title("About " + self.title)
        top.wm_iconbitmap(bitmap=cf.get(window, "icon_file"))

        #info frame in main frame
        frame = Frame(top, relief=SUNKEN, bg="white", borderwidth=1)

        Label(frame, text="Voice Analyzer. Simple program for speech recognition, created for qualification work",
              bg="white", font=font).pack(padx=5, pady=5)
        Label(frame, text="Copyright " + self.copyright_year + ". GNU License. All rights reserved.",
              bg="white", font=font).pack(padx=5, pady=5)

        #author
        link_info = Message(frame, text="Author: " + self.author, bg="white", font=font, width=250)
        link_info.pack(side=LEFT, anchor=E, padx=5, pady=5)

        #link to author page (somewhere)
        link = Label(frame, text="Google Plus", bg="white", fg=self.link_color, font=font, cursor=self.link_cursor)
        link.bind("<Button-1>", lambda x: webbrowser.open_new_tab(self.author_google_plus))
        link.pack(side=LEFT, anchor=S, pady=5)
        frame.pack()

        #OK button in main frame
        button = Button(top, text="OK", command=top.destroy, width=10, bg=ok_default_bg, borderwidth=1)
        button.bind("<Enter>", lambda event, h=button: self.change_bg(h, ok_hover_bg))
        button.bind("<Leave>", lambda event, h=button: self.change_bg(h, ok_default_bg))
        button.pack(side=RIGHT, anchor=S, padx=5, pady=5)

    @staticmethod
    def change_bg(item, new_bg):
        item.configure(bg=new_bg)
        item.pack()

    @staticmethod
    def clear_frame(frame):
        for child in frame.winfo_children():
            child.destroy()

    #==================================================================================================================
    #========================================================================
    # Record Audio
    def record_audio(self, time, path=path_to_records):
        """
        record audio data to file
        @param time: length of file in sec
        """
        file_name = filedialog.asksaveasfilename(filetypes=[("Wave audio files", "*.wav *.wave")],
                                                 defaultextension=".wav", initialdir=path)
        if len(file_name) == 0:
            messagebox.showwarning("Warning", "You must input name of new file, and save it!")
            return None
        else:
            wav = self.processor.recorder.record_audio_to_file_and_get_wav(time=time, file_name=file_name)
            messagebox.showinfo("File Saved", "Audio has recorded.")
            return wav

    def record_test_audio(self, time):
        """
        records audio from microphone and uses this audio for analyzing
        @param time: length of test file
        """
        if time.get() == 0:
            time.set(self.default_test_audio_time)
        return self.processor.recorder.record_and_get_wav(time.get())
    # Record Audio
    #========================================================================

    #========================================================================
    # Fast Fourier Transform Voice Analyzer
    def fft_analyzer_record_to_lib(self, time):
        """
        records short audio file (file example with some word)
        and adds it to library
        @param time: length of test file
        """
        if time.get() == 0:
            time.set(self.default_audio_time)
        wav = self.record_audio(time.get())
        self.processor.lib.create_and_add_item_from_wave(wav)

    def fft_analyzer_record(self, time):
        if time.get() == 0:
            time.set(self.default_audio_time)

        wav = self.record_test_audio(time)
        if not wav is None:
            result_str = FFTVoiceAnalyzer.analyze(wav, self.processor)
            messagebox.showinfo("Result", result_str)
            if show_plots:
                plot = Plotter("DRA")
                plot.add_sub_plot_data("Digitized Recorded Audio", wav.get_one_channel_data(), x_label="Samples",
                                       y_label="Amplitude")
                plot.sub_plot_all_horizontal(show=False, save=True)

    def fft_analyzer_select(self, path=path_to_test):
        askopenfile = filedialog.askopenfile(filetypes=[("Wave audio files", "*.wav *.wave")], defaultextension=".wav",
                                             initialdir=path)
        if not askopenfile is None:
            wav = WavFile(askopenfile.name)
            result_str = FFTVoiceAnalyzer.analyze(wav, self.processor)
            messagebox.showinfo("Result", result_str)
            if show_plots:
                plot = Plotter("DRA")
                plot.add_sub_plot_data("Digitized Recorded Audio", wav.get_one_channel_data(), x_label="Samples",
                                       y_label="Amplitude")
                plot.sub_plot_all_horizontal(show=False, save=True)
        else:
            messagebox.showwarning("Warning", "You should select one file. Please, try again")
    # Fast Fourier Transform Voice Analyzer
    #========================================================================

    #========================================================================
    # Naive Bayes Classifier
    def nbc_add_file_select(self, clazz, path=path_to_records):
        askopenfile = filedialog.askopenfile(filetypes=[("Wave audio files", "*.wav *.wave")], defaultextension=".wav",
                                             initialdir=path)
        if not askopenfile is None:
            self.nbc.add_one_audio_file(clazz, path_to_file=askopenfile.name)
            self.nbc.teach_classifier()

    def nbc_classify_file_select(self, path=path_to_test):
        askopenfile = filedialog.askopenfile(filetypes=[("Wave audio files", "*.wav *.wave")], defaultextension=".wav",
                                             initialdir=path)
        if not askopenfile is None:
            print("Teaching NBC classifier with added examples")
            self.nbc.teach_classifier()
            print("Teaching NBC classifier finished")
            classes = self.nbc.get_classes(self.nbc.classify(WavFile(askopenfile.name)))
            mess = ""
            for i in classes.keys():
                for j in classes[i].keys():
                    mess += str(i) + ": " + str(j) + "\n"
            messagebox.showinfo("Classification results", mess)
        else:
            messagebox.showwarning("Warning", "You should select one file. Please, try again")
    # Naive Bayes Classifier
    #========================================================================

    #========================================================================
    # Voice Activity Detection
    def show_test_vad_open(self, path=path_to_test):
        askopenfile = filedialog.askopenfile(filetypes=[("Wave audio files", "*.wav *.wave")], defaultextension=".wav",
                                             initialdir=path)
        if not askopenfile is None:
            test(WavFile(askopenfile.name), self.nbc)
        else:
            messagebox.showwarning("Warning", "You should select one file. Please, try again")

    def show_test_vad_record(self, time):
        wav = self.record_test_audio(time)
        if not wav is None:
            test(wav, self.nbc)
            if show_plots:
                plot = Plotter("DRA")
                plot.add_sub_plot_data("Digitized Recorded Audio", wav.get_one_channel_data(), x_label="Samples",
                                       y_label="Amplitude")
                plot.sub_plot_all_horizontal(show=False, save=True)
    # Voice Activity Detection
    #========================================================================

    #========================================================================
    # MFCC
    def add_mfcc_file(self, file_type, path=path_to_mfcc):
        if not self.record_audio(5, path=path + "waves/" + file_type) is None:
            self.s.learn()

    def show_test_mfcc(self):
        print("Start MFCC")
        self.s.test()
        str_res = SPro5.get_results()
        messagebox.showinfo("Results MFCC", str_res)
        print("MFCC finished successful")
    # MFCC
    #========================================================================
    #==================================================================================================================

    def make_main_frame(self):
        """
        makes simple GUI of main window with 2 buttons record example file (Teach Program)
        and record test audio and analyze it (Record and Analyze Sound)
        """
        self.clear_frame(self.main_frame)

        #========================================================================
        # Record Audio
        Label(self.main_frame, text="Record Audio File",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, pady=5, padx=5)
        Button(self.main_frame, text="Record",
               command=lambda: self.make_record_frame(self.min_audio_time, self.max_audio_time,
                                                      self.record_audio), width=15).pack()
        # Record Audio
        #========================================================================

        #========================================================================
        # Fast Fourier Transform Voice Analyzer
        Label(self.main_frame, text="FFT Voice Analyzer",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, pady=5, padx=5)
        Button(self.main_frame, text="Record and Teach Program",
               command=lambda: self.make_record_frame(self.min_audio_time, self.max_audio_time,
                                                      self.fft_analyzer_record_to_lib), width=30).pack()
        Button(self.main_frame, text="Record and Analyze Sound",
               command=lambda: self.make_record_frame(self.min_test_audio_time, self.max_test_audio_time,
                                                      self.fft_analyzer_record),
               width=30).pack()
        Button(self.main_frame, text="Choose and Analyze Sound",
               command=lambda: self.fft_analyzer_select(), width=30).pack()
        # Fast Fourier Transform Voice Analyzer
        #========================================================================

        #========================================================================
        # Naive Bayes Classifier
        Label(self.main_frame, text="Naive Bayes Classifier",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, pady=5, padx=5)
        Button(self.main_frame, text="Add Speech File for NBC", command=lambda: self.nbc_add_file_select("speech"),
               width=30).pack()
        Button(self.main_frame, text="Add Non Speech File for NBC",
               command=lambda: self.nbc_add_file_select("non_speech"),
               width=30).pack()
        Button(self.main_frame, text="Choose and Classify File", command=lambda: self.nbc_classify_file_select(),
               width=30).pack()
        # Naive Bayes Classifier
        #========================================================================

        #========================================================================
        # Voice Activity Detection
        Label(self.main_frame, text="Voice Activity Detection",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, pady=5, padx=5)
        Button(self.main_frame, text="Record and Analyze",
               command=lambda: self.make_record_frame(self.min_audio_time, self.max_audio_time,
                                                      self.show_test_vad_record), width=30).pack()
        Button(self.main_frame, text="Choose and Analyze", command=lambda: self.show_test_vad_open(), width=30).pack()
        # Voice Activity Detection
        #========================================================================

        #========================================================================
        # SPro 5 (MFCC classifier)
        Label(self.main_frame, text="MFCC",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, pady=5, padx=5)
        Button(self.main_frame, text="Test", command=lambda: self.show_test_mfcc(), width=30).pack()
        Button(self.main_frame, text="Record Test File", command=lambda: self.add_mfcc_file("test"), width=30).pack()
        Button(self.main_frame, text="Record Learn File", command=lambda: self.add_mfcc_file("learn"), width=30).pack()
        # SPro 5 (MFCC classifier)
        #========================================================================

        self.main_frame.pack(side=TOP)

    def init_top_frame(self):
        """
        initialize head of main window
        """
        self.top_frame = Frame(self, relief=RIDGE, height=50, bg="white", borderwidth=1)
        Label(self.top_frame, text="Welcome to " + self.title, bg="white",
              font=Font(family=self.font_family, size=10, weight="bold")).pack(side=TOP, anchor=W, pady=5, padx=5)

        Label(self.top_frame, text="You can teach program or use default data", bg="white",
              font=Font(family=self.font_family, size=8)).pack(side=TOP, anchor=W, padx=10)

        self.top_frame.pack(side=TOP, fill=BOTH)

    def init_bottom_frame(self):
        """
        initialize footer of main window
        """
        self.bottom_frame = Frame(self, relief=GROOVE, height=50, borderwidth=1)
        Button(self.bottom_frame, text="Cancel", command=self.close, width=10).pack(side=RIGHT, padx=5, pady=5)

        font = Font(family=self.font_family, size=8)
        link = Label(self.bottom_frame, text="License Agreement:", fg=self.link_color, font=font,
                     cursor=self.link_cursor)
        link.bind("<Button-1>", lambda x: webbrowser.open_new_tab(self.license_agree_link))
        link.pack(side=LEFT, pady=5)
        text = Label(self.bottom_frame, text="By continuing, you agree to the term of the license agreement.",
                     font=font)
        text.pack(side=LEFT, pady=5)

        self.bottom_frame.pack(side=BOTTOM, fill=BOTH)

    def close(self):
        """
        close program dialog
        """
        answer = messagebox.askyesno(parent=self, message='Are you sure you want to close program?',
                                     icon='question', title='Close')
        if answer:
            self.root.destroy()

    def make_record_frame(self, min_time, max_time, record_function):
        """
        make simple GUI of record window
        @param min_time: minimum length of audio which will record
        @param max_time: maximum length of audio which will record
        @param record_function: command for record button (now: record example audio or test audio)
        """
        self.clear_frame(self.main_frame)
        time = IntVar(self.main_frame)
        Label(self.main_frame, text="Time:").pack(side=LEFT)
        Spinbox(self.main_frame, from_=min_time, to=max_time, textvariable=time).pack(side=LEFT)
        Button(self.main_frame, text="Record audio", command=lambda: record_function(time), width=20).pack(side=LEFT)
        Button(self.main_frame, text="Back", command=self.make_main_frame, width=20).pack(side=LEFT)
        self.main_frame.pack()
Esempio n. 53
0
class BookManagerGUI(Frame):
    def __init__(self, parent):
        self.man = manage_Book.MyDb('book.db') #DB에 접근하는 변수

        Frame.__init__(self, parent) #MAIN FRAME만들기
        self.parent = parent
        self.table_name = 'manager'
        self.conn = sqlite3.connect('book.db')
        self.cursor = self.conn.cursor()
        self.initUI()


    def initUI(self):
        self.parent.title("Windows")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

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

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

        self.area = Text(self) #WHITE TEXT BOX
        self.area.grid(row=1, column=0, columnspan=3, rowspan=4,
            padx=5, sticky=E+W+S+N)

        abtn = Button(self, text="add", command=self.press_add)
        abtn.grid(row=1, column=3)

        srcbtn = Button(self, text="search", command=self.press_search)
        srcbtn.grid(row=2, column=3, pady=3)

        rbtn = Button(self, text="remove", command=self.press_remove)
        rbtn.grid(row=3, column=3, pady=3)

        sbtn = Button(self, text="show all", command=self.press_show)
        sbtn.grid(row=4, column=3, pady=3)

    def create_new_frame(self, com): #CREATE SUB FRAME. TRIGGERED WHEN CLICKING BUTTONS ON MAIN FRAME.
        newFrame = Toplevel(self)
        newFrame.geometry('300x150')
        newFrame.wm_title('title')

        l = Label(newFrame, text='fill the blank : ')
        l.grid(sticky=W, pady=4, padx=5)
        Label(newFrame, text='name: ').grid(row=1)
        Label(newFrame, text='author: ').grid(row=2)
        Label(newFrame, text='price: ').grid(row=3)

        self.eName, self.eAuth, self.ePri, = Entry(newFrame), Entry(newFrame), Entry(newFrame)
        self.eName.grid(row=1, column=1)
        self.eAuth.grid(row=2, column=1)
        self.ePri.grid(row=3, column=1)

        okbtn = Button(newFrame, text="OK", command=com)
        okbtn.grid(row=4, column=0, pady=1)

        clsbtn = Button(newFrame, text="CLOSE", command=lambda: newFrame.destroy())
        clsbtn.grid(row=4, column=1, pady=1)

    def clear_entry(self): #sub frame에서 text entry를 공백으로 돌려주는 메소드
        self.eName.delete(0, 'end')
        self.eAuth.delete(0, 'end')
        self.ePri.delete(0, 'end')

    def press_add(self):
        self.create_new_frame(self.addDB)

    def press_search(self):
        self.create_new_frame(self.filter)

    def press_remove(self):
        self.create_new_frame(self.removeDB)

    def press_show(self): #main frame에서 show_all button클릭하면 실행
        self.area.delete(1.0, END) #원래의 text area를 공백으로 초기화
        lst = self.man.get_all_qr() #모든 쿼리(tuple타입)를 불러와 리스트에 저장
        for tup in lst:
            self.area.insert(INSERT, '{0}\n'.format(' '.join([str(i) for i in tup])))

    def addDB(self): #main frame의 add btn -> sub frame의 ok btn 순으로 클릭되면 실행. 중복되는 책이 있더라도 add해줌
        if '' in (self.eName.get(), self.eAuth.get(), self.ePri.get()):
            #name, author, price칸이 하나라도 비어있으면 경고
            messagebox.showinfo('warning', 'please fill all of the field')
            return;

        lst=[ { 'name': self.eName.get(), 'author': self.eAuth.get(), 'price':int(self.ePri.get()) } ]
        self.man.add_qr(lst)
        self.clear_entry()

    def filter(self): #main frame의 search btn -> sub frame의 ok btn 순으로 클릭되면 실행. filter는 book name으로만 했음
        if '' is self.eName.get(): #name칸이 비어있으면 경고
            messagebox.showinfo('warning', 'please fill the field : name')
            return self.press_search()

        self.area.delete(1.0, END)
        lst = self.man.get_filtered_qr(self.eName.get()) #필터된 리스트를 받아옴
        for tup in lst:
            self.area.insert(INSERT, '{0}\n'.format(' '.join([str(i) for i in tup])))
        self.clear_entry()

    def removeDB(self): #main frame의 remove btn -> sub frame의 ok btn 순으로 클릭되면 실행. book name과 author이 일치하면 제거
        if '' in (self.eName.get(), self.eAuth.get()):
            messagebox.showinfo('warning', 'please fill field : name and author')
            return self.press_remove()

        self.man.del_qr(self.eName.get(), self.eAuth.get())
        self.clear_entry()
Esempio n. 54
0
class GUITournament(Frame):
    # Klassen GUITournament definerer en turnering mellom menneske
    # og en Spiller
    spiller = None
    # Resultater holder resultatet av kampene - for plotting
    resultater = None
    # Denne labelen vil brukes for aa rapportere enkeltspill
    resultat_label = None
    history = []

    def __init__(self, parent, motspiller):
        Frame.__init__(self, parent)
        self.parent = parent
        # Huske hvem vi spiller mot
        self.spiller = motspiller
        # Initiere listen av resultater
        self.resultater = []
        # Foreloepig ikke noe aa rapportere
        self.resultat_label = StringVar()
        self.resultat_label.set("Beskrivelse av siste spill kommer her")
        self.style = Style()
        self.fig = None
        self.history = []


    def arranger_enkeltspill(self, a):
        s1 = self.spiller.pick_action(self.history)
        if (s1 == a):
            lab = ("Draw, both played " + s1.getAction())
            self.resultater.append(0.5)
        elif (s1.win(a)):
            lab = ("Computer wins, played " + s1.getAction() + " against " + a.getAction())
            self.resultater.append(0)

        else:

            lab = ("Player wins, played " + a.getAction() + " against " + s1.getAction())
            self.resultater.append(1)
        self.history.append(a.getAction())
        lab += "\nScore against is " + str(sum(self.resultater)/len(self.resultater)*100) + "%"

        self.resultat_label.set(lab)


        plt.figure(self.fig.figure.number)  # Handle til figuren
        plt.ion()
        plt.plot(range(1, len(self.resultater) + 1),
                 100 * numpy.cumsum(self.resultater) /
                 range(1, len(self.resultater) + 1), 'b-', lw=4)
        plt.ylim([0, 100])
        plt.xlim([1, max(1.1, len(self.resultater))])
        plt.plot(plt.xlim(), [50, 50], 'k--', lw=2)
        plt.grid(b=True, which='both', color='0.65', linestyle='-')
        self.fig.show()

    def setup_gui(self):
        self.parent.title("Stein - Saks - Papir")
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        # Label for rapportering
        label = Label(self.parent, textvariable=self.resultat_label)
        label.place(x=800, y=50)
        # Buttons
        # Disse fyrer av metoden self.arranger_enkeltspill som er
        # definert i klassen. Denne metoden tar aksjonen til mennesket
        # som startup, og gjennomfoerer spillet
        # Samme type oppfoersel for de tre aksjons-knappene
        rock_button = Button(self, text="Stein",
                             command=lambda: self.arranger_enkeltspill(Action("rock")))
        rock_button.place(x=800, y=400)
        scissors_button = Button(self, text="Saks",
                                 command=lambda: self.arranger_enkeltspill(Action("scissor")))
        scissors_button.place(x=900, y=400)
        paper_button = Button(self, text="Papir",
                              command=lambda: self.arranger_enkeltspill(Action("paper")))
        paper_button.place(x=1000, y=400)
        # quit_button avslutter GUI'et naar den trykkes
        quit_button = Button(self, text="Quit", command=self.quit)
        quit_button.place(x=1000, y=450)
        # Embedde en graf i vinduet for aa rapportere fortloepende score
        self.fig = FigureCanvasTkAgg(pylab.figure(), master=self)
        self.fig.get_tk_widget().grid(column=0, row=0)
        self.fig.show()
Esempio n. 55
0
	def init_style( self ):
		""" Initializes style for the window """
		self.dir['root'].title('Lilac Modeling Suite')
		self.dir['canvas'].update_idletasks()
		style = Style()
		style.theme_use('clam')
Esempio n. 56
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("")
        self.style = Style()
        self.style.theme_use("clam")
        self.pack(fill=BOTH, expand = 1)

        self.labelU = Label(self, text="U:")
        self.labelP = Label(self, text="P:")
        
        self.entryUsername = Entry(self)
        self.entryUsername.config(relief='flat')
        self.entryUsername.focus_set()
        self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set())

        self.entryPassword = Entry(self)
        self.entryPassword.config(relief='flat', show='•')
        self.entryPassword.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))

        self.newbutton = Button(self, text="Login", command= lambda: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.config(width=6)
        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())
        self.quitbutton.config(width=6)
        
        self.mailIconRed = PhotoImage(file="mail.gif")
        self.labelRed = Label(self, image=self.mailIconRed)
        self.mailIconGray = PhotoImage(file="mail2.gif")
        self.labelGray = Label(self, image=self.mailIconGray)
        self.labelKarma = Label(self, text = '•')

        self.labelU.grid(row=0, column=0)
        self.entryUsername.grid(row=0, column=1)
        self.labelP.grid(row=1, column=0)
        self.entryPassword.grid(row=1, column=1, pady=4)
        self.newbutton.grid(row=2, column=1)
        self.quitbutton.grid(row=3, column=1, pady=4)
        

        '''
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        w=150
        h=112
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50))
        '''


    def login(self, username, password):
        #print('U: ' + username)
        self.username = username
        if username == '':
            #print('Please enter a username')
            self.entryUsername.focus_set()
        elif password == '':
            #print('Please enter a password')
            self.entryPassword.set_focus()
            
        if username != '' and password != '':
            #print('Attempting login for ' + username)
            try:
                self.USERAGENT = username + ' scans his inbox for new mail.'
                self.r = praw.Reddit(self.USERAGENT)
                #self.r.config._ssl_url = None
                self.r.login(username, password)
                #print('You have logged in as ' + username)
                self.labelU.grid_forget()
                self.labelP.grid_forget()
                self.entryUsername.grid_forget()
                self.entryPassword.grid_forget()
                self.newbutton.grid_forget()
                self.quitbutton.grid_forget()
                self.usernamelabel = Label(self, text=username)
                self.usernamelabel.grid(row=0, column=0, pady = 10, padx = 30)
                self.quitbutton.grid(row=1, column=0)
                self.labelKarma.grid(row = 3, column = 0)
                self.playedSound = 'false'
                self.loop()
            except praw.errors.InvalidUserPass:
                pass
                #print('Invalid username or password')

    def loop(self):
        while True:
            try:
                #print('Starting new search')
                hasmail = 'false'
                for msg in self.r.get_unread(limit=None):
                    hasmail = 'true'
                
                if hasmail == 'true':
                    #print("You've got mail!")
                    if self.playedSound == 'false':
                        winsound.PlaySound('pop.wav', winsound.SND_FILENAME)
                    self.playedSound = 'true'
                    self.labelGray.grid_forget()
                    self.labelRed.grid(row=2, column=0)
                if hasmail == 'false':
                    self.playedSound = 'false'
                    #print('No mail!')
                    self.labelRed.grid_forget()
                    self.labelGray.grid(row=2, column=0)
                self.user = self.r.get_redditor(self.username)
                lkarma = str(self.user.link_karma)
                ckarma = str(self.user.comment_karma)
                lkarma = self.karmaRound(lkarma)
                ckarma = self.karmaRound(ckarma)
                karmastring = lkarma + ' • ' + ckarma
                self.labelKarma.config(text = karmastring)
                time.sleep(10)
            except Exception:
                time.sleep(10)


    def karmaRound(self, karma):
        if len(karma) > 4 and len(karma) < 7:
            tstring = karma[:-3]
            tstring2 = karma[-3:]
            karma = tstring + '.' + tstring2[:2] + 'K'
            return karma
        if len(karma) > 6:
            tstring = karma[:-6]
            tstring2 = karma[-6:]
            karma = tstring + '.' + tstring2[:2] + 'M'
            return karma
        else:
            return karma
Esempio n. 57
0
class windowFrame(Frame):
    def __init__(self, parent):
        self.Data = Data()
        self.getReciepList()

        Frame.__init__(self, parent)

        self.parent = parent

        self.recipeList = None  # Listbox
        self.recipeName = None  # Entry
        self.prepTime = None  # Entry
        self.prepTimeUnit = None  # OptionMenu
        self.cookTime = None  # Entry
        self.cookTimeUnit = None  # OptionMenu
        self.ingredientName = None  # Entry
        self.ingredientQuantity = None  # Entry
        self.ingredientUnit = None  # OptionMenu
        self.ingredientList = None  # Listbox
        self.procedure = None  # Text

        self.recipes = []
        self.ingredients = []
        self.activeRecipeID = {"lst": None, "db": None}  # (listID, dbID)
        self.activeIngredientID = {"lst": None, "db": None}  # (listID, dbID)

        self.initUI()

        self.bind_all("<Control-w>", self.onExit)
        self.bind_all("<Control-s>", self.recipeSave)

    # display an error message to the user
    def msgError(self, error):
        print("error: " + error)
        showerror("ERROR!", error)

    # dispaly a warning to the user
    def msgWarning(self, warning):
        showwarning("Warning!", warning)

    # display caution message to user
    def msgCaution(self, caution):
        return askokcancel("Caution!", caution)

    # Get current ingredient selection from ingredient list
    def getIngredientSelection(self):
        if self.ingredients == []:
            self.msgWarning("No ingredient selected.  Try loading a recipe.")
            return -1
        else:
            return self.ingredientList.index(ACTIVE)

    # Get current recipe selection from recipe list
    def getRecipeSelection(self):
        if self.recipes == []:
            self.msgError("No recipes available.")
            return -1
        else:
            selection = list(self.recipeList.curselection())

            if selection == []:
                self.msgError("No recipe selected.")
                return -1
            else:
                return selection

    # retrieve recipe list from the database
    def getReciepList(self):
        self.recipes = self.Data.dbGetRecipeList()

    # retrieve recipe info from the database by recipe ID
    def getRecipeInfo(self, recipeID):
        return self.Data.dbGetRecipeInfo(recipeID)

    # retrieve ingredient info from the database by ingredient ID
    def getIngredientInfo(self, ingredientID):
        return self.Data.dbGetIngredientInfo(ingredientID)

    # Populate the recipe list from a provided list of recipes
    def populateIngredientList(self, ingredients):
        self.ingredients = sorted(self.ingredients, key=itemgetter(-1))

        self.ingredientList.delete(0, END)
        for ingredient in self.ingredients:
            ingredientName = str(ingredient[2])
            ingredientQuantity = str(ingredient[3])
            ingredientUnit = str(ingredient[4])
            self.ingredientList.insert(END, ingredientQuantity + " " + ingredientUnit + " of " + ingredientName)

    # Populate the recipe list from a provided list of recipes
    def populateRecipeList(self, recipes):
        self.recipeList.delete(0, END)
        for recipe in [recipe[1] for recipe in recipes]:
            self.recipeList.insert(END, recipe)

    # save currently loaded ingredient info to database
    def ingredientSaveInfo(self):
        if self.activeIngredientID["lst"] == None:
            self.msgWarning("No ingredient is loaded.")
        else:
            print("Saving ingredient info")

            name = self.ingredientName.get()
            quantity = self.ingredientQuantity.get()
            unit = self.ingredientUnit.get()

            ingredient = self.ingredients[self.activeIngredientID["lst"]]

            print(ingredient)

            ingredient = (ingredient[0], ingredient[1], name, quantity, unit, ingredient[-1])

            print(ingredient)

            self.ingredients[self.activeIngredientID["lst"]] = ingredient

            self.populateIngredientList(self.ingredients)

    # load active ingredient info into GUI elements
    def ingredientLoadInfo(self, ID=None):

        if ID == None:
            currentSelection = self.getIngredientSelection()
            if currentSelection == -1:
                return -1
            else:
                self.activeIngredientID["lst"] = currentSelection
                self.activeIngredientID["db"] = self.ingredients[currentSelection][0]
                print("\n\nLoading ingredient info for ID " + str(self.activeIngredientID))
                ingredient = self.ingredients[self.activeIngredientID["lst"]]
        elif ID >= 0:
            self.activeIngredientID["lst"] = ID
            self.activeIngredientID["db"] = self.ingredients[ID][0]
            ingredient = self.ingredients[self.activeIngredientID["lst"]]
        elif ID == -1:
            print("Clearing ingredient info...")
            self.activeIngredientID = {"lst": None, "db": None}
            ingredient = ["", "", "", "", ""]

        name = ingredient[2]
        quantity = ingredient[3]
        unit = ingredient[4]

        self.ingredientName.delete(0, END)
        self.ingredientName.insert(END, name)
        self.ingredientQuantity.delete(0, END)
        self.ingredientQuantity.insert(END, quantity)
        self.ingredientUnit.delete(0, END)
        self.ingredientUnit.insert(END, unit)

    # Move an ingredient further up in the ingredient list
    def ingredientMoveUp(self):
        currentSelection = self.getIngredientSelection()
        if currentSelection == -1:
            return -1
        elif currentSelection > 0:
            if (
                currentSelection == self.activeIngredientID["lst"]
                or currentSelection - 1 == self.activeIngredientID["lst"]
            ):
                if not self.msgCaution(
                    "Reordering the actively loaded ingredient could cause duplicate and deleted entries when saving.  Continue?"
                ):
                    return
            print("ingredient %d up\n\n" % currentSelection)

            self.ingredients[currentSelection] = self.ingredients[currentSelection][0:-1] + (
                self.ingredients[currentSelection][-1] - 1,
            )
            self.ingredients[currentSelection - 1] = self.ingredients[currentSelection - 1][0:-1] + (
                self.ingredients[currentSelection - 1][-1] + 1,
            )

            self.populateIngredientList(self.ingredients)

            self.ingredientList.select_set(currentSelection - 1)
            self.ingredientList.event_generate("<<ListboxSelect>>")

    # Move an ingredient further down in the ingredient list
    def ingredientMoveDown(self):

        #####################################################
        # Bug: when repeatedly pressing the down button,    #
        # every press after the first switches the order of #
        # the first ingredient with the second ingredient.  #
        #####################################################

        currentSelection = self.getIngredientSelection()
        if currentSelection == -1:
            return -1
        elif currentSelection < len(self.ingredients) - 1:
            if (
                currentSelection == self.activeIngredientID["lst"]
                or currentSelection + 1 == self.activeIngredientID["lst"]
            ):
                if not self.msgCaution(
                    "Reordering the actively loaded ingredient could cause duplicate and deleted entries when saving.  Continue?"
                ):
                    return
            print("ingredient %d down\n\n" % currentSelection)

            self.ingredients[currentSelection] = self.ingredients[currentSelection][0:-1] + (
                self.ingredients[currentSelection][-1] + 1,
            )
            self.ingredients[currentSelection + 1] = self.ingredients[currentSelection + 1][0:-1] + (
                self.ingredients[currentSelection + 1][-1] - 1,
            )

            self.populateIngredientList(self.ingredients)

            self.ingredientList.select_set(currentSelection + 1)
            self.ingredientList.event_generate("<<ListboxSelect>>")

    # Add an ingredient slot to the bottom of the list
    def ingredientAdd(self):
        if self.activeRecipeID["lst"] == None:
            self.msgWarning("No recipe loaded.")
        else:
            blankIngredient = (None, self.activeRecipeID["db"], "blank", "?", "?", len(self.ingredients))
            self.ingredients.append(blankIngredient)

            self.populateIngredientList(self.ingredients)

            self.ingredientLoadInfo(len(self.ingredients) - 1)

    # Delete the currently selected ingredient
    def ingredientDelete(self):

        #######################################################
        # BUG: when pressing the delete button several times, #
        # all but the first press just deletes the first      #
        # ingredient in the list.                             #
        #######################################################

        currentSelection = self.getIngredientSelection()
        if currentSelection == -1 or self.activeRecipeID["lst"] == None:
            return -1
        elif currentSelection < len(self.ingredients) and currentSelection >= 0:
            print("remove ingredient %d\n\n" % currentSelection)

            del self.ingredients[currentSelection]

            for ingredient in range(currentSelection, len(self.ingredients)):
                self.ingredients[ingredient] = self.ingredients[ingredient][0:-1] + (
                    self.ingredients[ingredient][-1] - 1,
                )

            self.populateIngredientList(self.ingredients)

            self.ingredientList.select_set(currentSelection)
            self.ingredientList.event_generate("<<ListboxSelect>>")

            print(self.ingredients)

    # Display help: about dialogue
    def helpAbout(self):
        print("Digital Cookbook v1.0 - Theodore Lindsey")
        aboutDialog = Toplevel()
        aboutDialog.geometry("200x100+300+300")
        aboutDialog.title("About Digital Cookbook")
        Message(aboutDialog, text="Digital Cookbook v1.0\nTheodore Lindsey").pack(side=TOP, fill=BOTH, expand=1)
        Button(aboutDialog, text="Ok", command=aboutDialog.destroy).pack(side=TOP)

    # Import recipe from XML file - need to implement
    def xmlImport(self):
        print("Importing XML file...")

    # add a recipe to the database and create a blank space for the recipe to go - need to implement
    def recipeAdd(self):
        print("Adding recipe...")

    # delete the currently selected recipe - need to implement
    def recipeDelete(self):
        recipeID = self.recipeList.curselection()
        print(recipeID)
        if len(recipeID) == 0:
            self.msgError("No recipes selected.")
            return
        elif len(recipeID) > 1:
            if not askokcancel("Caution!", "Are you sure you want to delete these %d recipes?" % len(recipeID)):
                return
            print("\nDeleting %d recipes..." % len(recipeID))
        else:
            if not askokcancel("Caution!", "Are you sure you want to delete this recipe?"):
                return
            print("\nDeleting recipe %d..." % recipeID)

        blankrecipe = ((None, "", None, "", "", "", "", ""), [])
        self.recipeLoad(blankrecipe)

    # load currently selected recipe
    def recipeLoad(self, recipe=None):
        activeSelection = self.getRecipeSelection()

        if activeSelection == -1:
            return -1
        elif len(activeSelection) > 1:
            self.msgError("Too many recipes selected.")
            return -1
        else:
            if recipe == None:
                listID = activeSelection[0]

                self.activeRecipeID["lst"] = listID
                self.activeRecipeID["db"] = self.recipes[listID][0]

                print(self.activeRecipeID)

                recipe = self.getRecipeInfo(self.activeRecipeID["db"])
            else:
                print("Clearing recipe info...")
                self.activeRecipeID = {"lst": None, "db": None}
                self.ingredientLoadInfo(-1)
            print(recipe)
            name = recipe[0][1]
            servings = recipe[0][2]
            prepTime = recipe[0][3]
            prepTimeUnits = recipe[0][4]
            cookTime = recipe[0][5]
            cookTimeUnits = recipe[0][6]
            procedure = recipe[0][7]
            self.ingredients = recipe[1]

            self.recipeName.delete(0, END)
            self.recipeName.insert(END, name)

            self.prepTime.delete(0, END)
            self.prepTime.insert(END, prepTime)

            self.cookTime.delete(0, END)
            self.cookTime.insert(END, cookTime)

            self.populateIngredientList(self.ingredients)

            self.procedure.delete(0.0, END)
            self.procedure.insert(END, procedure)

    # save changes to active recipe to database
    def recipeSave(self, event=""):
        print(self.activeRecipeID)

        if self.activeRecipeID["lst"] == None:
            self.msgError("No active recipe to save.")
            return -1

        listID = self.activeRecipeID["lst"]
        dbID = self.activeRecipeID["db"]

        name = self.recipeName.get()
        servings = 0  # self.recipes[listID][2]
        prepTime = self.prepTime.get()
        prepUnit = None  # self.prepTimeUnit.????()
        cookTime = self.cookTime.get()
        cookUnit = None  # self.cookTimeUnit.????()
        procedure = self.procedure.get(0.0, END)

        recipeInfo = (dbID, name, servings, prepTime, prepUnit, cookTime, cookUnit, procedure)

        recipe = (recipeInfo, self.ingredients)

        self.recipes[listID] = (dbID, name)

        self.populateRecipeList(self.recipes)

    # quit the program
    def onExit(self, event=""):
        print("Quitting...")
        sys.exit(0)

    # Create the UI layout
    def initUI(self):

        self.parent.title("Digital Cookbook")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1, side=BOTTOM)

        # Establish menu bar #
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        # Add file menu #
        filemenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Import recipe from XML file", command=self.xmlImport)
        filemenu.add_command(label="Add blank recipe to database", command=self.recipeAdd)
        filemenu.add_command(label="Delete recipe from database", command=self.recipeDelete)
        filemenu.add_command(label="Load recipe", command=self.recipeLoad)
        filemenu.add_command(label="Save recipe to database", command=self.recipeSave, accelerator="Ctrl+S")
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.onExit, accelerator="Ctrl+W")
        # Add help menu #
        helpmenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.helpAbout)

        # Establish toolbar #
        frameToolbar = Frame(self.parent)  # , relief=RAISED, borderwidth=1)
        frameToolbar.pack(side=TOP, fill=X)
        # Add buttons to toolbar #
        buffer = 2
        buttonspaceing = 100
        buttonwidth = 12
        buttonheight = 30
        bImportXML = Button(frameToolbar, text="Import XML", command=self.xmlImport, width=buttonwidth)
        bImportXML.pack(side=LEFT, padx=buffer, pady=buffer)
        bAddRecipe = Button(frameToolbar, text="Add Recipe", command=self.recipeAdd, width=buttonwidth)
        bAddRecipe.pack(side=LEFT, padx=buffer, pady=buffer)
        bDeleteRecipe = Button(frameToolbar, text="Delete Recipe", command=self.recipeDelete, width=buttonwidth)
        bDeleteRecipe.pack(side=LEFT, padx=buffer, pady=buffer)
        bEditRecipe = Button(frameToolbar, text="Load Recipe", command=self.recipeLoad, width=buttonwidth)
        bEditRecipe.pack(side=LEFT, padx=buffer, pady=buffer)
        bSaveRecipe = Button(frameToolbar, text="Save Recipe", command=self.recipeSave, width=buttonwidth)
        bSaveRecipe.pack(side=LEFT, padx=buffer, pady=buffer)

        # Recipe list section
        frameRecipeList = Frame(self, borderwidth=1, width=200)
        frameRecipeList.pack_propagate(0)
        frameRecipeList.pack(side=LEFT, fill=Y)
        Label(frameRecipeList, text="Recipe List").pack()
        # Category option menu
        default = StringVar(frameRecipeList)
        default.set("----")
        recipeCatagories = OptionMenu(frameRecipeList, default, "----", "None", "Cat 1", "Cat 2", "Cat 3")
        recipeCatagories.pack(side=TOP, fill=X)
        # Filter Frame
        frameFilter = Frame(frameRecipeList, relief=RAISED, borderwidth=1, width=200)
        frameFilter.pack(side=TOP, fill=X)
        Label(frameFilter, text="Filter...").pack()
        # Filter text
        filterText = Entry(frameFilter)
        filterText.pack_propagate(0)
        filterText.pack(side=LEFT, fill=X)
        # Filter Button
        filterButton = Button(frameFilter, text="Go", command=self.placeholder)
        filterButton.pack_propagate(0)
        filterButton.pack(side=RIGHT)
        # Recipe Box Frame
        frameRecipeBox = Frame(frameRecipeList, relief=RAISED, borderwidth=1)
        frameRecipeBox.pack(side=TOP, fill=BOTH, expand=1)
        # ==== Recipe List box ====
        recipeListScroll = Scrollbar(frameRecipeBox, orient=VERTICAL)
        self.recipeList = Listbox(frameRecipeBox, selectmode=EXTENDED, yscrollcommand=recipeListScroll.set)
        self.recipeList.pack(side=LEFT, fill=BOTH, expand=1)
        recipeListScroll.config(command=self.recipeList.yview)
        recipeListScroll.pack(side=RIGHT, fill=Y)

        self.getReciepList()
        self.populateRecipeList(self.recipes)

        # Spacer
        frameSpacer1 = Frame(self, borderwidth=1, width=10)
        frameSpacer1.pack_propagate(0)
        frameSpacer1.pack(side=LEFT, fill=Y)

        # Recipe info section
        frameRecipeInfo = Frame(self, borderwidth=1, width=200)
        frameRecipeInfo.pack_propagate(0)
        frameRecipeInfo.pack(side=LEFT, fill=Y)
        # Recipe name
        Label(frameRecipeInfo, text="Recipe Name:", anchor=E, justify=LEFT).pack()
        self.recipeName = Entry(frameRecipeInfo)
        self.recipeName.pack(side=TOP, fill=X)
        # Prep Time
        framePrepTime = Frame(frameRecipeInfo)
        framePrepTime.pack(side=TOP, fill=X)
        Label(framePrepTime, text="Prep Time:", anchor=E, justify=LEFT).pack()
        self.prepTime = Entry(framePrepTime)
        self.prepTime.pack(side=LEFT, fill=X)
        default = StringVar(framePrepTime)
        default.set("----")
        self.prepTimeUnit = OptionMenu(framePrepTime, default, "----", "Min", "Hr")
        self.prepTimeUnit.pack(side=RIGHT, fill=X)
        # Cook Time
        frameCookTime = Frame(frameRecipeInfo)
        frameCookTime.pack(side=TOP, fill=X)
        Label(frameCookTime, text="Cook Time:", anchor=E, justify=LEFT).pack()
        self.cookTime = Entry(frameCookTime)
        self.cookTime.pack(side=LEFT, fill=X)
        default = StringVar(frameCookTime)
        default.set("----")
        self.cookTimeUnit = OptionMenu(frameCookTime, default, "----", "Min", "Hr")
        self.cookTimeUnit.pack(side=RIGHT, fill=X)

        # Spacer
        frameSpacer2 = Frame(self, borderwidth=1, width=10)
        frameSpacer2.pack_propagate(0)
        frameSpacer2.pack(side=LEFT, fill=Y)

        # Ingredient List
        frameIngredients = Frame(self, borderwidth=1, width=300)
        frameIngredients.pack_propagate(0)
        frameIngredients.pack(side=LEFT, fill=Y)
        Label(frameIngredients, text="Ingredients").pack()
        # Ingredient Name
        self.ingredientName = Entry(frameIngredients)
        self.ingredientName.pack(side=TOP, fill=X)
        # Ingredient info
        frameIngredientQuantity = Frame(frameIngredients)
        frameIngredientQuantity.pack(side=TOP, fill=X)
        Label(frameIngredientQuantity, text="Ingredient Quantity (value, unit):", anchor=E, justify=LEFT).pack()
        self.ingredientQuantity = Entry(frameIngredientQuantity)
        self.ingredientQuantity.pack(side=LEFT, fill=X, expand=1)
        self.ingredientUnit = Entry(frameIngredientQuantity, width=20)
        self.ingredientUnit.pack_propagate(0)
        self.ingredientUnit.pack(side=RIGHT, fill=X)
        # Spacer
        frameSpacer3 = Frame(frameIngredients, height=10)
        frameSpacer3.pack_propagate(0)
        frameSpacer3.pack(side=TOP, fill=X)
        # Ingredient List buttons
        frameIngredientButtons = Frame(frameIngredients)
        frameIngredientButtons.pack(side=TOP, fill=X)
        ingredientAdd = Button(frameIngredientButtons, text="+", command=self.ingredientAdd, width=3)
        ingredientAdd.pack(side=LEFT)
        ingredientDel = Button(frameIngredientButtons, text="-", command=self.ingredientDelete, width=3)
        ingredientDel.pack(side=LEFT)
        ingredientUp = Button(frameIngredientButtons, text=u"\u25B2", command=self.ingredientMoveUp, width=3)
        ingredientUp.pack(side=LEFT)
        ingredientDwn = Button(frameIngredientButtons, text=u"\u25BC", command=self.ingredientMoveDown, width=3)
        ingredientDwn.pack(side=LEFT)
        ingredientLoad = Button(frameIngredientButtons, text="Load", command=self.ingredientLoadInfo)
        ingredientLoad.pack(side=LEFT)
        ingredientSave = Button(frameIngredientButtons, text="Save", command=self.ingredientSaveInfo)
        ingredientSave.pack(side=LEFT)
        # Ingredient List Box Frame
        frameIngredientList = Frame(frameIngredients, relief=RAISED, borderwidth=1)
        frameIngredientList.pack(side=TOP, fill=BOTH, expand=1)
        # Ingredient List box
        ingredientListScroll = Scrollbar(frameIngredientList, orient=VERTICAL)
        self.ingredientList = Listbox(
            frameIngredientList, selectmode=SINGLE, yscrollcommand=ingredientListScroll.set
        )  # Set selectmode=SINGLE????
        self.ingredientList.pack(side=LEFT, fill=BOTH, expand=1)
        ingredientListScroll.config(command=self.ingredientList.yview)
        ingredientListScroll.pack(side=RIGHT, fill=Y)

        # Spacer
        frameSpacer4 = Frame(self, borderwidth=1, width=10)
        frameSpacer4.pack_propagate(0)
        frameSpacer4.pack(side=LEFT, fill=Y)

        # Recipe Procedure
        frameProcedure = Frame(self, borderwidth=1)
        frameProcedure.pack(side=LEFT, fill=BOTH, expand=1)
        Label(frameProcedure, text="Procedure", anchor=E, justify=LEFT).pack(side=TOP)
        procedureScroll = Scrollbar(frameProcedure, orient=VERTICAL)
        self.procedure = Text(frameProcedure, maxundo=30, undo=1, wrap=WORD, yscrollcommand=procedureScroll.set)
        self.procedure.pack(side=LEFT, fill=BOTH, expand=1)
        procedureScroll.config(command=self.procedure.yview)
        procedureScroll.pack(side=LEFT, fill=Y)

    # placeholder function for unimplemented UI elements
    def placeholder(self):
        print("Coming soon!")
Esempio n. 58
0
class BookManagerUi(Frame):

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

        self.parent = parent

        self.initUI()

        self.db = dao('blist') #데이터베이스 관리 클래스 생성


    def initUI(self):

        self.parent.title("Book Manager")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

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


        self.input_bname=''
        self.input_aname=''
        self.input_price=0
        self.delete=''

        lb_bookname = Label(self, text="bookname:")
        lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5)

        self.entry_bookname = Entry(self)
        self.entry_bookname.grid(row=0, column = 1 )

        lb_author = Label(self, text="author:")
        lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5)

        self.entry_author = Entry(self)
        self.entry_author.grid(row=0, column = 3 )


        lb_price = Label(self, text="price:")
        lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5)

        self.entry_price = Entry(self)
        self.entry_price.grid(row=0, column = 5 ,padx=15)


        abtn = Button(self, text="Add", command=lambda:self.clicked_add())
        abtn.grid(row=0, column=6)

        sbtn = Button(self, text="Serach", command = lambda:self.clicked_search())
        sbtn.grid(row=1, column=6, pady=4)

        dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete())
        dbtn.grid(row=2, column=6, pady=4)

        self.lb = Listbox(self)

        self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)


    #삭제를 위한 select부분
    def onSelect(self,val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.delete = value

    # 데이터 추가 버튼
    def clicked_add(self):
        bname =self.entry_bookname.get()
        aname = self.entry_author.get()
        price = self.entry_price.get()

        self.lb.delete(0,END)


        # 입력받을 데이터가 모자란지 검사
        if(len(bname) >0 and len(aname)>0 and len(price)>0 ):
            #가격에 문자를 입력했을 경우 처리
            try:
                priceI = eval(price)
            except:
                self.lb.insert(END,"you input wrong price. it must be integer")

            #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외)
            rec = self.db.excute_select(bname,'')
            if ( len(rec) >0):
                self.lb.insert(END,bname +" is already in the database")
            else:
                self.db.insert_data(bname,aname,priceI) # 모든 조건 만족시 데이터 입력 수행
                r =self.db.excute_select(bname,aname)
                for rs in r:
                    self.lb.insert(END,str(rs))


        else:
            s = StringVar()
            self.entry_price.config(textvariable = s)
            self.lb.insert(END,"you have to input more values")


    #검색버튼
    def clicked_search(self):
        bname =self.entry_bookname.get()
        aname = self.entry_author.get()

        self.lb.delete(0,END)

        #책이름 또는 저자이름 둘중 하나만입력 되어도 검색 가능하도록
        if(len(bname)>0 or len(aname)>0 ):
            rec = self.db.excute_select(bname,aname)

            for r in rec:
                self.lb.insert(END,str(r))
        else:
            self.lb.insert(END,"you have to input more values(bookname or author")

    #삭제 버튼
    def clicked_delete(self):
        self.lb.delete(0,END)
        q = self.db.excute_delete(self.delete)
        self.lb.insert(END,q+' is delete from database')
Esempio n. 59
0
class autoClicker(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
    
    def initUI(self):
        self.sliderTime=0
        self.running = 0
        self.leftclick = 0
        self.middleclick = 0
        self.rightclick = 0
                
        self.parent.overrideredirect(True)
        self.style = Style()
        self.style.theme_use("default")
        self.parent.wm_attributes("-topmost", 1)
        self.parent.resizable(0,0)
        
        self.gripBar = BitmapImage(data=GRIPBAR)
        self.closeBox = BitmapImage(data=CLOSEBOX)
        self.closeHover = BitmapImage(data=CLOSEHOVER)
        self.leftClick = BitmapImage(data=LEFTCLICK)
        self.leftClickDown = BitmapImage(data=LEFTCLICKDOWN)
        self.middleClick = BitmapImage(data=MIDDLECLICK)
        self.middleClickDown = BitmapImage(data=MIDDLECLICKDOWN)
        self.rightClick = BitmapImage(data=RIGHTCLICK)
        self.rightClickDown = BitmapImage(data=RIGHTCLICKDOWN)
        
        self.barFrame = Frame(self)
        self.barFrame.pack(side=TOP, fill=BOTH)
        self.clickFrame = Frame(self, borderwidth=0)
        self.clickFrame.pack(side=TOP, fill=BOTH, padx=12, expand=1)

        self.sliderScale = Scale(self, from_=0, to=1, resolution=.01, orient=HORIZONTAL, borderwidth=0, showvalue=0)
        self.sliderScale.pack(side=TOP, fill="x", expand=1)
        
        self.buttonFrame = Frame(self, borderwidth=0)
        self.buttonFrame.pack(side=TOP, fill=BOTH, expand=1)
        
        self.grip = Label(self.barFrame, image=self.gripBar)
        self.grip.image=self.gripBar
        self.grip.pack(side=LEFT, fill="x")
        self.grip.bind("<ButtonPress-1>", self.startMove)
        self.grip.bind("<ButtonRelease-1>", self.stopMove)
        self.grip.bind("<B1-Motion>", self.onMotion)
        
        self.closeButton = Label(self.barFrame, image=self.closeBox)
        self.closeButton.image=self.closeBox
        self.closeButton.pack(side=RIGHT, fill="none")
        self.closeButton.bind("<ButtonPress-1>", self.sysExit)
        self.closeButton.bind("<Enter>", self.onHover)
        self.closeButton.bind("<Leave>", self.onLeave)
        
        self.leftClickToggle = Label(self.clickFrame, image=self.leftClick, borderwidth=0)
        self.leftClickToggle.image=self.leftClick
        self.leftClickToggle.pack(side=LEFT, expand=1)
        self.leftClickToggle.bind("<Button-1>", self.leftToggle)
        
        self.middleClickToggle = Label(self.clickFrame, image=self.middleClick, borderwidth=0)
        self.middleClickToggle.image=self.middleClick
        self.middleClickToggle.pack(side=LEFT, expand=1)
        self.middleClickToggle.bind("<Button-1>", self.middleToggle)

        self.rightClickToggle = Label(self.clickFrame, image=self.rightClick, borderwidth=0)
        self.rightClickToggle.image=self.rightClick
        self.rightClickToggle.pack(side=LEFT, expand=1)
        self.rightClickToggle.bind("<Button-1>", self.rightToggle)

        self.startButton = Button(self.buttonFrame, text="Start", relief=FLAT, activebackground="lightgrey", borderwidth=0)
        self.startButton.pack(fill=BOTH, expand=1)
        self.startButton.bind("<Button-1>", self.startClick)
        self.startButton.bind("<space>", self.startClick)
                
        w = 116
        h = 74

        ws = self.winfo_screenwidth() # width of the screen
        hs = self.winfo_screenheight() # height of the screen

        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.parent.config(bg="black")
        self.pack(fill="both", padx=1, pady=1)
        
    def leftToggle(self,event):
        if self.running == 0:
            if self.leftclick == 0:
                event.widget.configure(image=self.leftClickDown)
                self.leftclick = 1;
            else:
                event.widget.configure(image=self.leftClick)
                self.leftclick = 0;
                
    def middleToggle(self,event):
        if self.running == 0:
            if self.middleclick == 0:
                event.widget.configure(image=self.middleClickDown)
                self.middleclick = 1;
            else:
                event.widget.configure(image=self.middleClick)
                self.middleclick = 0;
                
    def rightToggle(self,event):
        if self.running == 0:
            if self.rightclick == 0:
                event.widget.configure(image=self.rightClickDown)
                self.rightclick = 1;
            else:
                event.widget.configure(image=self.rightClick)
                self.rightclick = 0;

    def onHover(self,event):
        event.widget.configure(image=self.closeHover)
    
    def onLeave(self,event):
        event.widget.configure(image=self.closeBox)

    def startMove(self,event):
        self.parent.x = event.x
        self.parent.y = event.y
        
    def onMotion(self, event):
        deltax = event.x - self.parent.x
        deltay = event.y - self.parent.y
        x = self.parent.winfo_x() + deltax
        y = self.parent.winfo_y() + deltay
        self.parent.geometry("+%s+%s" % (x, y))
        
    def stopMove(self, event):
        event.x = None
        event.y = None

    def sysExit(self, event):
        self.running = 0
        sys.exit()
            
    def startClick(self, event):
        if self.running == 0 and not (self.leftclick == 0 and self.middleclick==0 and self.rightclick == 0):
            self.running = 1
            event.widget.config(text="Stop")
            currentMouseX, currentMouseY = pyautogui.position()
            pyautogui.moveTo(currentMouseX, currentMouseY+50)
            threading.Thread(target=self.startLoop, args=()).start()
        else:
            self.running = 0
            event.widget.config(text="Start")
        time.sleep(0.2)
        return

    def startLoop(self):
        while self.running == 1:
            if self.leftclick == 1:
                pyautogui.click()
            if self.middleclick == 1:
                pyautogui.click(button="middle")
            if self.rightclick == 1:
                pyautogui.click(button="right")
            delay = self.sliderScale.get()
            time.sleep(delay)
        return