def pilve_pildid():
    """Load two pictures of clouds and return them."""
    pilve_pilt = PhotoImage(file="vihmaPilv.png")
    pilve_pilt = pilve_pilt.subsample(4, 4)
    teine_pilv = PhotoImage(file="tavalinePilv.png")
    teine_pilv = teine_pilv.subsample(7, 7)
    return pilve_pilt, teine_pilv
Exemplo n.º 2
0
def __main__():

    try:
        img_1 = PhotoImage(file=joinDirectory(
            getPathAssets(), "img_1_test.png"))

        img_1 = img_1.subsample(1)

        btnFind = Button(
            gui, image=img_1, cursor="hand1", border=0, command=getFolderPath)

        btnFind.pack()

        img_start = PhotoImage(file=joinDirectory(
            getPathAssets(), "img_start.png"))
        img_start = img_start.subsample(2)

        btnStart = Button(gui, image=img_start, cursor="hand1",
                          border=0, command=start)

        btnStart.pack()

        img_by = PhotoImage(file=joinDirectory(getPathAssets(), "by.png"))
        buttonBy = Button(gui, border=0, cursor="hand1",
                          padx=10, pady=10, image=img_by, command=urlOpenYAVBCODE)
        buttonBy.pack(side="right")

        gui.mainloop()

    except:
        messagebox.showwarning(message="Ocurrio un Error", title="ERROR")
        exit()
Exemplo n.º 3
0
    def __init__(self, root):
        self.root = root
        self.root.title('Find my tune')
        self.root.geometry()
        self.root.minsize(800, 800)
        self.searchname = tkinter.StringVar()

        # creating help button
        help_button_img = PhotoImage(file='images/help_button.png')
        help_button_img = help_button_img.subsample(2)
        help_img_label = Label(image=help_button_img)
        help_img_label.image = help_button_img
        self.help_button = Button(self.root,
                                  image=help_button_img,
                                  command=self.helpFrame,
                                  border=0)
        self.help_button.pack(side=TOP, anchor=NE, padx=10, pady=10)

        # creating input frame
        self.input_frame = Frame(self.root)
        self.input_frame.pack()

        # creating heading
        heading = Label(self.input_frame,
                        text="Find My Tune",
                        font=("Helvetica", 30),
                        fg="black")
        heading.pack(pady=20, side=TOP)

        # creating search bar
        self.search_box_input = Entry(self.input_frame,
                                      font=("Helvetica", 20),
                                      textvariable=self.searchname)
        self.search_box_input.pack()

        # creating search button
        search_button_img = PhotoImage(file='images/search_button.png')
        search_button_img = search_button_img.subsample(2)
        search_img_label = Label(image=search_button_img)
        search_img_label.image = search_button_img
        self.search_button = Button(self.input_frame,
                                    image=search_button_img,
                                    border=0,
                                    command=self.searchSong)
        self.search_button.pack(pady=10, side=LEFT)

        # creating refresh button
        refresh_button_img = PhotoImage(file='images/refresh_button.png')
        refresh_button_img = refresh_button_img.subsample(2)
        refresh_img_label = Label(image=refresh_button_img)
        refresh_img_label.image = refresh_button_img
        self.refresh_button = Button(self.input_frame,
                                     image=refresh_button_img,
                                     fg='green',
                                     command=self.refreshFrame,
                                     border=0)
        self.refresh_button.pack(pady=10, side=RIGHT)
class ButtonLabel:
    def __init__(self, master):

        self.master = master
        master.title("Capturing input with Buttons")

        # Create a button with the class Button
        self.button = Button(master,
                             text='Click Me ',
                             font=('Arial', 16, 'bold'))
        self.button.pack()
        # assing a function with 'command' parameter
        self.button.config(command=self.callback)
        # Simulate a button click
        self.button.invoke()
        # Disable button
        self.button.config(state='disable')
        # Back to normal button
        self.button.config(state='normal')

        # Assing image path
        self.logo = PhotoImage(
            file=
            "C:\\Users\\marce\\Google Drive\\PROGRAMMING\\CURSOS\\LINKEDIN LEARNING\\Become a Python Developer\\Python GUI Development with Tkinter\\python-dev-gui-tkinter\\images\\python.gif"
        )
        # Resize logo
        self.small_logo = self.logo.subsample(30, 30)
        # put logo inside the button, on the right side
        self.button.config(image=self.small_logo, compound=RIGHT)

    def callback(self):
        print('Clicked')
Exemplo n.º 5
0
 def PlaceBtn(imgfile,_row,_col, _callback,lbl):
     photo1 = PhotoImage(file=imgfile)
     photo1 = photo1.zoom(3)
     photo1 = photo1.subsample(5)
     btn = Button(self, text="Up",command = lambda: _callback(lbl), image=photo1, borderwidth=0)
     btn.image = photo1
     btn.grid(row=_row, column=_col) 
Exemplo n.º 6
0
 def get_image(location, width, height):
     image = PhotoImage(data=Resource(location).resource)
     orig_width = image.width()
     orig_height = image.height()
     image = image.zoom(width, height)
     image = image.subsample(orig_width, orig_height)
     return image
Exemplo n.º 7
0
    def __init__(self, parent, controller):
        global button6
        print(parent)
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Welcome to TRAT", font=LARGE_FONT)
        label.place(x=210, y=20)

        button = ttk.Button(self, text="ORGANIZATIONAL READINESS", width=25,
                            command=lambda: controller.show_frame(PageOne))
        button.place(x=250, y=90)

        button2 = ttk.Button(self, text="TECHNOLOGY READINESS", width=25,
                             command=lambda: controller.show_frame(PageTwo))
        button2.place(x=250, y=120)
        button3 = ttk.Button(self, text="FINANCIAL READINESS", width=25,
                             command=lambda: controller.show_frame(PageThree))
        button3.place(x=250, y=150)
        button4 = ttk.Button(self, text="POLICY READINESS", width=25,
                             command=lambda: controller.show_frame(PageFour))
        button4.place(x=250, y=180)
        button5 = ttk.Button(self, text="ABOUT TRAT",
                             command=lambda: controller.show_frame(About))
        button5.place(x=50, y=270)
        button6 = ttk.Button(self, text="INSTRUCTIONS",
                             command=lambda: controller.show_frame(Instructions))
        button6.place(x=550, y=270)
        button6 = ttk.Button(self, text="Overall Readiness Score", state = 'disabled',
                             command=lambda: controller.show_frame(OverallReadiness))
        button6.place(x=280, y=310)

        photo = PhotoImage(file="logo.png")

        photo = photo.subsample(6, 6)
        label = ttk.Label(self, image=photo)

        label.image = photo
        label.place(x=20, y=120)

        photo1 = PhotoImage(file="logo1.png")

        photo1 = photo1.subsample(2, 2)
        label1 = ttk.Label(self, image=photo1)

        label1.image = photo1
        label1.place(x=550, y=100)
Exemplo n.º 8
0
 def __LoadInterface(self):
     """ Load GUI interface from json instead of live"""
     standard.Log("Loading GUI interface...")
     interface = standard.LoadInterface()
     for n, i in enumerate(interface):
         extra = {}
         if i["x"] < 0:
             x = self.root.winfo_screenwidth()+i["x"]
         else:
             x = i["x"]
         if i["y"] < 0:
             y = self.root.winfo_screenheight()+i["y"]
         else:
             y = i["y"]
         if (i["type"] == "label"):
             widget = Label(
                 self.__Root,
                 width = i["width"],
                 height = i["height"],
                 bg=self.__Configuration["pixel.pixel"]["background colour"],
                 anchor=W,
                 justify=LEFT)
             extra["module"] = i["module"]
         elif i["type"] == "button":
             widget = Button(
                 self.__Root, 
                 width = i["width"],
                 height = i["height"],
                 bg=self.__Configuration["pixel.pixel"]["background colour"])
                 #relief="flat")
         elif i["type"] == "image":
             widget = Label(
                 self.__Root,
                 width = i["width"],
                 height = i["height"],
                 bg=self.__Configuration["pixel.pixel"]["background colour"],
                 anchor=W, 
                 justify=LEFT)
         if "text" in i:
             widget.config(
                 text = i["text"],
                 font = (i["font"], i["font size"]),
                 fg=i["font colour"])
         elif "image" in i:
             photo = PhotoImage(file = i["image"])
             extra["image"] = i["image"]
             if "zoom" in i:
                 photo = photo.zoom(i["zoom"])
                 extra["zoom"] = i["zoom"]
             if "subsample" in i:
                 photo = photo.subsample(i["subsample"])
                 extra["subsample"] = i["subsample"]
             widget.config(image = photo)
             widget.image = photo
         widget.place(x = i["x"], y = i["y"])
         self.__Interface.append((i["tag"], widget, extra))
     standard.Log("Loading GUI interface... Done")
Exemplo n.º 9
0
 def format_image(self, file, ratio):
     assert (ratio >= 1), "Ratio must be bigger than 1!"
     my_path = "images/" + str(file) + ".gif"
     image = PhotoImage(file = my_path)
     sfx = image.width() / self.size
     sfy = image.height() / self.size
     sf = int(min(sfx, sfy) * ratio)
     new_image = image.subsample(sf, sf)
     return new_image
Exemplo n.º 10
0
    def criaTelaConfigurações(self):
        self.config_window = Toplevel(self)
        # cria o frame
        frame = LabelFrame(self.config_window, text="Configurações")
        # poe imagem de configurações
        img = PhotoImage(file='./icons/gear.png')
        img = img.subsample(8, 8)
        img_lbl = Label(frame, image=img)
        img_lbl.image = img
        img_lbl.grid(row=0, column=0, columnspan=2, pady=20)
        # insere labels
        Label(frame, text='Carrier (5 espaços): ').grid(row=1,
                                                        column=0,
                                                        sticky=W)
        Label(frame, text='Battleship (4 espaços): ').grid(row=2,
                                                           column=0,
                                                           sticky=W)
        Label(frame, text='Submarine (3 espaços): ').grid(row=3,
                                                          column=0,
                                                          sticky=W)
        Label(frame, text='Destroyer (2 espaços): ').grid(row=4,
                                                          column=0,
                                                          sticky=W)
        Label(frame, text='Percentual de água: ').grid(row=5,
                                                       column=0,
                                                       sticky=W)
        Label(frame, text='Tamanho do tabuleiro').grid(row=6,
                                                       column=0,
                                                       sticky=W)
        # insere entradas
        self.carrier_entry = Entry(frame)
        self.carrier_entry.insert(0, str(self.navios[0]))
        self.carrier_entry.grid(row=1, column=1)
        self.battleship_entry = Entry(frame)
        self.battleship_entry.insert(0, str(self.navios[1]))
        self.battleship_entry.grid(row=2, column=1)
        self.submarine_entry = Entry(frame)
        self.submarine_entry.insert(0, str(self.navios[2]))
        self.submarine_entry.grid(row=3, column=1)
        self.destroyer_entry = Entry(frame)
        self.destroyer_entry.insert(0, str(self.navios[3]))
        self.destroyer_entry.grid(row=4, column=1)
        self.n_entry = Entry(frame)
        self.n_entry.insert(0, str(self.n))
        self.n_entry.grid(row=6, column=1)
        # insere slider de pma
        self.pma_slider = Scale(frame, from_=10, to=60, orient=HORIZONTAL)
        self.pma_slider.set(self.pma * 100)
        self.pma_slider.grid(row=5, column=1)

        # insere botao de ok
        ok_button = Button(frame, text="Salvar", command=self.getNumeros)
        ok_button.grid(row=7, column=0, columnspan=2, sticky=W + E)
        # poe o frame na tela
        frame.pack(padx=5, pady=5)
        pass
Exemplo n.º 11
0
Arquivo: gui.py Projeto: mgely/scriptq
    def __init__(self, *args, image=None, **kwargs):

        # Import image
        image = PhotoImage(file=path.join(graphics_directory, image))

        # Make two times smaller
        image = image.subsample(2, 2)

        super(ImageLabel, self).__init__(*args, image=image, **kwargs)

        # This is necessary otherwise the picture dosnt appear somehow
        self.image = image
Exemplo n.º 12
0
def popmessage(emotion):
	root = Tk()
	# First command line arg is image path. PNG format
	img = PhotoImage(file=emotion)
	img = img.subsample(1, 1)
	my_image = Label(root, image=img)
	my_image.pack()
	button = Button(root, text='OK', width=30, command=root.destroy)
	button.pack(padx=40, pady=40)
	button.config(bg='dark green', fg='white')
	button.config(font=('helvetica', 100, 'underline italic'))
	root.mainloop()
Exemplo n.º 13
0
class Reaction():
    def __init__(self):
        self.text = ""
        self.id = 'base'
        self.face = PhotoImage(file="img/base.png")
        self.face = self.face.zoom(1, 1)
        self.face = self.face.subsample(1, 1)

    def __call__(self, reaction):
        self.face = reaction.face

    def __eq__(self, obj):
        return self.id == obj.id
Exemplo n.º 14
0
def reklaam_start(taust):
    """Close the previous window and create a new one for the commercial.

    The previous window will be closed after the button is pressed. Pictures
    are made for functions and functions are called out for the commercial.
    """
    taust.destroy()
    aken = Tk()
    aken.title("Reklaam")
    aken.geometry("720x480")
    aken["bg"] = "Blue"
    vana_pilt = PhotoImage(file="jouluvana_saanis.png")
    vana_pilt = vana_pilt.subsample(4, 4)
    lume_pilt = PhotoImage(file="snowflake.png")
    lume_pilt = lume_pilt.subsample(25, 25)
    kingi_pilt = PhotoImage(file="gift.png")
    kingi_pilt = kingi_pilt.subsample(15, 15)
    aken.grid()
    pilve_list = pilve_pildid()
    loo_pilv(aken, pilve_list, 7)
    jouluvana(aken, vana_pilt)
    loo_lumi(aken, lume_pilt, kingi_pilt)
    aken.mainloop()
Exemplo n.º 15
0
    def __init__(self, cns, x, y):
        from tkinter import PhotoImage
        self.cns = cns
        self.x = x
        self.y = y

        self.ref = {}  # Reference de toutes les images d'émotions
        path = "./img/emoticons/"

        for state in ["happy", "tickle"
                      ]:  # ["happy", "pokerface", "tickle", "anxious","dead"]
            img = PhotoImage(file=path + state + ".gif")
            self.ref[state] = img.subsample(5, 5)

        self.draw("happy")
Exemplo n.º 16
0
    def _icon_scale(self, icon: tk.PhotoImage) -> tk.PhotoImage:
        '''
        Rescale icon.

        Args:
            icon: icon to be rescaled
        Returns:
            tk.PhotoImage: rescaled icon
        '''

        if self.scaling[0] != 1:
            icon = icon.zoom(self.scaling[0], self.scaling[0])
        if self.scaling[1] != 1:
            icon = icon.subsample(self.scaling[1], self.scaling[1])
        return icon
Exemplo n.º 17
0
    def load_frames(self, path, zoom, subsample):

        self._frames = []
        i = 0
        try:
            while i < 100:
                fformat = "gif -index " + str(i)
                photoframe = PhotoImage(file=path, format=fformat)
                photoframe = photoframe.zoom(zoom)
                photoframe = photoframe.subsample(subsample)
                self._frames.append(photoframe)
                i += 1
        except Exception as inst:
            if (inst.args[0] == 'no image data for this index'):
                pass

        self._last_index = len(self._frames)
Exemplo n.º 18
0
    def __init__(self, win):
        super().__init__()
        self.video = Capture()
        self.win = win
        self.win.title("FCA")
        Label(self.win,
              bg='white',
              fg='black',
              text="--UIT ATTENDANCE--",
              font=('times new roman', 25)).pack(fill=X)
        self.canvas = Canvas(self.win, bd=2, height=480, width=640)
        self.canvas.pack(fill=BOTH, expand='yes')

        self.frame3 = Frame(self.win, bg='white')
        self.frame3.pack(fill=X)

        self.marked_label = Label(self.frame3,
                                  text="",
                                  wraplength=500,
                                  font=('times new roman', 12, "bold"))
        self.marked_label.pack(fill=X, expand='yes')

        self.label1 = Label(self.frame3,
                            text="Look in to the Camera :)",
                            bg='white',
                            fg="green",
                            font=('times new roman', 16))

        self.label1.pack(side=LEFT, expand=TRUE)
        photo = PhotoImage(file=r"resources/close.png")
        photoimage = photo.subsample(2, 2)
        Button(self.frame3, bg="white", image=photoimage,
               command=self.close).pack(side=RIGHT)

        userpic = ImageTk.PhotoImage(Image.open("resources/emptyFace.jpg"))
        self.image_label = Label(self.frame3,
                                 image=userpic,
                                 height=200,
                                 width=200)
        self.image_label.pack()

        self.updates()
        self.win.mainloop()
Exemplo n.º 19
0
def gui():
    root = tk.Tk()
    root.title("S.A.V.A")

    root.resizable(False, False)

    canvas1 = tk.Canvas(root, width=300, height=300)
    canvas1.configure(background='#c8c8c8')
    canvas1.pack()

    entry1 = tk.Entry(root)
    canvas1.create_window(150, 140, window=entry1)

    photo = PhotoImage(file=r"res\AI.png")
    photoimage = photo.subsample(7, 7)
    button1 = tk.Button(image=photoimage, background='#ffffff', command=lambda: get_question(entry1))

    canvas1.create_window(150, 180, window=button1)

    root.mainloop()
Exemplo n.º 20
0
class DislpayLabel:
    def __init__(self, master):

        self.master = master
        master.title("Displaying text and images with Labels")

        # *******************
        # TEXT
        # *******************
        self.label = Label(master, text="Hello Tkinter")
        self.label.pack()

        self.label.config(
            text="I just have changed the text. This is an amazing OOP program"
        )
        # Wrap the text, passing number of pixels
        self.label.config(wraplength=150)
        # Justify text
        self.label.config(justify=CENTER)
        # Setup colors
        self.label.config(foreground='blue', background='yellow')
        # Setup font -> passing a set of elements
        self.label.config(font=('Courier', 18, 'bold'))

        # *******************
        # IMAGE
        # *******************

        # Assign image path
        self.logo = PhotoImage(
            file=
            "C:\\Users\\marce\\Google Drive\\PROGRAMMING\\CURSOS\\LINKEDIN LEARNING\\Become a Python Developer\\Python GUI Development with Tkinter\\python-dev-gui-tkinter\\images\\python.gif"
        )
        #Resize logo
        self.small_logo = self.logo.subsample(5, 5)
        # Put logo in label
        self.label.config(image=self.small_logo)
        self.label.config(compound='left')
def PhotoImageFromLink(link, width=None, height=None, scale=None):
    base64_data = downloadImage(link)
    image = PhotoImage(data=base64_data)
    (old_w, old_h) = (image.width(), image.height())

    if scale != None:
        width = int(old_w * scale)
        height = int(old_h * scale)

    (target_w, target_h) = (width, height)

    if (target_w != None and target_h != None):
        x_common = math.gcd(target_w, old_w)
        x_zoom = int(target_w / x_common)
        x_sub = int(old_w / x_common)

        y_common = math.gcd(target_h, old_h)
        y_zoom = int(target_h / y_common)
        y_sub = int(old_h / y_common)

        image = image.zoom(x_zoom, y_zoom)
        image = image.subsample(x_sub, y_sub)

    return image
Exemplo n.º 22
0
class Splash(Toplevel):
    def __init__(self, parent):
        from tkinter import Label, PhotoImage
        from tkinter.ttk import Progressbar

        Toplevel.__init__(self, parent)
        self.title("Splash")
        self.overrideredirect(True)

        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        width = round(screenwidth / 30) * 10
        height = round(screenheight / 30) * 10

        self.gif1 = PhotoImage(file='timg.gif')
        old_width = self.gif1.width()
        old_height = self.gif1.height()
        scale_w = width/old_width
        scale_h = (height-20)/old_height
        if scale_h < 1:
            scale_h = 1 / scale_h
        if scale_w < 1:
            scale_w = 1 / scale_w
        self.gif1 = self.gif1.subsample(int(scale_w), int(scale_h))
        self.label = Label(self, image=self.gif1)
        self.label.config(width=width, height=height-20, bg='white', bd=1)

        self.pgb = Progressbar(self, orient='horizontal', length=width, mode='determinate')

        self.geometry('%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2))

        self.label.pack(side='top', fill='both')
        self.pgb.pack(side='bottom', fill='both')

        # required to make window show before the program gets to the mainloop
        self.update()
Exemplo n.º 23
0
class Window:
    def __init__(self, window):
        self.window = window
        self.random_list = []
        self.color = "black"
        self.dark_image = PhotoImage(file="dark_mode.png")
        self.dark_image = self.dark_image.zoom(1)
        self.dark_image = self.dark_image.subsample(30)
        self.canvas = Canvas(self.window, bg="#f0ffff")
        self.canvas.place(relx=0, relwidth=1, relheight=0.80)
        self.display_options()

    def display_options(self):
        lower_frame = tk.Frame(self.window, bg="#1b3945")
        lower_frame.place(relx=0, rely=0.8, relwidth=1, relheight=0.2)

        algorithm_label = tk.Label(lower_frame, text="Algorithm", width=20)
        algorithm_label.place(x=40, y=20)

        combo_algorithm = ttk.Combobox(lower_frame,
                                       values=[
                                           "Bubble sort", "Selection sort",
                                           "Insertion sort",
                                           "Cocktail shaker sort", "Shell sort"
                                       ],
                                       font=(8))
        combo_algorithm.place(x=40, y=60)
        combo_algorithm.config(font=("Helvetica"), width=16)
        combo_algorithm.current(0)

        min_value = tk.Label(lower_frame, text="Min. Value", width=20)
        min_value.place(x=240, y=20)

        min_value_number = tk.Scale(lower_frame,
                                    from_=1,
                                    to=1000,
                                    orient=tk.HORIZONTAL,
                                    width=5)
        min_value_number.place(x=260, y=60)

        max_value = tk.Label(lower_frame, text="Max. Value", width=20)
        max_value.place(x=440, y=20)

        max_value_number = tk.Scale(lower_frame,
                                    from_=1,
                                    to=1000,
                                    orient=tk.HORIZONTAL,
                                    width=5)
        max_value_number.place(x=460, y=60)

        speed = tk.Label(lower_frame, text="Speed", width=19)
        speed.place(x=640, y=20)

        speed_var = tk.Scale(lower_frame,
                             from_=1,
                             to=5,
                             orient=tk.HORIZONTAL,
                             width=5)
        speed_var.place(x=660, y=60)

        new_info_btn = tk.Button(
            lower_frame,
            text="Generate graph",
            activebackground="#468499",
            width=12,
            command=lambda: self.generate_info(min_value_number.get(
            ), max_value_number.get(), combo_algorithm.get()))
        new_info_btn.place(x=825, y=15)

        sort_items = tk.Button(lower_frame,
                               text="Sort",
                               activebackground="#468499",
                               width=12,
                               command=lambda: self.select_algorithm(
                                   speed_var.get(), combo_algorithm.get()))
        sort_items.place(x=825, y=53)

        delete_btn = tk.Button(lower_frame,
                               text="Delete all",
                               activebackground="#468499",
                               width=12,
                               command=self.delete_all)
        delete_btn.place(x=825, y=90)

        img_label = tk.Label(lower_frame,
                             background="white",
                             image=self.dark_image)
        img_label.place(x=955, y=45)
        img_label.bind('<Button-1>', lambda x: self.dark_screen(lower_frame))

    def comparisons_info(self, comp_value):
        self.canvas.create_text(20,
                                500,
                                anchor="sw",
                                text="Comparisons",
                                fill=self.color)
        self.canvas.create_text(130,
                                500,
                                anchor="sw",
                                text=comp_value,
                                fill=self.color)

    def speed_values(self, speed):
        if speed == 1:
            return 0.4
        elif speed == 2:
            return 0.3
        elif speed == 3:
            return 0.2
        elif speed == 4:
            return 0.1
        else:
            return 0.08

    def dark_screen(self, lower_frame):
        if self.color == "black":
            self.canvas.config(bg="#666666")
            lower_frame.config(bg="#333333")
            self.canvas.update_idletasks()
            self.color = "white"
        else:
            self.canvas.config(bg="#f0ffff")
            lower_frame.config(bg="#1b3945")
            self.canvas.update_idletasks()
            self.color = "black"

    def select_algorithm(self, speed, option):
        if option == "Bubble sort":
            bubble_sort(self.speed_values(speed), self.random_list, 0,
                        self.draw_info, self.final_animation)

        elif option == "Selection sort":
            selection_sort(self.speed_values(speed), self.random_list, 0,
                           self.draw_info, self.final_animation)

        elif option == "Insertion sort":
            insertion_sort(self.speed_values(speed), self.random_list, 0,
                           self.draw_info, self.final_animation)

        elif option == "Cocktail shaker sort":
            cocktail_sort(self.speed_values(speed), self.random_list, 0,
                          self.draw_info, self.final_animation)

        elif option == "Shell sort":
            shell_sort(self.speed_values(speed), self.random_list, 0,
                       self.draw_info, self.final_animation)

    def final_animation(self, comp_value):
        for x in range(len(self.random_list)):
            time.sleep(0.03)
            self.draw_info(comp_value, [
                "#ff7f50" if i <= x else "#4ca3dd" if i == x + 1 else "#badd99"
                for i in range(len(self.random_list))
            ])
            #self.draw_info(["#f3d3a5" if i <= x else "#4e2c7f" if i == x+1 else "#badd99" fothemer i in range(len(self.random_list))])

    def delete_all(self):
        self.canvas.delete("all")

    def generate_info(self, min_value, max_value, algorithm):
        self.canvas.delete("all")
        self.random_list.clear()

        if min_value > max_value:
            mBox.showerror("ERROR", "Value error")
            return

        for i in range(24):
            number = random.randint(min_value, max_value)
            self.random_list.append(number)

        max_value = max(self.random_list)
        temp_list = []

        for i in self.random_list:
            height_value = int(i * 450 / max_value)  #max_value = 450  -> i?

            if height_value <= 9:
                temp_list.append((i, 9))
                continue

            temp_list.append((i, height_value))  #[(1, 10), (32, 300)]

        self.random_list = temp_list
        print(self.random_list)

        return self.draw_info(
            0, ["#ffa500" for i in range(len(self.random_list))])

    def draw_info(self, comp_value, color):
        self.canvas.delete("all")
        self.comparisons_info(comp_value)
        x = 20
        y = 50
        for key, value in enumerate(self.random_list):
            self.canvas.create_rectangle(x, value[1], y, 10, fill=color[key])
            self.canvas.create_text(x,
                                    value[1] + 20,
                                    anchor="sw",
                                    text=value[0],
                                    fill=self.color)
            x += 40
            y += 40

        self.window.update_idletasks()
Exemplo n.º 24
0
def load_editor():

    root = Tk()
    global path
    path = False

    def dark_mode():
        root.configure(background='#4d4d4d')
        my_txt.config(background='#2e2e2e', foreground="#ccfcff")
        status_bar.config(background='#4d4d4d', foreground="#ccfcff")
        txt_scroll.config(background='#2e2e2e')
        my_menu.config(background='#2e2e2e', foreground="#ccfcff")
        edit_menu.config(background='#2e2e2e', foreground="#ccfcff")
        export_menu.config(background='#2e2e2e', foreground="#ccfcff")
        file_menu.config(background='#2e2e2e', foreground="#ccfcff")
        theme_menu.config(background='#2e2e2e', foreground="#ccfcff")

    def light_mode():
        root.configure(background='white')
        my_txt.config(background='white', foreground="black")
        status_bar.config(background='white', foreground="black")
        txt_scroll.config(background='white')
        my_menu.config(background='white', foreground="black")
        edit_menu.config(background='white', foreground="black")
        export_menu.config(background='white', foreground="black")
        file_menu.config(background='white', foreground="black")
        theme_menu.config(background='white', foreground="black")

    def open_file():
        my_txt.delete("1.0", END)
        file = filedialog.askopenfilename(
            initialdir="C:/",
            filetypes=(('Text Files', '*.txt'), ('HTML Files', '*.html'),
                       ('Python Files', '*.py'), ('All Files', '*.*')),
            title="Open file")
        name = file
        status_bar.config(text='Opened        ')

        root.title(f'{name} - Scribble Editor')
        global path
        if file:
            global path
            path = file

        file = open(file, "r")
        stuff = file.read()
        my_txt.insert(END, stuff)
        file.close()

    def save_as():
        global path
        file = filedialog.asksaveasfilename(
            initialdir="C:/",
            filetypes=(('Text Files', '*.txt'), ('HTML Files', '*.html'),
                       ('Python Files', '*.py'), ('All Files', '*.*')))
        name = file
        path = file
        status_bar.config(text='Saved        ')
        # name = name.replace("C:/scribble","")
        root.title(f'{name} - Scribble Editor')
        file = open(file, 'w')
        file.write(my_txt.get(1.0, END))
        file.close()

    def pdf():
        #root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='yes.png'))
        user_name = os.getlogin()
        if path == False:
            USER_INP = simpledialog.askstring(title="EXPORT To PDF",
                                              prompt="Enter File name of PDF:")

            #root.iconbitmap("icon1.ico")
            pdf = FPDF()
            pdf.add_page()
            pdf.set_font("Arial", size=15)
            f = my_txt.get(1.0, END)
            pdf.cell(200, 10, txt=f, ln=1, align='L')
            s = "C:/Users/" + str(user_name) + "/Desktop/" + str(
                USER_INP) + ".pdf"
            my_txt.insert(END, pdf.output(s))
            status_bar.config(text='Pdf created at ' + s)

        else:
            USER_INP = simpledialog.askstring(title="EXPORT To PDF",
                                              prompt="Enter File name of PDF:")
            pdf = FPDF()
            pdf.add_page()
            pdf.set_font("Arial", size=15)
            f = open(path, "r")
            for x in f:
                pdf.cell(200, 10, txt=x, ln=1, align='C')
            s = "C:/Users/" + str(user_name) + "/Desktop/" + str(
                USER_INP) + ".pdf"
            my_txt.insert(END, pdf.output(s))
            status_bar.config(text='Pdf created at ' + s)

    def save():
        global path
        if path:
            file = open(path, 'w')
            file.write(my_txt.get(1.0, END))
            name = file
            status_bar.config(text='Saved        ')
            # name = name.replace("C:/scribble","")
            root.title(f'{name} - Scribble Editor')
            file.close()
        else:
            save_as()

    def choose_color():
        color_code = colorchooser.askcolor(title="Choose color")
        my_txt.config(foreground=color_code[1])

    def say_out():

        engin = pyttsx3.init()
        voices = engin.getProperty('voices')
        engin.setProperty('voice', voices[1].id)
        engin.setProperty('rate', 175)
        engin.say(my_txt.get(1.0, END))
        engin.runAndWait()

    def end_task():
        pass

    # window configuration
    root.title("Scribble Editor")
    root.iconbitmap('icon1.ico')

    #root.geometry("1366x768")
    root.configure(background='white')
    app_width = 1366
    app_height = 768

    win_width = root.winfo_screenwidth()
    win_height = root.winfo_screenheight()

    x = (win_width / 2) - (app_width / 2)
    y = (win_height / 2) - (app_height / 2)

    root.geometry(f"{app_width}x{app_height}+{int(x)}+{int(y)}")

    my_frm_format = Frame(root)
    my_frm_format.pack(anchor=NW, fill=X)

    photo = PhotoImage(file=r"clipart891338.png")
    photo1 = photo.subsample(1, 1)

    photo2 = PhotoImage(file=r"59377.png")
    photo3 = photo2.subsample(1, 1)

    photo4 = PhotoImage(file=r"under.png")
    photo5 = photo4.subsample(1, 1)

    ttk.Label(my_frm_format, text="Font :",
              font=("Consolas", 10)).pack(side=LEFT, padx=5)
    n_font_style = StringVar()
    n_font_size = IntVar()
    Font_Select = ttk.Combobox(my_frm_format,
                               width=20,
                               textvariable=n_font_style,
                               state="readonly")

    # Adding combobox drop down list
    Font_Select['values'] = (
        ' Times New Roman',
        ' Arial',
        ' Arial Black',
        ' Helvatica',
        ' Ink Free',
        ' Courier New',
        ' Lucida Console',
        ' Impact',
        ' Segoe Print',
        ' Yu Gothic UI',
        ' Comic Sans MS',
        ' Calibri',
    )

    Font_Select.pack(side=LEFT, padx=5)
    Font_Select.current()
    a = Font_Select.get()

    Font_Size = ttk.Combobox(my_frm_format, width=2, textvariable=n_font_size)

    # Adding combobox drop down list
    Font_Size['values'] = (9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36,
                           48, 72)

    Font_Size.pack(side=LEFT, padx=5)
    Font_Size.current()

    bold = Button(my_frm_format, borderwidth=0, image=photo1)
    bold.pack(side=LEFT, padx=5)

    italics = Button(my_frm_format, borderwidth=0, image=photo3)
    italics.pack(side=LEFT, padx=5)

    underline = Button(my_frm_format, borderwidth=0, image=photo5)
    underline.pack(side=LEFT, padx=5)

    color_piker = Button(my_frm_format,
                         borderwidth=1,
                         text="Text Colour ▼",
                         command=choose_color)
    color_piker.pack(side=LEFT, padx=5)

    say = Button(my_frm_format,
                 borderwidth=1,
                 text="Speak Out Loud ",
                 command=say_out)
    say.pack(side=LEFT, padx=5)

    end_say = Button(my_frm_format, borderwidth=1, text="||", command=end_task)
    end_say.pack(side=LEFT, padx=5)

    # frame initialization
    my_frm = Frame(root)
    my_frm.pack(pady=5)

    # scroll bar
    txt_scroll = Scrollbar(my_frm)
    txt_scroll.pack(side=RIGHT, fill=Y)

    # text area
    my_txt = Text(my_frm,
                  width=150,
                  height=30,
                  font=('Consolas', 16),
                  selectbackground="#ff564a",
                  selectforeground="white",
                  undo=True,
                  yscrollcommand=txt_scroll.set,
                  borderwidth="0")
    my_txt.pack()

    # menu initialization
    my_menu = Menu(root)
    root.config(menu=my_menu)

    # file menu
    file_menu = Menu(my_menu, tearoff=False, font=('Consolas', 11))
    my_menu.add_cascade(label="File", menu=file_menu)
    file_menu.add_command(label="Open               Ctr+O", command=open_file)
    file_menu.add_command(label="Save               Ctr+S", command=save)
    file_menu.add_command(label="Save As      Ctr+Shift+S", command=save_as)
    file_menu.add_separator()
    file_menu.add_command(label="Exit", command=root.quit)

    # edit menu
    edit_menu = Menu(my_menu, tearoff=False, font=('Consolas', 11))
    my_menu.add_cascade(label="Edit", menu=edit_menu)
    edit_menu.add_command(
        label="Cut",
        accelerator="Ctrl+X",
        command=lambda: my_txt.focus_get().event_generate('<<Cut>>'))
    edit_menu.add_command(
        label="Copy ",
        accelerator="Ctrl+C",
        command=lambda: my_txt.focus_get().event_generate('<<Copy>>'))
    edit_menu.add_command(
        label="Paste",
        accelerator="Ctrl+V",
        command=lambda: my_txt.focus_get().event_generate('<<Paste>>'))
    edit_menu.add_separator()
    edit_menu.add_command(label="Undo    Ctr+Z", command=my_txt.edit_undo)
    edit_menu.add_command(label="Redo    Ctr+Y", command=my_txt.edit_redo)

    # export menu
    export_menu = Menu(my_menu, tearoff=False, font=('Consolas', 11))
    my_menu.add_cascade(label="Export", menu=export_menu)
    export_menu.add_command(label="Export As PDF", command=pdf)

    # themes
    theme_menu = Menu(my_menu, tearoff=False, font=('Consolas', 11))
    my_menu.add_cascade(label="Theme", menu=theme_menu)
    theme_menu.add_command(label="Dark Mode", command=dark_mode)
    theme_menu.add_command(label="Light Mode", command=light_mode)

    # status bar
    status_bar = Label(root, text='Ready         ', anchor=E)
    status_bar.pack(fill=X, side=BOTTOM, ipady=5)

    # config scroll bar
    txt_scroll.config(command=my_txt.yview)

    root.mainloop()
Exemplo n.º 25
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        self.initUI()

        
    def initUI(self):
      
        self.parent.title("EGUANA")
        self.style = ttk.Style()        
        self.style.theme_use("alt")        
        
        self.photoName = "eguana.gif"
        self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46')

        self.frame.pack(fill=BOTH, expand=True)        
        self.pack(fill=BOTH, expand=True)
        
        self.setupMenuBar()
        self.setupTopBar()  
        
    def setupMenuBar(self):
        
        self.menubar = EguanaMenu(self.parent,self)
        self.parent.config(menu=self.menubar)

    def setupTopBar(self):
        
        self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory)
        self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2)
        
        self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory);
        self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2)

        self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2)
        self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2)
        self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2)
        self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2)
        self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2)
        self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2)

        self.openButton3D.bind('<Motion>',self.cursorPosition)
        self.openButton2D.bind('<Motion>',self.cursorPosition)

        self.photo = PhotoImage(file="eguana.gif")
        self.photo = self.photo.subsample(2);
        self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0)
        self.photo_label.configure(bg='#FADC46')
        
        self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2)
        
        self.photo_label.image = self.photo
    
    
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.columnconfigure(2, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.rowconfigure(2, weight=1)
        
    def askDirectory(self):

        dirStr = filedialog.askdirectory()
        
        if len(dirStr):
            self.openButton3D.destroy()
            self.openButton2D.destroy()
            self.p1Button.destroy()
            self.p2Button.destroy()
            self.p3Button.destroy()
            self.p4Button.destroy()
            self.p5Button.destroy()
            self.p6Button.destroy()

            self.menubar.entryconfigure('Filter', state = 'active')
            self.photo_label.destroy()

            dirStr = 'Input Path : '+dirStr
            
            
            self.frame.grid_forget()
            
           

            self.infoFrame = Frame(self.frame, relief=FLAT, bg='#FADC46')
            self.infoFrame.grid(row=0,column=0,columnspan=3, sticky=N+S+E+W,padx=2,pady =2)
               
        
            self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT)
            self.directoryLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.directoryLabel.config(text=dirStr)
            
        
            self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory)
            self.outputDirButton.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            
            
            self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter)
            self.filterButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
           
           
            self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E)
            self.trialLabel.grid(row=3,column=0, sticky=N+S+E+W,padx=2,pady =2)


            vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
            self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd)
            self.trialEntry.grid(row=3,column=1, sticky=N+S+E+W,padx=2,pady =2)

            self.infoFrame.columnconfigure(0, weight=1)
            self.infoFrame.columnconfigure(1, weight=1)
            self.infoFrame.rowconfigure(0, weight=1)
            self.infoFrame.rowconfigure(1, weight=1)
            self.infoFrame.rowconfigure(2, weight=1)
            self.infoFrame.rowconfigure(3, weight=1)

            self.showPlotTools()

    def validate(self, action, index, value_if_allowed,
                       prior_value, text, validation_type, trigger_type, widget_name):
                           
        if len(value_if_allowed)==0 : 
            return True
        
        if text in '0123456789.-+ ':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
            
    def askOutputDirectory(self):
        dirStr = filedialog.askdirectory()
        if len(dirStr):
            dirStr = 'Output Path : '+dirStr
            self.outputDirButton.destroy()
            self.outputDirLabel = Label(self.infoFrame, relief=FLAT)
            self.outputDirLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.outputDirLabel.config(text=dirStr)

            

    def showPlotTools(self):        
        
        f2= Frame(self.frame, relief=FLAT,bg='#FADC46')
        f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10)
        
        b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1))
        b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5)
        
        b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2))
        b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5)
        
        b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3))
        b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4))
        b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5))
        b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5)

        b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6))
        b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        f2.columnconfigure(0, weight=1)
        f2.columnconfigure(1, weight=1)
        f2.columnconfigure(2, weight=1)

        f2.rowconfigure(0, weight=1)
        f2.rowconfigure(1, weight=1)
       
       
    def plotButtonPressed(self,number):
        trialNum = self.trialEntry.get()
        
        try:
            trialNum = float(trialNum)
            
            
            if trialNum < 16 and trialNum > 0:
                self.plotFigure(number)
                return True             
            else:
                messagebox.showerror(
                    "Trial Number Error",
                    "The trial number is out of range"
                    )     
                return False
        except ValueError:
            messagebox.showerror(
                "Trial Number Error",
                "Error with the trial number"
            )  
            return False
            
    def plotFigure(self,number):
        m =  CoilNumDialog(self.frame)
        if m.isSet():
            print(m.getValues())
        
    def selectFilter(self):        
        self.top = FilterPopup(self);

    def speech3DButtonPressed(self):
        self.menubar.filterSelected(0)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : speech3D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : speech3D",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def speech2DButtonPressed(self):
        self.menubar.filterSelected(1)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : speech2D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : speech2D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def swallow3DButtonPressed(self):
        self.menubar.filterSelected(2)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : swallow3D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : swallow3D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def swallow2DButtonPressed(self):
        self.menubar.filterSelected(3)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : swallow2D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : swallow2D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()

    def changeImage(self):
        self.photo = PhotoImage(file=self.photoName)
        self.photo = self.photo.subsample(2);
        self.photo_label.image = self.photo  
        self.photo_label.config(image=self.photo)
        
        
        
    def cursorPosition(self,event):       
        if event.widget ==  self.openButton3D:
            if self.photoName == "eguana2.gif":
                self.photoName = "eguana.gif"
                self.changeImage()
                
        elif event.widget ==  self.openButton2D:
            if self.photoName == "eguana.gif":
                self.photoName = "eguana2.gif"
                self.changeImage()
Exemplo n.º 26
0
OptionMenu(root, v, *output).grid(row=1,column=4)



Label(root, text="Select format:", bg=bg, fg=text_color, font=font).grid(row=4, column=3, padx=10, pady=10)
types = ["Video","Audio"]
extension = StringVar()
extension.set(types[0])

OptionMenu(root, extension, *types).grid(row=4,column=4)

connection = sqlite3.connect("videodata.db")
db = connection.cursor()

poweroff_image = PhotoImage(file="images/poweroff.png")
poweroff_image = poweroff_image.subsample(2, 2) 


Button(root, text="Download!", command=lambda: download(), fg=bg).grid(row=7, column=3, padx=10, pady=10)
Button(root,text="Download history", command=lambda: history(), fg=bg).grid(row=7, column=4, padx=10, pady=10)
Button(root, image=poweroff_image, command=lambda: myexit(), fg=bg).grid(row=8, column=2, padx=10, pady=10)

def download():
    link = linkentry.get()
    title = titleentry.get()
    ex = extension.get()
  
    if len(link) == 0:
        messagebox.showwarning("Warning", "Insert a link!")
        return
Exemplo n.º 27
0
    def __init__(self, titulo: str, mensagem: str):

        # Basic Config
        root = Tk()
        root.rowconfigure(1, weight=1)
        root.grid_columnconfigure(1, weight=1)
        root.title(titulo)
        root.configure(bg="#fefefe")
        img_icone = PhotoImage(file='imagens/error_icon.png')
        img_icone = img_icone.subsample(2, 2)
        root.call('wm', 'iconphoto', root._w, img_icone)

        # Image and Message error
        fr_base = Frame(root, bg="#fefefe", pady=10, padx=10)
        fr_base.rowconfigure(1, weight=1)
        fr_base.grid_columnconfigure(2, weight=1)
        fr_base.grid(row=1, column=1, sticky=NSEW)

        lb_image = Label(fr_base, image=img_icone, bg="#fefefe")
        lb_image.grid(row=1, column=1)

        txt_message = Text(fr_base, height=4, bg="#fefefe", bd=0)
        txt_message.insert(0.0, mensagem)
        txt_message.grid(row=1, column=2, sticky=NSEW)

        # Buttons, copy and report
        fr_butons = Frame(
            root,
            bg="#fefefe",
            pady=5,
            padx=10,
        )
        fr_butons.rowconfigure(1, weight=1)
        fr_butons.grid_columnconfigure(2, weight=1)
        fr_butons.grid(row=2, column=1, sticky='ew')

        # Button Copy
        fr_copy = Frame(fr_butons,
                        bg='#ffffff',
                        highlightthickness=1,
                        highlightbackground="#ff2660",
                        highlightcolor="green",
                        bd=0)
        fr_copy.grid(row=2, column=2, sticky='e')

        btn_copy = Button(fr_copy,
                          text="Copiar Mensagem",
                          bg='#ffffff',
                          fg='#ff2660',
                          relief='flat',
                          activebackground="#fefefe",
                          activeforeground="#ff2660",
                          highlightthickness=5,
                          bd=0)
        btn_copy.grid(row=1, column=1, sticky='e')

        # white space
        fr_white = Frame(fr_butons, bg="#fefefe", width=5)
        fr_white.grid(row=2, column=3)

        # Button Report
        fr_report = Frame(fr_butons,
                          bg='#ffffff',
                          highlightthickness=1,
                          highlightbackground="#ff2660",
                          highlightcolor="green",
                          bd=0)
        fr_report.grid(row=2, column=5, sticky='e')

        btn_report = Button(fr_report,
                            text="Reportar Bug",
                            bg='#ff2660',
                            fg='#ffffff',
                            relief='flat',
                            activebackground="#ff2660",
                            activeforeground="#ffffff",
                            highlightthickness=5,
                            bd=0)
        btn_report.grid(row=1, column=1, sticky='e')

        root.mainloop()
Exemplo n.º 28
0
Arquivo: tools.py Projeto: zhenyat/Rob
def get_gif_logo(file, factor):
    logo = PhotoImage(file=file)
    return logo.subsample(factor)
Exemplo n.º 29
0
class EguanaGUI(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        self.initUI()

        # if not EguanaInit.eguana_root_dir_exists():
        #     EguanaInit.create_eguana_root_dir()
        
    def initUI(self):
      
        self.parent.title("EGUANA")
        self.style = ttk.Style()        
        self.style.theme_use("alt")        
        
        self.photoName = "eguana.gif"
        self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46')

        self.frame.pack(fill=BOTH, expand=True)        
        self.pack(fill=BOTH, expand=True)
        
        self.setupMenuBar()
        self.setupTopBar()  
        
    def setupMenuBar(self):
        
        self.menubar = EguanaMenu(self.parent,self)
        self.parent.config(menu=self.menubar)

    def setupTopBar(self):
        
        self.supportedDevices = []        
        
        for fileName in [name for name in os.listdir('./machineConfig') if os.path.isfile('./machineConfig/' + name) and not name == 'eguanaMachineConfig.py' and  name.endswith('.py')]:
        # try:{
            components = fileName.split('.')
            fileName = components[0]
            className = fileName[0].upper() + fileName[1:]
            try:
                module = __import__("machineConfig."+fileName,fromlist=["machineConfig."])                        
                classVar = getattr(module,className)
            except:
                continue
            self.supportedDevices.append(classVar())
            # except:
            #     pass

        self.selectMachineFrame = Frame(self.frame,relief=FLAT,bg='#FADC46')
        self.selectMachineFrame.pack(fill=BOTH,expand=True)
        self.setupSelectMachineButtons()
        
    def setupSelectMachineButtons(self):

        numDevices = len(self.supportedDevices)
        numColumns = 3
        numRows = math.ceil((numDevices+1)/3)
        
        self.photo = PhotoImage(file="eguana.gif")
        self.photo = self.photo.subsample(2);
        self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0)
        self.photo_label.configure(bg='#FADC46')
        self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2)
        self.photo_label.image = self.photo        
        
        index = 0
        for i in range(numRows):
            for j in range(numColumns):
                
                if not(j == 1 and i == int(numRows/2)) and (index < numDevices):
                    device = self.supportedDevices[index]
                    b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device))
                    b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2)
                    index += 1

            
        for i in range(numRows):
            self.selectMachineFrame.rowconfigure(i,weight=1)
         
        for i in range(numColumns):
            self.selectMachineFrame.columnconfigure(i,weight=1)
            

    def machineButtonPressed(self,inputDevice):

        dirStr = filedialog.askdirectory()
        
        if len(dirStr) and inputDevice.isDirectoryValid(dirStr):

            inputDevice.setDirPath(dirStr)
            EguanaModel().machine = inputDevice

            self.selectMachineFrame.destroy()

            self.menubar.inputSelected()

            self.photo_label.destroy()

            dirStr = 'Input Path : '+dirStr


            
            self.selectPlotFrame = Frame(self.frame, relief=FLAT,bg='#FADC46')
            self.selectPlotFrame.pack(fill=BOTH,expand=True)
            self.selectPlotFrame.rowconfigure(0,weight=1)
            self.selectPlotFrame.rowconfigure(1,weight=2)
            self.selectPlotFrame.columnconfigure(0,weight=1)

            self.infoFrame = Frame(self.selectPlotFrame, relief=FLAT, bg='#FADC46')
            self.infoFrame.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2)
               
            
            self.machineNameLabel = Label(self.infoFrame, text=inputDevice.name,relief=FLAT)
            self.machineNameLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)

            self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT)
            self.directoryLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.directoryLabel.config(text=dirStr)
            
        
            self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory)
            self.outputDirButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            
            
            self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter)
            self.filterButton.grid(row=3,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
           
           
            self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E)
            self.trialLabel.grid(row=4,column=0, sticky=N+S+E+W,padx=2,pady =2)


            vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
            self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd)
            self.trialEntry.grid(row=4,column=1, sticky=N+S+E+W,padx=2,pady =2)

            self.infoFrame.columnconfigure(0, weight=1)
            self.infoFrame.columnconfigure(1, weight=1)
            self.infoFrame.rowconfigure(0, weight=1)
            self.infoFrame.rowconfigure(1, weight=10)
            self.infoFrame.rowconfigure(2, weight=10)
            self.infoFrame.rowconfigure(3, weight=10)
            self.infoFrame.rowconfigure(4, weight=10)

            self.showPlotTools()

    def validate(self, action, index, value_if_allowed,
                       prior_value, text, validation_type, trigger_type, widget_name):
                           
        if len(value_if_allowed)==0 : 
            return True
        
        if text in '0123456789.-+ ':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
            
    def askOutputDirectory(self):
        dirStr = filedialog.askdirectory()
        if len(dirStr):
            dirStr = 'Output Path : '+dirStr
            self.outputDirButton.config(text=dirStr)

            

    def showPlotTools(self):        
        
        
        f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46')
        f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10)
        
        b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1))
        b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2))
        b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5)
        
        b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3))
        b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4))
        b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5))
        b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5)

        b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6))
        b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        
    
        b1.config(state=EguanaModel().machine.plot3DKButtonState)
        b2.config(state=EguanaModel().machine.plot3DDstButtonState)
        b3.config(state=EguanaModel().machine.plot3DDpButtonState)
        b4.config(state=EguanaModel().machine.plot2DKButtonState)
        b5.config(state=EguanaModel().machine.plot2DDstButtonState)
        b6.config(state=EguanaModel().machine.plot2DDpButtonState)

        f2.columnconfigure(0, weight=1)
        f2.columnconfigure(1, weight=1)
        f2.columnconfigure(2, weight=1)

        f2.rowconfigure(0, weight=1)
        f2.rowconfigure(1, weight=1)
       
    def plotButtonPressed(self,number):
        trialNum = self.trialEntry.get()
        
        try:
            trialNum = int(trialNum)
            
            print(EguanaModel().machine.ifTrialExists(trialNum))
            if EguanaModel().machine.ifTrialExists(trialNum):
                self.plotFigure(number)
                return True             
            else:
                messagebox.showerror(
                    "Trial Number Error",
                    "The trial doesn't exist"
                    )     
                return False
        except ValueError:
            messagebox.showerror(
                "Trial Number Error",
                "Error with the trial number"
            )  
            return False
            
    def plotFigure(self,number):
        m =  CoilNumDialog(self.frame)
        if m.isSet():
            print(m.getValues())
            EguanaModel().machine.getDataForTrialNumber(number)
        
    def selectFilter(self):        
        ffPopup = FilterFunctionPopup(self)
        if ffPopup.selectedFilter is not None:
            EguanaModel().filterFunction = ffPopup.selectedFilter
            ftPopup = FilterTypePopup(self,ffPopup.selectedFilter)
            if (ftPopup.selectedHeadFilterType is not None) and (ftPopup.selectedHeadFilterType is not None):
                self.menubar.setSelectedFilters(ffPopup.selectedFilter,ftPopup.selectedHeadFilterType,ftPopup.selectedJawFilterType)
                EguanaModel().filterTypeHead = ftPopup.selectedHeadFilterType
                EguanaModel().filterTypeJaw = ftPopup.selectedJawFilterType
                EguanaModel().filterFunction = ffPopup.selectedFilter
                buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffPopup.selectedFilter.name,ftPopup.selectedJawFilterType.name, ftPopup.selectedHeadFilterType.name)
                self.filterButton.config(text=buttonText)


    def updateSelectedFilters(self,ffName,ftHeadName,ftJawName): 
        buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffName,ftHeadName,ftJawName)
        self.filterButton.config(text=buttonText)

    def changeImage(self):
        self.photo = PhotoImage(file=self.photoName)
        self.photo = self.photo.subsample(2);
        self.photo_label.image = self.photo  
        self.photo_label.config(image=self.photo)
        
        
        
    def cursorPosition(self,event):       
        if event.widget ==  self.openButton3D:
            if self.photoName == "eguana2.gif":
                self.photoName = "eguana.gif"
                self.changeImage()
                
        elif event.widget ==  self.openButton2D:
            if self.photoName == "eguana.gif":
                self.photoName = "eguana2.gif"
                self.changeImage()
Exemplo n.º 30
0
class Idioma():
    def __init__(self, tela, design, idioma, interface_idioma, icon):
        self.icon = icon
        self.idioma = idioma
        self.interface_idioma = interface_idioma
        self.design = design
        self.tela = tela
        self.base = "imagens/"
        self.tp_interface_idioma = None
        self.bt_idioma = None
        self.lb1 = None
        self.dic_imgs = None

    def selecionar_idioma(self, dic_imgs):
        self.dic_imgs = dic_imgs
        self.tp_interface_idioma = Toplevel(self.tela,
                                            self.design.dic["idioma_tp"])
        self.tp_interface_idioma.withdraw()

        self.tp_interface_idioma.tk.call('wm', 'iconphoto',
                                         self.tp_interface_idioma._w,
                                         self.icon)
        self.tp_interface_idioma.grid_columnconfigure(1, weight=1)
        self.tp_interface_idioma.title('Escolha de Idioma')

        self.fr_top_idioma = Frame(self.tp_interface_idioma,
                                   self.design.dic["idioma_fr"])
        self.fr_top_idioma.grid_columnconfigure(1, weight=1)
        self.fr_top_idioma.grid(row=1, column=1, sticky=NSEW)

        self.lb1 = Label(
            self.fr_top_idioma,
            self.design.dic['idioma_lb'],
            text=self.interface_idioma["texto_atualizacao"][self.idioma])
        self.lb1.grid(row=1, column=1, sticky=NSEW)

        self.fr_idionas = Frame(self.tp_interface_idioma,
                                self.design.dic['idioma_fr2'])
        self.fr_idionas.grid(row=2, column=1)

        # Carregar as imagens
        self.imgs = []
        for k, v in self.dic_imgs.items():
            self.imgs.append(PhotoImage(file=self.base + v))

        # Carregar os botões
        x = 0
        self.lista_botoes = []
        for k, v in self.dic_imgs.items():

            if self.idioma == k:
                self.fr_bt = Frame(self.fr_idionas,
                                   self.design.dic['idioma_fr3'])
                self.bt_bt = Button(
                    self.fr_bt,
                    self.design.dic['idioma_bt'],
                    relief=GROOVE,
                    image=self.imgs[x],
                )
                self.lb_bt = Label(
                    self.fr_bt,
                    self.design.dic['idioma_lb2'],
                    relief=GROOVE,
                    text=k,
                )
            else:
                self.fr_bt = Frame(self.fr_idionas,
                                   self.design.dic['idioma_fr4'])
                self.bt_bt = Button(
                    self.fr_bt,
                    self.design.dic['idioma_bt2'],
                    relief=GROOVE,
                    image=self.imgs[x],
                )
                self.lb_bt = Label(self.fr_bt,
                                   self.design.dic['idioma_lb3'],
                                   relief=GROOVE,
                                   text=k)

            self.bt_bt[
                "command"] = lambda bt_bt=self.bt_bt, dic=self.dic_imgs: self.marcar_opcao_idioma(
                    bt_bt, dic)

            self.lista_botoes.append([self.fr_bt, self.bt_bt, self.lb_bt])

            self.fr_bt.grid(row=1, column=x)
            self.bt_bt.grid(row=1, column=x)
            self.lb_bt.grid(row=2, column=x)

            x += 1

        self.tp_interface_idioma.update()

        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        j_heigth = self.tp_interface_idioma.winfo_screenmmheight()
        j_width = self.tp_interface_idioma.winfo_screenmmwidth()

        self.tp_interface_idioma.geometry("+{}+{}".format(
            j_width, j_heigth, int(t_width / 2 - (j_width / 2)),
            int(t_heigth / 2 - (j_heigth / 2))))
        self.tp_interface_idioma.deiconify()

    def marcar_opcao_idioma(self, botao, dic_imgs):
        self.dic_imgs = dic_imgs
        self.tp_interface_idioma.withdraw()

        for bandeira in self.lista_botoes:
            if bandeira[1] == botao:
                self.idioma = bandeira[2]["text"]

                self.ic_idioma = PhotoImage(
                    file="imagens/{}".format(self.dic_imgs[self.idioma]))
                self.ic_idioma = self.ic_idioma.subsample(4, 4)
                funcoes.arquivo_de_configuracoes_interface(
                    "idioma", self.idioma)

                #self.lb1.configure(text=self.interface_idioma["texto_atualizacao"][self.idioma])

                self.tp_interface_idioma.destroy()
                del bandeira

                self.selecionar_idioma(self.dic_imgs)

            else:
                pass
        return 10, 20
Exemplo n.º 31
0
current_sound_static.grid(row=0, column=1)
current_track.grid(row=1, column=1)

#buttons on second row
BUTTON_H = 250
BUTTON_W = 225
back_arrow_img = PhotoImage(file=os.path.join(cwd, 'images', 'back_arrow.png'))
forward_arrow_img = PhotoImage(
    file=os.path.join(cwd, 'images', 'forward_arrow.png'))

#resize images to fit in button
IMAGE_H = 512
IMAGE_W = 512
REDUCER_H = int(IMAGE_H / BUTTON_H) + 1
REDUCER_W = int(IMAGE_W / BUTTON_W) + 1
back_arrow_img = back_arrow_img.subsample(REDUCER_H, REDUCER_W)
forward_arrow_img = forward_arrow_img.subsample(REDUCER_H, REDUCER_W)

back_arrow_btn = Button(
    window,
    image=back_arrow_img,
    height=BUTTON_H,
    width=BUTTON_W,
    command=lambda: btn_preset_change(current_track, soundfonts, current, -1,
                                      client_connection))
forward_arrow_btn = Button(
    window,
    image=forward_arrow_img,
    height=BUTTON_H,
    width=BUTTON_W,
    command=lambda: btn_preset_change(current_track, soundfonts, current, 1,
    def __init__(self):
        super().__init__()

        self.title('Virtual Painter')
        
        self.isrunning = False
        self.width = self.winfo_screenwidth()
        self.height = self.winfo_screenheight() - 100
        
        self.canvas_img = np.ones((self.height,self.width,3),dtype=np.int8) * 255
        self.color = (0,0,0)
        self.mcolor = (0,0,0)
        self.xp = self.yp = ''
        self.thickness = 5
        self.drawhand = False

        # * Top Label
        l1 = Label(self,borderwidth=2, relief="solid")
        l1.pack(fill='x',expand=True)

        # * Button for Save the Canvas
        # Creating a photoimage object to use image
        save_img = PhotoImage(file = r"./Assets/save.png")
        # Resizing image to fit on button
        save_img = save_img.subsample(20, 20)
        # Button Creation
        Button(l1,image=save_img, compound='left', command=self.save_canvas).pack(side='left')


        # * Button for Color Changer
        # Creating a photoimage object to use image
        color_bucket_img = PhotoImage(file = r"./Assets/paint-bucket.png")
        # Resizing image to fit on button
        color_bucket_img = color_bucket_img.subsample(20, 20)
        # Button Creation
        self.color_bucket_bt = Button(l1, image=color_bucket_img, compound='left', bg='#000000', command=self.choose_color)
        self.color_bucket_bt.pack(side='left',padx=10)

        # * Button for Pen
        # Creating a photoimage object to use image
        pen_img = PhotoImage(file = r"./Assets/pen.png")
        # Resizing image to fit on button
        pen_img = pen_img.subsample(20, 20)
        # Button Creation
        Button(l1,image=pen_img, compound='left',command=self.pen).pack(side='left',padx=5)

        # * Button for Eraser
        # Creating a photoimage object to use image
        eraser_img = PhotoImage(file = r"./Assets/eraser.png")
        # Resizing image to fit on button
        eraser_img = eraser_img.subsample(10, 10)
        # Button Creation
        Button(l1, image=eraser_img, compound='left', command=self.eraser).pack(side='left',padx=10)
        
        # Extra Gap
        Label(l1).pack(side='left',padx=15)

        # * Button for Clear the Canvas
        # Creating a photoimage object to use image
        clear_img = PhotoImage(file = r"./Assets/clear.png")
        # Resizing image to fit on button
        clear_img = clear_img.subsample(20, 20)
        # Button Creation
        Button(l1, image=clear_img, compound='left', command=self.clear).pack(side='left',padx=10)

        # Extra Gap
        Label(l1).pack(side='left',padx=15)

        # * Button for increase Pen Size
        # Creating a photoimage object to use image
        plus_img = PhotoImage(file = r"./Assets/plus.png")
        # Resizing image to fit on button
        plus_img = plus_img.subsample(20, 20)
        # Button Creation
        Button(l1, image=plus_img, compound='left', command=lambda: self.change_thicness(i=1)).pack(side='left')
        
        # * Pen Size Display
        self.brush_size = Label(l1,text=self.thickness,font=('',15))
        self.brush_size.pack(side='left',padx=5)

        # * Button for decrease Pen Size
        # Creating a photoimage object to use image
        minus_img = PhotoImage(file = r"./Assets/minus.png")
        # Resizing image to fit on button
        minus_img = minus_img.subsample(20, 20)
        # Button Creation
        Button(l1, image=minus_img, compound='left', command=lambda: self.change_thicness(i=-1)).pack(side='left')
        
        # * Start/Stop Button for detection
        self.command_bt = Button(l1,text='Strat',command=self.engine)
        self.command_bt.pack(side='right')

        # * Button to show hand Landmarks
        self.hand_bt = Button(l1,text='Show Hand',command=self.draw_hand)
        self.hand_bt.pack(side='right')
        
        # * Middle Frame
        frame = Frame(self)
        frame.pack(fill='both',expand=True)
        
        # * Image Canvas
        self.canvas = Canvas(frame,width=self.width,height=self.height)
        self.canvas.pack()

        # * Bottum Label
        self.l2 = Label(self,bg='#3e00ff',text='Not Started',font=('',18),fg='#d4087a',height=2)
        self.l2.pack(fill='x',expand=True)

        # * Key Bindings
        self.bind('<Control-s>',self.save_canvas)       # Key bind for saving canvas
        self.bind('<Control-C>',self.clear)             # Key bind for clean the canvas
        self.bind('<Control-h>',self.draw_hand)         # Key bind for Toggle display of hand Landmarks


        # * Main Loop
        self.mainloop()
Exemplo n.º 33
0
class Robot():
    """Documentation du robot
    image: stocke l'image du robot (doit etre de type .gif)
    coord_.: contient les coordonnées actuels du robot
    """

    def __init__(self, labyrinthe):
        # ------------ Coordonnées sur écran ------------
        self.coord_x = labyrinthe.robot_start_x * labyrinthe.largeur_carre
        self.coord_y = labyrinthe.robot_start_y * labyrinthe.hauteur_carre
        # ------------ Coordonnées logique ------------
        self.logic_coord_x = labyrinthe.robot_start_y
        self.logic_coord_y = labyrinthe.robot_start_x
        # ------------ Chargement des images ------------
        self.image_up = PhotoImage(file="up.gif")
        self.image_down = PhotoImage(file="down.gif")
        self.image_right = PhotoImage(file="right.gif")
        self.image_left = PhotoImage(file="left.gif")
        # ------------ Mise à l'échelle ------------
        self.displayimage_up = self.image_up.subsample(2, 2)
        self.displayimage_down = self.image_down.subsample(2, 2)
        self.displayimage_right = self.image_right.subsample(2, 2)
        self.displayimage_left = self.image_left.subsample(2, 2)
        # ------------ Création de l'image ------------
        self.display = labyrinthe.laby.create_image(self.coord_x, self.coord_y, anchor='nw', image=self.displayimage_up)
        self.ref_labyrinthe = labyrinthe
        # ------------ Variables pour l'animation de déplacement ------------
        self.anim_count = 0
        self.anim = False
        # ------------ Variables pour l'algorithme ------------
        self.direction_actuel = 'Up' # ATTENTION INUTILISE
        self.direction_ancienne = 'Up'

    def move(self, direction):
        if direction == 'Left':
            new_coord_x = self.logic_coord_x
            new_coord_y = self.logic_coord_y - 1
        if direction == 'Up':
            new_coord_x = self.logic_coord_x - 1
            new_coord_y = self.logic_coord_y
        if direction == 'Right':
            new_coord_x = self.logic_coord_x
            new_coord_y = self.logic_coord_y + 1
        if direction == 'Down':
            new_coord_x = self.logic_coord_x + 1
            new_coord_y = self.logic_coord_y

        if self.ref_labyrinthe.test_case_vide(new_coord_x, new_coord_y):
            self.logic_coord_x = new_coord_x
            self.logic_coord_y = new_coord_y
            self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre
            self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre
            self.animation(direction)

    def animation(self, direction):
        for i in range(1, 11):
            if direction == 'Up':
                self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_up)
                self.ref_labyrinthe.laby.move(self.display, 0, -4)
            if direction == 'Left':
                self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_left)
                self.ref_labyrinthe.laby.move(self.display, -4, 0)
            if direction == 'Down':
                self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_down)
                self.ref_labyrinthe.laby.move(self.display, 0, 4)
            if direction == 'Right':
                self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_right)
                self.ref_labyrinthe.laby.move(self.display, 4, 0)
            self.ref_labyrinthe.laby.update()
            time.sleep(0.025)
    
    def algo_droite(self):
        """ Le robot regarde toujours vers la droite afin de savoir s'il peut y aller en fonction
            de sa direction de base."""
        # Si il partait vers la haut
        if self.direction_ancienne == 'Up':
            # On regarde s'il peut maintenant tourner à droite (par rapport à l'écran)
            if self.ref_labyrinthe.test_case_vide(self.logic_coord_x + 1, self.logic_coord_y):
                # On peut aller à droite donc on y va
                self.logic_coord_x += 1
                self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre
                self.direction_ancienne = 'Right'
                self.animation('Up')
            # TODO: POUR LES 3 AUTRES RAJOUTER AUSSI LES TESTES
        # Si il partait vers le bas
        if self.direction_ancienne == 'Down':
            # On regarde s'il peut maintenant tourner à gauche (par rapport à l'écran)
            if self.ref_labyrinthe.test_case_vide(self.logic_coord_x - 1, self.logic_coord_y):
                self.logic_coord_x -= 1
                self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre
                self.direction_ancienne = 'Left'
                self.animation('Down')
        if self.direction_ancienne == 'Right':
            # On regarde s'il peut maintenant tourner vers le bas (par rapport à l'écran)
            if self.ref_labyrinthe.test_case_vide(self.logic_coord_x, self.logic_coord_y + 1):
                self.logic_coord_y += 1
                self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre
                self.direction_ancienne = 'Down'
                self.animation('Down')
        if self.direction_ancienne == 'Left':
            # On regarde s'il peut maintenant tourner vers le haut (par rapport à l'écran)
            if self.ref_labyrinthe.test_case_vide(self.logic_coord_x, self.logic_coord_y - 1):
                self.logic_coord_y -= 1
                self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre
                self.direction_ancienne = 'Up'
                self.animation('Down')
Exemplo n.º 34
0
class TeacherInterfaceGUI:
    """ Main GUI class """

    CURRENT_DIR = os.path.dirname(__file__)
    IMAGE_DIR = os.path.join(CURRENT_DIR, 'images')
    SCENARIOS_DIR = os.path.join(CURRENT_DIR, 'scenarios')

    INFORMATION_FILE = os.path.join(CURRENT_DIR, 'informationDBv3final.csv')
    SCENARIOS_FILE = os.path.join(SCENARIOS_DIR, 'scenarios.csv')

    scenario_obj = None

    def __init__(self, master):
        # customize root object
        master.title("Micro:Chem")
        master.set_theme("arc")
        master.minsize(1024, 648)
        master.configure(background='#f5f6f7')
        self.master = master

        self.add_styling()

        self.add_heading_area(master)

        nb = ttk.Notebook(master)
        self.add_main_page(nb)
        self.add_options_page(nb)
        self.add_scenarios_page(nb)
        nb.pack(expand=1, fill="both")

    def add_styling(self):
        """Add custom styling here"""
        style = ttk.Style()
        style.configure("Groove.TFrame", relief="groove")
        style.configure('Log.Treeview', rowheight=30)

    def add_heading_area(self, master):
        """Header area with logo"""
        self.header_im = PhotoImage(
            file=os.path.join(self.IMAGE_DIR, 'microchem_logo.png'))
        self.header_im = self.header_im.subsample(4, 4)
        self.heading = ttk.Label(master, image=self.header_im)
        self.heading.pack()

    def add_main_page(self, nb):
        """ Main tab has 
                - list of ElementBits and current element/compounds
                - information panel about selected elementbit
                - panel showing current reaction(s) 
                - panel with description for current scenario? """

        self.main_page = ttk.Frame(nb)

        self.add_element_bit_list_frame()
        self.add_reaction_frame()
        self.add_info_frame()

        nb.add(self.main_page, text='Main')

    def add_element_bit_list_frame(self):
        """ Frame contains
            - list of ElementBits and their current element/compounds """
        self.element_bit_list_frame = ttk.Frame(self.main_page,
                                                style="Groove.TFrame")

        self.element_bit_list_frame_label = ttk.Label(
            self.element_bit_list_frame, text="ElementBit List")
        self.element_bit_list_frame_label.pack(pady=10)

        self.element_bit_tree = ttk.Treeview(self.element_bit_list_frame,
                                             selectmode="browse")
        self.element_bit_tree['show'] = 'headings'  # hide empty first column
        self.element_bit_tree['columns'] = ('id', 'element', 'valence')

        self.element_bit_tree.column('id', width=100)
        self.element_bit_tree.heading('id', text='ElementBit ID')
        self.element_bit_tree.column('element', width=150)
        self.element_bit_tree.heading('element', text='Element/Compound')
        self.element_bit_tree.column('valence', width=50)
        self.element_bit_tree.heading('valence', text='Valence')

        self.element_bit_tree.pack()
        self.element_bit_tree.bind("<<TreeviewSelect>>",
                                   self.on_element_bit_tree_select)

        self.element_bit_list_frame.pack(side=LEFT,
                                         ipadx=10,
                                         fill="both",
                                         expand="false")

    def update_element_bit_list(self, new_list):
        """ update element bit list with new values stored in numpy ndarray
            array items are expected to have 'aliasID', 'chem_symbol' and 'valence' """

        # clear current tree
        for row in self.element_bit_tree.get_children():
            self.element_bit_tree.delete(row)

        # repopulate tree
        for item in new_list:
            item_values = " ".join([
                item['aliasID'].decode('UTF-8'),
                item['chem_symbol'].decode('UTF-8'),
                item['valence'].decode('UTF-8')
            ])
            self.element_bit_tree.insert('', 'end', values=item_values)

    def on_element_bit_tree_select(self, event):
        """ Get values from selection and update info frame """
        selection = self.element_bit_tree.selection()[0]
        item = self.element_bit_tree.item(selection)
        self.info_frame_update(
            item['values'][1])  # send chemical symbol to info panel

    def add_reaction_frame(self):
        """ Frame contains 
            - information about the current ongoing reaction(s)
            - log of past reactions? """
        self.reaction_frame = ttk.Frame(self.main_page,
                                        width=400,
                                        style="Groove.TFrame")

        self.reaction_frame_label = ttk.Label(self.reaction_frame,
                                              text="Reaction Panel")
        self.reaction_frame_label.pack(pady=10)

        self.current_reactions_frame = ttk.Frame(self.reaction_frame)
        self.current_reaction_label_string = StringVar()
        self.current_reaction_label_string.set('No reactions yet')
        self.current_reaction_label = Message(
            self.current_reactions_frame,
            textvariable=self.current_reaction_label_string,
            background="white",
            relief="raised",
            foreground="#535d6d",
            aspect=700)
        self.current_reaction_label.pack(ipady=10, padx=1, fill="x")
        self.current_reactions_frame.pack(padx=5,
                                          side=TOP,
                                          fill="both",
                                          expand="true")

        self.reaction_log_frame = ttk.Frame(self.reaction_frame,
                                            height="250",
                                            style="Groove.TFrame")
        self.reaction_log_frame_label = ttk.Label(self.reaction_log_frame,
                                                  text="Reaction Log")
        self.reaction_log_frame_label.pack(pady=10)

        self.reaction_log_tree = ttk.Treeview(self.reaction_log_frame,
                                              selectmode="browse",
                                              style="Log.Treeview")
        self.reaction_log_tree.pack(fill="x", padx=10, ipady=15)

        self.reaction_log_frame.pack(padx=5,
                                     pady=5,
                                     side=BOTTOM,
                                     fill="both",
                                     expand="false")
        self.reaction_log_frame.pack_propagate(0)

        self.reaction_frame.pack(side=LEFT, fill="both", expand="false")
        self.reaction_frame.pack_propagate(0)

    def trigger_reaction(self, elements):
        """ Triggers a reaction which is displayed in the reaction frame """

        # add previous reaction to log
        old_reaction = self.current_reaction_label_string.get()
        if old_reaction != 'No reactions yet':
            self.add_to_log(old_reaction)

        symbols = []
        valences = []

        for e in elements:
            symbols.append(e['prev_symbol'].decode('UTF-8'))
            valences.append(int(e['prev_valence'].decode('UTF-8')))

        quant_symbols = ['', '']

        abs_valences = [abs(v) for v in valences]
        max_i = abs_valences.index(max(abs_valences))
        min_i = abs_valences.index(min(abs_valences))

        ratio = valences[max_i] / valences[min_i]
        rem = valences[max_i] % valences[min_i]

        quants = [0, 0]

        if ratio == 1:
            quants[0] = 1
            quants[1] = 1
        elif rem == 0:
            quants[max_i] = 1
            quants[min_i] = abs(ratio)
        else:
            quants[0] = abs(valences[1])
            quants[1] = abs(valences[0])

        for i in range(len(symbols)):
            if quants[i] == 1:
                quant_symbols[i] = symbols[i]
            else:
                quant_symbols[i] = str(int(quants[i])) + symbols[i]

        reaction_str = ' + '.join(quant_symbols)
        reaction_str += " => "
        reaction_str += elements[0]['chem_symbol'].decode('UTF-8')

        print(reaction_str)
        self.current_reaction_label_string.set(reaction_str)

    def add_to_log(self, old_reaction):
        """ add old_reaction to the reaction log """

        self.reaction_log_tree.insert('', '0', text=old_reaction)

    def add_info_frame(self):
        """ Frame contains 
            - information about the element/compound on whichever ElementBit has been selected in the list
            - description of current scenario? """
        self.info_frame = ttk.Frame(self.main_page, style="Groove.TFrame")

        self.info_frame_label = ttk.Label(self.info_frame,
                                          text="Information Panel")
        self.info_frame_label.pack(pady=10)

        self.info_empty_label = ttk.Label(
            self.info_frame,
            text="Select an ElementBit from the list for information")
        self.info_empty_label.pack(pady=30, padx=20)

        self.read_info_from_file()

        self.info_labels = []
        self.info_entries = []
        self.info_im = None

        self.info_frame.pack(side=RIGHT, fill="both", expand="true")

    def read_info_from_file(self):
        """ reads the whole information table from file into memory"""
        self.info_table = []
        with open(self.INFORMATION_FILE, 'rt') as info_File:
            reader = csv.DictReader(info_File)

            for row in reader:
                self.info_table.append(
                    OrderedDict(
                        sorted(row.items(),
                               key=lambda item: reader.fieldnames.index(item[0]
                                                                        ))))

    def info_frame_update(self, selected_symbol):
        """ update info frame to display info about selected element/compound """

        self.info_empty_label.pack_forget()

        # get relevant info from table
        info_results = [
            x for x in self.info_table if x['Symbol'] == selected_symbol
        ]
        res = info_results[0]

        # clear info from previous selection
        [l.pack_forget() for l in self.info_labels]
        [e.pack_forget() for e in self.info_entries]

        self.info_labels.clear()
        self.info_entries.clear()
        self.info_im = None

        # make labels and entries for new info
        for key, value in res.items():
            if key == 'Image':
                if value != "":
                    self.info_im = PhotoImage(
                        file=os.path.join(self.IMAGE_DIR, value))
                    label = ttk.Label(self.info_frame, image=self.info_im)
                    self.info_labels.append(label)
                    label.pack()
            else:
                if value != '':
                    label = ttk.Label(self.info_frame, text=key)
                    self.info_labels.append(label)
                    label.pack()

                    info = Message(self.info_frame,
                                   text=value,
                                   aspect=500,
                                   background="white",
                                   relief="raised",
                                   fg="#535d6d")
                    self.info_entries.append(info)
                    info.pack(ipadx=5, ipady=5, pady=10)

    def add_options_page(self, nb):
        """ Options tab has
                - list of fields to include in information panel """

        self.options_page = ttk.Frame(nb, width=1000, height=600)
        nb.add(self.options_page, text='Options')

    def add_scenarios_page(self, nb):
        """ Load Scenarios tab has
                - list of scenarios to choose from
                - button to load selected scenario """

        self.scenarios_page = ttk.Frame(nb, width=1000, height=600)

        self.scenarios_tree = ttk.Treeview(self.scenarios_page,
                                           show='headings',
                                           columns=('name', 'desc', 'nbits'),
                                           selectmode="browse")

        self.scenarios_tree.column('name', width=150)
        self.scenarios_tree.heading('name', text='Scenario')
        self.scenarios_tree.column('desc', width=600)
        self.scenarios_tree.heading('desc', text='Description')
        self.scenarios_tree.column('nbits', width=120)
        self.scenarios_tree.heading('nbits', text='No. ElementBits')

        self.read_scenarios_from_file()

        self.scenarios_tree.pack(pady=20)
        self.scenarios_tree.bind("<<TreeviewSelect>>",
                                 self.on_scenario_tree_select)

        self.load_scenario_button = ttk.Button(self.scenarios_page,
                                               command=self.load_scenario,
                                               text="Load Scenario",
                                               state="disabled")
        self.load_scenario_button.pack()

        nb.add(self.scenarios_page, text="Load Scenario")

    def read_scenarios_from_file(self):
        """ reads the list of scenarios from file into a list of ordered dicts"""
        self.scenarios_list = []
        with open(self.SCENARIOS_FILE, 'rt') as scenarios_file:
            reader = csv.DictReader(scenarios_file)

            for row in reader:
                self.scenarios_list.append(
                    OrderedDict(
                        sorted(row.items(),
                               key=lambda item: reader.fieldnames.index(item[0]
                                                                        ))))

        for s in self.scenarios_list:
            self.scenarios_tree.insert(
                '',
                'end',
                text=s['File'],
                values=([s['Name'], s['Description'], s['No. ElementBits']]))

    def on_scenario_tree_select(self, event):
        """ set currently selected scenario and enable load scenario button"""

        selection = self.scenarios_tree.selection()[0]
        self.scenario_file = os.path.join(
            self.SCENARIOS_DIR,
            self.scenarios_tree.item(selection)['text'])
        self.load_scenario_button.state(['!disabled'])

    def load_scenario(self):
        """ load scenario from file """
        if self.scenario_obj:
            self.scenario_obj.force_quit_main_loop()
            self.thread.join()
        print(self.scenario_file)
        self.scenario_obj = sc.Scenario(self, scenario_file=self.scenario_file)
        self.thread = Thread(target=self.scenario_obj.main_loop,
                             kwargs=dict(master=self))
        self.thread.setDaemon(True)
        self.thread.start()
this_dir = os.path.dirname(os.path.realpath(__file__))

top_frame = Frame(root, width=1200, height=1000)
top_frame.pack(side='bottom', fill='both', padx=10, pady=5, expand=True)

bottom_frame = Frame(root, width=1200, height=1000)
bottom_frame.pack(side='bottom', padx=10, pady=5, expand=True)

# Adds a custom logo
imgicon = PhotoImage(file=os.path.join(this_dir, "imgs", "icon.png"))
root.tk.call("wm", "iconphoto", root._w, imgicon)

##Create 5 buttons and assign their corresponding function to active sprites
rabbit = PhotoImage(
    file=os.path.join(this_dir, "sprites", "icon", "rabbitIcon.png"))
rabbit = rabbit.subsample(5, 5)
btn_rabbit = Button(top_frame,
                    image=rabbit,
                    compound="left",
                    command=lambda: put_sprite(0))
btn_rabbit.pack(side="left", fill="none", expand="false", padx="14", pady="10")

fire = PhotoImage(file=os.path.join(this_dir, "sprites", "icon", "fire.png"))
fire = fire.subsample(5, 5)
btn_fire = Button(top_frame,
                  image=fire,
                  compound="left",
                  command=lambda: put_sprite(1))
btn_fire.pack(side="left", fill="none", expand="false", padx="14", pady="10")

glassesHeart = PhotoImage(
Exemplo n.º 36
0
class Aplication:
    def __init__(self, master, *args, **kwargs):
        self.master = master

        self.frame1 = Frame(master,
                            width=200,
                            height=1500,
                            bg='#222125',
                            bd=5,
                            relief='raise')
        self.frame1.pack(side=LEFT)

        self.label1 = Label(master,
                            text='Barber Shop',
                            font=('arial', 55, 'bold'))
        self.label1.pack()

        self.caixa = Button(self.frame1,
                            text='Caixa',
                            fg='#f97303',
                            bg='#505157',
                            bd=10,
                            relief='raise',
                            width=12,
                            height=2,
                            font=('comic sans ms', 15, 'bold'),
                            command=self.home_caixa).place(x=10, y=5)

        self.agenda = Button(self.frame1,
                             text='Agenda',
                             fg='#f97303',
                             bg='#505157',
                             bd=10,
                             relief='raise',
                             width=12,
                             height=2,
                             font=('comic sans ms', 15, 'bold'),
                             command=self.agenda).place(x=10, y=125)

        self.cadprod = Button(self.frame1,
                              text='Cadastro\nProduto',
                              fg='#f97303',
                              bg='#505157',
                              bd=10,
                              relief='raise',
                              width=12,
                              height=2,
                              font=('comic sans ms', 15, 'bold'),
                              command=self.cadprod).place(x=10, y=245)

        self.cadclient = Button(self.frame1,
                                text='Cadastro\nCliente',
                                fg='#f97303',
                                bg='#505157',
                                bd=10,
                                relief='raise',
                                width=12,
                                height=2,
                                font=('comic sans ms', 15, 'bold'),
                                command=self.cadcliente).place(x=10, y=365)

        self.cadfornec = Button(self.frame1,
                                text='Cadastro\nFornecedor',
                                fg='#f97303',
                                bg='#505157',
                                bd=10,
                                relief='raise',
                                width=12,
                                height=2,
                                font=('comic sans ms', 15, 'bold'),
                                command=self.cadfornecedor).place(x=10, y=490)

        self.aniversario = Button(
            self.frame1,
            text='Aniversários',
            fg='#f97303',
            bg='#505157',
            bd=10,
            relief='raise',
            width=12,
            height=2,
            font=('comic sans ms', 15, 'bold'),
        ).place(x=10, y=610)

        self.modelo = Button(
            self.frame1,
            text='Modelos',
            fg='#f97303',
            bg='#505157',
            bd=10,
            relief='raise',
            width=12,
            height=2,
            font=('comic sans ms', 15, 'bold'),
        ).place(x=10, y=730)

        self.foto = PhotoImage(file='img.gif')
        self.foto = self.foto.subsample(1, 1)
        self.label = Label(master, image=self.foto)
        self.label.pack()

    def home_caixa(self):
        call(['python', 'home_caixa.py'])

    def agenda(self):
        call(['python', 'agendar.py'])

    def cadprod(self):
        call(['python', 'cad_prod.py'])

    def cadcliente(self):
        call(['python', 'cad_cliente.py'])

    def cadfornecedor(self):
        call(['python', 'cad_fornecedor.py'])