Exemple #1
0
    def __init__(self, master, image, name, enhancer, lo, hi):
        Frame.__init__(self, master)

        # set up the image
        self.tkim = ImageTk.PhotoImage(image.mode, image.size)
        self.enhancer = enhancer(image)
        self.update("1.0")  # normalize

        # image window
        Label(self, image=self.tkim).pack()

        # scale
        s = Scale(self, label=name, orient=HORIZONTAL, from_=lo, to=hi, resolution=0.01, command=self.update)
        s.set(self.value)
        s.pack()
Exemple #2
0
    def __init__(self, master, image, name, enhancer, lo, hi):
        Frame.__init__(self, master)

        # set up the image
        self.tkim = ImageTk.PhotoImage(image.mode, image.size)
        self.enhancer = enhancer(image)
        self.update("1.0")  # normalize

        # image window
        Label(self, image=self.tkim).pack()

        # scale
        s = Scale(self,
                  label=name,
                  orient=HORIZONTAL,
                  from_=lo,
                  to=hi,
                  resolution=0.01,
                  command=self.update)
        s.set(self.value)
        s.pack()
    def __init__(self, master, image, image_name):
        Frame.__init__(self, master)
        self.image = image
        self.image_name = image_name

        # make a blank image for the text, initialized to transparent text color
        self.blank_image = Image.new('RGBA', self.image.size, (255,255,255,0))
        self.fnt = ImageFont.truetype('fonts/MontereyFLF.ttf', 50)
        self.d = ImageDraw.Draw(self.blank_image)

        #default watermark
        self.name = "watermark"
        self.loc_x = 0
        self.loc_y = 225
        self.rgbo = (0,0,0,200)
        self.d.text((self.loc_x, self.loc_y), self.name, font=self.fnt, fill=self.rgbo)

        self.out = Image.alpha_composite(self.image, self.blank_image)
        self.tkim = ImageTk.PhotoImage(self.out)

        #display image
        Label(root, image=self.tkim).pack()

        # opacity scale
        s_opacity = Scale(self, label="Opacity", orient=HORIZONTAL, from_=0, to=255, resolution=1, command=self.update_opacity)
        s_opacity.set(200)
        s_opacity.pack(pady = 10)


        #update text
        self.textbox = Entry()
        self.textbox.pack(pady = 10)
        b_text = Button(master, text="update text", command=self.update_text)
        b_text.pack()

        b_color = Button(master, text="black/white", command=self.update_color)
        b_color.pack()
        
        b_save = Button(master, text="save image", command=self.save_image)
        b_save.pack()
Exemple #4
0
def main():
    """Configurate the game"""
    def start_game():
        """Starting"""
        rng = rang.get()
        cmb = combo.get()
        clr = colors.get()
        if cmb <= rng:
            root.destroy()
            score = lines.game(rng, cmb, clr)
            if score:
                scores.end(score)

    root = Tk()
    rang = Scale(root, orient=H, length=300, from_=5, to=20, resolution=1)
    combo = Scale(root, orient=H, length=300, from_=3, to=10, resolution=1)
    colors = Scale(root, orient=H, length=300, from_=3, to=8, resolution=1)
    lab1 = Label(root, text="Rang of the field", font="Arial 12")
    lab2 = Label(root, text="Size of combo-line (<=rang)", font="Arial 12")
    lab3 = Label(root, text="Colors count", font="Arial 12")
    start = Button(root, text="Start", command=start_game)
    lab1.pack()
    rang.pack()
    lab2.pack()
    combo.pack()
    lab3.pack()
    colors.pack()
    start.pack()
    root.mainloop()
Exemple #5
0
    class BirthOptions:
        def __init__(self, master, count, default):
            self.frame = LabelFrame(master, text="Born option")
            self.value = IntVar(value=default)
            self.spin_box = Spinbox(self.frame,
                                    textvariable=self.value,
                                    wrap=True,
                                    width=int(count / 10 + 2),
                                    to=count - 1,
                                    from_=1)
            self.spin_box.pack(side=LEFT)
            self.scale = Scale(self.frame,
                               variable=self.value,
                               orient='horizontal',
                               to=count - 1,
                               from_=1,
                               showvalue=0)
            self.scale.pack(side=LEFT, fill="x", expand=True)
            self.frame.pack(side=TOP, fill="x", expand=True)

        def get_values(self):
            return self.value.get()
Exemple #6
0
def main():
    window = Tk()
    # window.iconbitmap('Nik.ico')
    window.title('Селезнев Никита, ФИИТ-401')
    window.resizable(width=False, height=False)
    color1 = 'PaleGoldenrod'
    color2 = 'lightyellow'

    frame = Frame(window, bg=color1)
    frame.pack()

    Label(frame, text="Лабораторная работа №2.\n14 вариант.",
          justify=CENTER, font=("Helvetica", 12), bd=10, bg=color1).pack()

    Label(frame, text="""f(x) = y + Lx(1-x) + 2L + 2, L = 3.3,\ty0 = 0
    Решение численными методами
        1) Эйлера (явный)
        2) Эйлера (с пересчётом)
        3) Рунге-Кутта
        4) Прогонка
    а также точное решение.""", justify=LEFT, font=("Helvetica", 12), bd=10, bg=color2).pack()

    Label(frame, text="\nВыберите количество точек:", justify=CENTER, font=("Helvetica", 12), bd=0, bg=color1).pack()

    w = Scale(frame, from_=5, to=500, resolution=1, length=300, bg=color1, borderwidth=0,
              relief=GROOVE, orient=HORIZONTAL, highlightthickness=0)
    w.pack()

    Label(frame, text='\n', bg=color1).pack()

    Button(frame, text="Нарисовать график",
           font=("Helvetica", 12),
           bg=color2,
           command=lambda: draw_all(int(w.get()))).pack()

    window.mainloop()
Exemple #7
0
    def run(self):
        self.pack()

        label = Label(self, bg="black", height=20, width=40)
        label.pack()
        name = Label(self, text="black")
        name.pack()
        self.name = name
        self.label = label

        red = Scale(
            self,
            from_=0,
            to=255,
            orient="horizontal",
            length=256,
            label="Red",
            command=self.change_red,
        )
        red.pack()

        green = Scale(
            self,
            from_=0,
            to=255,
            orient="horizontal",
            length=256,
            label="Green",
            command=self.change_green,
        )
        green.pack()

        blue = Scale(
            self,
            from_=0,
            to=255,
            orient="horizontal",
            length=256,
            label="Blue",
            command=self.change_blue,
        )
        blue.pack()
Exemple #8
0
class LayerViewer(ttk.LabelFrame):
    def __init__(self, project, width, height, *args, **kwargs):
        ttk.LabelFrame.__init__(self, *args, **kwargs)
        self.configure(text="LayerViewer")
        self.project = project
        self.width = width
        self.height = height
        self.delay = 1000
        self.index = 0
        self.state = PAUSED

        self.outer_frame = Frame(self)
        self.outer_frame.pack(side="top",
                              fill="both",
                              expand=True,
                              padx=4,
                              pady=4)
        self.outer_frame.config(width=250, height=200)
        self.inner_frame = Frame(self)
        force_aspect(self.inner_frame, self.outer_frame,
                     float(width) / float(height))

        self.canvas = Canvas(self.inner_frame, relief="sunken")
        self.canvas.config(
            width=50,  #Parent frame width
            height=50,
            highlightthickness=0)
        self.canvas.config()
        self.canvas_frame = Frame(self.canvas, border=0, highlightthickness=0)
        self.canvas.create_window(0, 0, window=self.canvas_frame, anchor='nw')
        self.canvas_frame.config(width=50, height=50)
        self.canvas.pack(fill="both", expand=True)

        self.playback_scale = Scale(self,
                                    orient="horizontal",
                                    from_=0,
                                    to=30,
                                    command=self.set_delay)
        self.playback_scale.set(int(self.delay / 1000))
        self.playback_scale.pack(fill="both", expand=False, padx=4, pady=4)

        self.display_loop()

    # def pause(self, event = None):
    # 	self.state = PAUSED

    # def play(self, event = None):
    # 	self.state = RUNNING

    def set_delay(self, fps):
        if float(fps) < float(1.0):
            self.delay = None
            return
        self.delay = int(1000.0 / float(fps))

    """
	Approximates an fps, milage will vary, it would be 
	better for me to run this as a thread spawned by a
	timer thread  that acts as the loop, so the fps 
	would more closely match the one selected with the menu bar
	"""

    def display_loop(self):
        if not self.project.frames or not self.delay:
            self.after(100, self.display_loop)
            return
        if self.index > len(self.project.frames) - 1:
            self.index = 0
        layer = self.project.frames[self.index]
        self.image = layer.export_composite_image().resize(
            (self.inner_frame.winfo_width(), self.inner_frame.winfo_height()),
            Image.BOX)
        self.displayed = ImageTk.PhotoImage(self.image)
        self.canvas.delete("all")
        self.canvas.create_image(0, 0, image=self.displayed, anchor="nw")
        self.configure(text=f"Preview: {layer.id}")
        self.index += 1
        if self.delay < 10:
            delay = 10
        delay = self.delay or 1000
        self.after(delay, self.display_loop)
Exemple #9
0
class SimulationPage(tk.Frame):
    def __init__(self, parent, controller, queue):
        self._dashboard = Dashboard()
        self.controller = controller
        self.simulator = Simulator(queue)
        self.window_closed = False

        tk.Frame.__init__(self, parent, bg='white')
        title_label = tk.Label(self,
                               text="Project Origin Dashboard",
                               font=LARGE_FONT,
                               foreground='blue',
                               bg='white')
        title_label.pack(pady=10, padx=10)

        self.s = ttk.Style()
        self.s.theme_use('vista')

        self.status_label = tk.Label(self, text="Simulator Ready.", bg='white')
        self.status_label.pack(pady=10, padx=10)

        self.sim_btn = ttk.Button(
            self,
            text="Start Simulation",
            command=lambda: self.on_simulation_btn_click())

        self.sim_btn.pack()
        self.food_creature_scale = Scale(
            self,
            from_=0,
            to=1,
            orient=tk.HORIZONTAL,
            resolution=0.1,
            bg='white',
            command=lambda x: self.set_food_creature_ratio(x))
        self.food_creature_scale.set(ConfigPhysics.FOOD_CREATURE_RATIO)
        self.food_creature_scale.pack()

        dash_fig = self._dashboard.get_figure()

        canvas = FigureCanvasTkAgg(dash_fig, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        controller.protocol("WM_DELETE_WINDOW", self.close_window_event)

    def close_window_event(self):
        self.stop_simulation()
        self.window_closed = True
        if self.simulator.status() == SimState.IDLE:
            self.close_window()

    def close_window(self):
        self.controller.destroy()
        sys.exit()

    def refresh_data(self, msg):
        if type(msg) == SimState:
            print(msg.value)
            if msg == SimState.IDLE:
                self.sim_btn['text'] = 'Start Simulation'
                self.sim_btn['state'] = tk.ACTIVE
                if self.window_closed:
                    self.close_window()
            self.status_label['text'] = str(msg.value)
        else:
            self._dashboard.update_step_dash(msg.step_stats_df)
            self._dashboard.update_epoch_dash(msg.epoch_stats_df)

    def on_simulation_btn_click(self):
        if self.sim_btn['text'] == 'Start Simulation':
            self.start_simulation()
            self.sim_btn['text'] = 'Stop Simulation'
        else:
            self.stop_simulation()
            self.sim_btn['state'] = tk.DISABLED

    def stop_simulation(self):
        self.simulator.stop()
        self.status_label['text'] = "Simulation Interrupted. Stopping..."

    def start_simulation(self):
        self.simulator.run_in_thread()

    @staticmethod
    def set_food_creature_ratio(new):
        ConfigPhysics.FOOD_CREATURE_RATIO = float(new)
Exemple #10
0
class ColoredBar(tk.Frame):
    RANGE = [0, 1000]

    def __init__(self, *args):
        super().__init__(*args)

        # firmware value
        self.firmware_value = Label(
            self, text="(Pad's firmware sens)", justify="center"
        )
        self.firmware_value.pack(expand=True, fill="both")

        # current value
        self.canvas = Canvas(self, bd=1, relief="solid", width=98, height=15)
        self.canvas.pack(expand=True, fill="both")
        self.critical = 800

        # frame the slider and entry together
        frame = tk.Frame(self, highlightthickness=3, relief=tk.RIDGE, bg="black")
        frame.pack(expand=True, fill="both")

        self.slider = Scale(
            frame,
            from_=0,
            to=1000,
            orient="horizontal",
            command=self.set_critical,
            showvalue=0,
        )
        self.slider.pack(expand=True, fill="both")

        self.entry = Entry(frame, justify="center")
        self.entry.bind("<FocusOut>", self.set_critical_entry)
        self.entry.bind("<Return>", self.set_critical_entry)
        self.entry.pack(expand=True, fill="both")
        self.valid_range = self.RANGE

    def set_firmware_value(self, value):
        self.firmware_value["text"] = value

    def set_range(self, valid_range):
        """valid range for raw and cutoff"""
        self.valid_range = valid_range

    def set_critical_entry(self, *args):
        value = self.entry.get()
        try:
            value = int(value)
            value = clamp(value, *self.valid_range)
        except:
            value = self.critical
            raise
        self.set_critical(value)

    def set_critical(self, value):
        self.critical = int(value)
        # update entries text
        self.entry.delete(0, tk.END)
        self.entry.insert(0, str(value))
        self.slider.set(value)
        # debug only:
        # self.set_value(value)

    def set_value(self, value):
        """
        sets the raw value
        """
        value = float(value)
        self.canvas.delete(tk.ALL)
        width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
        perc = float(value) / 1000.0
        x_right = lerp(SLIDER_WIDTH, width - SLIDER_WIDTH, perc)

        text_anchor = "w" if value < 500 else "e"

        if value < self.critical:
            fill = "yellow"
        else:
            fill = "green"

        self.canvas.create_rectangle(SLIDER_WIDTH, 5, x_right, height - 5, fill=fill)
        self.canvas.create_text(
            x_right + 5, height / 2, text=str(int(value)), anchor=text_anchor
        )
Exemple #11
0
if __name__ == '__main__':
    from tkinter import Tk, Scale
    from comtypes import CoCreateInstance
    from win32gui import GetParent    
    
    tbm = CoCreateInstance(GUID_CTaskbarList, interface=ITaskbarList3)
    
    def onMove_gen(root):
        def onMove(value):
            tbm.SetProgressValue(GetParent(root.winfo_id()), int(value), 100)
        return onMove
    
    root    = Tk()
    tbar    = Scale(root, from_=0, to=100, orient='horizontal', command=onMove_gen(root))
    tbar.pack()
    root.mainloop()
    
    
    
#class ITaskbarList(IUnknown):
#    _iid_   = GUID('{56FDF342-FD6D-11D0-958A-006097C9A090}')
#    _methods_   = [
#        COMMETHOD([], HRESULT, 'HrInit'),
#
#        COMMETHOD([], HRESULT, 'AddTab',
#            (['in'], HWND, 'hwnd')
#        ),
#
#        COMMETHOD([], HRESULT, 'DeleteTab',
#            (['in'], HWND, 'hwnd')
class TelloUI:
    """Wrapper class to enable the GUI."""
    def __init__(self, tello, outputpath):
        """
        Initial all the element of the GUI,support by Tkinter

        :param tello: class interacts with the Tello drone.

        Raises:
            RuntimeError: If the Tello rejects the attempt to enter command mode.
        """

        self.tello = tello  # videostream device
        self.outputPath = outputpath  # the path that save pictures created by clicking the takeSnapshot button
        self.frame = None  # frame read from h264decoder and used for pose recognition
        self.thread = None  # thread of the Tkinter mainloop
        self.stopEvent = None

        # control variables
        self.distance = 0.1  # default distance for 'move' cmd
        self.degree = 30  # default degree for 'cw' or 'ccw' cmd

        # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello
        self.quit_waiting_flag = False

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None

        # create buttons
        self.btn_snapshot = tki.Button(self.root,
                                       text="Snapshot!",
                                       command=self.takeSnapshot)
        self.btn_snapshot.pack(side="bottom",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

        self.btn_pause = tki.Button(self.root,
                                    text="Pause",
                                    relief="raised",
                                    command=self.pauseVideo)
        self.btn_pause.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_landing = tki.Button(self.root,
                                      text="Open Command Panel",
                                      relief="raised",
                                      command=self.openCmdWindow)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

        # set a callback to handle when the window is closed
        self.root.wm_title("TELLO Controller")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose)

        # the sending_command will send command to tello every 5 seconds
        self.sending_command_thread = threading.Thread(
            target=self._sendingCommand)

    def videoLoop(self):
        """
        The mainloop thread of Tkinter
        Raises:
            RuntimeError: To get around a RunTime error that Tkinter throws due to threading.
        """
        try:
            # start the thread that get GUI image and drwa skeleton
            time.sleep(0.5)
            self.sending_command_thread.start()
            while not self.stopEvent.is_set():
                system = platform.system()

                # read the frame for GUI show
                self.frame = self.tello.read()
                if self.frame is None or self.frame.size == 0:
                    continue

                    # transfer the format from frame to image
                image = Image.fromarray(self.frame)

                # we found compatibility problem between Tkinter,PIL and Macos,and it will
                # sometimes result the very long preriod of the "ImageTk.PhotoImage" function,
                # so for Macos,we start a new thread to execute the _updateGUIImage function.
                if system == "Windows" or system == "Linux":
                    self._updateGUIImage(image)

                else:
                    thread_tmp = threading.Thread(target=self._updateGUIImage,
                                                  args=(image, ))
                    thread_tmp.start()
                    time.sleep(0.03)
        except RuntimeError as e:
            print("[INFO] caught a RuntimeError")

    def _updateGUIImage(self, image):
        """
        Main operation to initial the object of image,and update the GUI panel
        """
        image = ImageTk.PhotoImage(image)
        # if the panel none ,we need to initial it
        if self.panel is None:
            self.panel = tki.Label(image=image)
            self.panel.image = image
            self.panel.pack(side="left", padx=10, pady=10)
        # otherwise, simply update the panel
        else:
            self.panel.configure(image=image)
            self.panel.image = image

    def _sendingCommand(self):
        """
        start a while loop that sends 'command' to tello every 5 second
        """

        while True:
            self.tello.send_command('command')
            time.sleep(5)

    def _setQuitWaitingFlag(self):
        """
        set the variable as TRUE,it will stop computer waiting for response from tello
        """
        self.quit_waiting_flag = True

    def openCmdWindow(self):
        """
        open the cmd window and initial all the button and text
        """
        panel = Toplevel(self.root)
        panel.wm_title("Command Panel")

        # create text input entry
        text0 = tki.Label(
            panel,
            text=
            'This Controller map keyboard inputs to Tello control commands\n'
            'Adjust the trackbar to reset distance and degree parameter',
            font='Helvetica 10 bold')
        text0.pack(side='top')

        text1 = tki.Label(
            panel,
            text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n'
            'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n'
            'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n'
            'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right',
            justify="left")
        text1.pack(side="top")

        self.btn_landing = tki.Button(panel,
                                      text="Land",
                                      relief="raised",
                                      command=self.telloLanding)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.btn_takeoff = tki.Button(panel,
                                      text="Takeoff",
                                      relief="raised",
                                      command=self.telloTakeOff)
        self.btn_takeoff.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        # binding arrow keys to drone control
        self.tmp_f = tki.Frame(panel, width=100, height=2)
        self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w)
        self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s)
        self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a)
        self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d)
        self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)
        self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down)
        self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left)
        self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right)
        self.tmp_f.pack(side="bottom")
        self.tmp_f.focus_set()

        self.btn_landing = tki.Button(panel,
                                      text="Flip",
                                      relief="raised",
                                      command=self.openFlipWindow)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.distance_bar = Scale(panel,
                                  from_=0.02,
                                  to=5,
                                  tickinterval=0.01,
                                  digits=3,
                                  label='Distance(m)',
                                  resolution=0.01)
        self.distance_bar.set(0.2)
        self.distance_bar.pack(side="left")

        self.btn_distance = tki.Button(
            panel,
            text="Reset Distance",
            relief="raised",
            command=self.updateDistancebar,
        )
        self.btn_distance.pack(side="left",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

        self.degree_bar = Scale(panel,
                                from_=1,
                                to=360,
                                tickinterval=10,
                                label='Degree')
        self.degree_bar.set(30)
        self.degree_bar.pack(side="right")

        self.btn_distance = tki.Button(panel,
                                       text="Reset Degree",
                                       relief="raised",
                                       command=self.updateDegreebar)
        self.btn_distance.pack(side="right",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

    def openFlipWindow(self):
        """
        open the flip window and initial all the button and text
        """

        panel = Toplevel(self.root)
        panel.wm_title("Gesture Recognition")

        self.btn_flipl = tki.Button(panel,
                                    text="Flip Left",
                                    relief="raised",
                                    command=self.telloFlip_l)
        self.btn_flipl.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipr = tki.Button(panel,
                                    text="Flip Right",
                                    relief="raised",
                                    command=self.telloFlip_r)
        self.btn_flipr.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipf = tki.Button(panel,
                                    text="Flip Forward",
                                    relief="raised",
                                    command=self.telloFlip_f)
        self.btn_flipf.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipb = tki.Button(panel,
                                    text="Flip Backward",
                                    relief="raised",
                                    command=self.telloFlip_b)
        self.btn_flipb.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

    def takeSnapshot(self):
        """
        save the current frame of the video as a jpg file and put it into outputpath
        """

        # grab the current timestamp and use it to construct the filename
        ts = datetime.datetime.now()
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))

        p = os.path.sep.join((self.outputPath, filename))

        # save the file
        cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR))
        print("[INFO] saved {}".format(filename))

    def pauseVideo(self):
        """
        Toggle the freeze/unfreze of video
        """
        if self.btn_pause.config('relief')[-1] == 'sunken':
            self.btn_pause.config(relief="raised")
            self.tello.video_freeze(False)
        else:
            self.btn_pause.config(relief="sunken")
            self.tello.video_freeze(True)

    def telloTakeOff(self):
        return self.tello.takeoff()

    def telloLanding(self):
        return self.tello.land()

    def telloFlip_l(self):
        return self.tello.flip('l')

    def telloFlip_r(self):
        return self.tello.flip('r')

    def telloFlip_f(self):
        return self.tello.flip('f')

    def telloFlip_b(self):
        return self.tello.flip('b')

    def telloCW(self, degree):
        return self.tello.rotate_cw(degree)

    def telloCCW(self, degree):
        return self.tello.rotate_ccw(degree)

    def telloMoveForward(self, distance):
        return self.tello.move_forward(distance)

    def telloMoveBackward(self, distance):
        return self.tello.move_backward(distance)

    def telloMoveLeft(self, distance):
        return self.tello.move_left(distance)

    def telloMoveRight(self, distance):
        return self.tello.move_right(distance)

    def telloUp(self, dist):
        return self.tello.move_up(dist)

    def telloDown(self, dist):
        return self.tello.move_down(dist)

    def updateTrackBar(self):
        self.my_tello_hand.setThr(self.hand_thr_bar.get())

    def updateDistancebar(self):
        self.distance = self.distance_bar.get()
        print
        'reset distance to %.1f' % self.distance

    def updateDegreebar(self):
        self.degree = self.degree_bar.get()
        print
        'reset distance to %d' % self.degree

    def on_keypress_w(self, event):
        print
        "up %d m" % self.distance
        self.telloUp(self.distance)

    def on_keypress_s(self, event):
        print
        "down %d m" % self.distance
        self.telloDown(self.distance)

    def on_keypress_a(self, event):
        print
        "ccw %d degree" % self.degree
        self.tello.rotate_ccw(self.degree)

    def on_keypress_d(self, event):
        print
        "cw %d m" % self.degree
        self.tello.rotate_cw(self.degree)

    def on_keypress_up(self, event):
        print
        "forward %d m" % self.distance
        self.telloMoveForward(self.distance)

    def on_keypress_down(self, event):
        print
        "backward %d m" % self.distance
        self.telloMoveBackward(self.distance)

    def on_keypress_left(self, event):
        print
        "left %d m" % self.distance
        self.telloMoveLeft(self.distance)

    def on_keypress_right(self, event):
        print
        "right %d m" % self.distance
        self.telloMoveRight(self.distance)

    def on_keypress_enter(self, event):
        if self.frame is not None:
            self.registerFace()
        self.tmp_f.focus_set()

    def onClose(self):
        """
        set the stop event, cleanup the camera, and allow the rest of

        the quit process to continue
        """
        print("[INFO] closing...")
        self.stopEvent.set()
        del self.tello
        self.root.quit()
Exemple #13
0
def init():
    #setting variables to global scope that need to be accessed outside of init()
    global curve_smoothing_slider, horizontal_shift_slider, vertical_shift_slider, image_canvas, bounds_button, preview_button, export_button, baseline_choice, im, imload, peak_num_choice

    left_frame = Frame(root)
    left_frame.pack(side="left")

    middle_frame = Frame(root)
    middle_frame.pack(side="right")

    right_frame = Frame(root)
    right_frame.pack(side="right")

    sub_middle_frame = Frame(middle_frame)
    sub_middle_frame.pack(side="bottom", pady=(0, 10))

    #left side inputs
    Button(left_frame, text="Help", command=help_window).pack(anchor='nw',
                                                              padx=(10, 0),
                                                              pady=(10, 10))

    Button(left_frame, text="Select a file",
           command=select_file).pack(anchor='n', pady=(0, 15))

    Label(left_frame, text="Threshold and Crop", justify="center").pack()
    threshold_slider = Scale(left_frame,
                             orient="horizontal",
                             length=200,
                             from_=1.0,
                             to=30.0,
                             command=update_thresh)
    threshold_slider.pack(padx=20, pady=(0, 10))

    #button for selecting the region of interest (ROI), this ROI is then analyzed for the graph
    Button(left_frame, text="Select a ROI",
           command=find_roi).pack(pady=(0, 15))

    #slider for determining how much the curve is smoothed out (typically has very many oscillations and spikes)
    Label(left_frame, text="Curve Smoothing", justify="center", padx=20).pack()
    curve_smoothing_slider = Scale(left_frame,
                                   orient="horizontal",
                                   length=200,
                                   from_=0.0,
                                   to=30.0,
                                   command=update_smooth)
    curve_smoothing_slider.pack(padx=20, pady=(0, 20))
    curve_smoothing_slider['state'] = 'disable'

    #determines whether the baselining will happen from the lowest value (from both curves lowest val is zeroed) or midpoint (average value of both is zeroed and then lowest value brought to zero)
    baseline_choice = tkinter.IntVar()
    baseline_choice.set(1)
    modes = [("Midpoint", 101), ("Lowest Value", 102)]
    Label(left_frame, text="Baseline from:", justify="left", padx=20).pack()
    for mode, val in modes:
        Radiobutton(left_frame,
                    text=mode,
                    indicatoron=1,
                    command=update_baseline,
                    justify="left",
                    padx=20,
                    variable=baseline_choice,
                    value=val).pack(anchor='w')

    #a multiple choice field for how many peaks you want analyzed at the current moment
    peak_num_choice = tkinter.IntVar()
    peak_num_choice.set(1)
    modes = [("One Peak", 101), ("Two Peaks", 102)]
    Label(left_frame,
          text="How many peaks to compare:",
          justify="left",
          padx=20).pack(pady=(20, 0))
    for mode, val in modes:
        Radiobutton(left_frame,
                    text=mode,
                    indicatoron=1,
                    command=update_peaks,
                    justify="left",
                    padx=20,
                    variable=peak_num_choice,
                    value=val).pack(anchor='w')

    #bottom row inputs
    bounds_button = Button(left_frame,
                           text="Choose Bounds",
                           command=choose_peak_bounds)
    bounds_button.pack(side="left", padx=(15, 10), pady=(30, 10))
    bounds_button["state"] = "disable"

    #building the preview button, used to look at the current strip being analyzed
    preview_button = Button(left_frame, text="Preview", command=preview_graph)
    preview_button.pack(side="left", padx=(10, 10), pady=(30, 10))
    preview_button["state"] = "disable"

    #building the export button, disabled at first until you have data to export
    export_button = Button(left_frame, text="Export", command=save_graph)
    export_button.pack(side="left", padx=(10, 0), pady=(30, 10))
    export_button["state"] = "disable"

    #building the horizontal shift (used to shift one line left and right)
    Label(sub_middle_frame, text="Horizontal Shift").grid(column=0,
                                                          row=1,
                                                          padx=(0, 20))
    horizontal_shift_slider = Scale(sub_middle_frame,
                                    orient="horizontal",
                                    length=300,
                                    from_=-10.0,
                                    to=10.0,
                                    command=update_h_shift)
    horizontal_shift_slider.grid(column=0, row=0, padx=(0, 20))
    horizontal_shift_slider['state'] = 'disable'

    #building the vertical shift (shifts one line up and down)
    Label(sub_middle_frame, text="Vertical Shift").grid(column=1, row=1)
    vertical_shift_slider = Scale(sub_middle_frame,
                                  orient="horizontal",
                                  length=300,
                                  from_=-10.0,
                                  to=10.0,
                                  command=update_v_shift)
    vertical_shift_slider.grid(column=1, row=0)
    vertical_shift_slider['state'] = 'disable'

    #right side graph
    width, height = plot_disp_size
    image_canvas = Canvas(middle_frame, width=width, height=height)
    image_canvas.pack(padx=(20, 0), pady=(0, 0))

    #blanks canvas with a white frame, image_canvas is modified to add the graph onto screen each time
    im = ImageTk.PhotoImage(Image.new("RGB", plot_disp_size,
                                      (255, 255, 255)))  #PIL solution
    imload = image_canvas.create_image(0, 0, image=im, anchor='nw')
Exemple #14
0
def guiMain(settings=None):
    frames = {}

    mainWindow = Tk()
    mainWindow.wm_title("OoT Randomizer %s" % ESVersion)

    set_icon(mainWindow)

    notebook = ttk.Notebook(mainWindow)
    frames['rom_tab'] = ttk.Frame(notebook)
    frames['rules_tab'] = ttk.Frame(notebook)
    frames['logic_tab'] = ttk.Frame(notebook)
    frames['other_tab'] = ttk.Frame(notebook)
    frames['aesthetic_tab'] = ttk.Frame(notebook)
    adjustWindow = ttk.Frame(notebook)
    customWindow = ttk.Frame(notebook)
    notebook.add(frames['rom_tab'], text='ROM Options')
    notebook.add(frames['rules_tab'], text='Main Rules')
    notebook.add(frames['logic_tab'], text='Detailed Logic')
    notebook.add(frames['other_tab'], text='Other')
    notebook.add(frames['aesthetic_tab'], text='Aesthetics')

    # Shared Controls   

    # adds a LabelFrame containing a list of radio buttons based on the given data
    # returns the label_frame, and a variable associated with it
    def MakeRadioList(parent, data):
        # create a frame to hold the radio buttons
        lable_frame = LabelFrame(parent, text=data["name"], labelanchor=NW)
        # create a variable to hold the result of the user's decision
        radio_var = StringVar(value=data["default"]);
        # setup orientation
        side = TOP
        anchor = W
        if "horizontal" in data and data["horizontal"]:
            side = LEFT
            anchor = N
        # add the radio buttons
        for option in data["options"]:
            radio_button = Radiobutton(lable_frame, text=option["description"], value=option["value"], variable=radio_var,
                                       justify=LEFT, wraplength=data["wraplength"])
            radio_button.pack(expand=True, side=side, anchor=anchor)
        # return the frame so it can be packed, and the var so it can be used
        return (lable_frame, radio_var)

    #######################
    # randomizer controls #
    #######################

    # hold the results of the user's decisions here
    guivars = {}

    # hierarchy
    ############

    #Rules Tab
    frames['open']   = LabelFrame(frames['rules_tab'], text='Open',   labelanchor=NW)
    frames['logic']  = LabelFrame(frames['rules_tab'], text='Logic',  labelanchor=NW)

    # Logic tab
    frames['rewards'] = LabelFrame(frames['logic_tab'], text='Remove Specific Locations', labelanchor=NW)
    frames['tricks']  = LabelFrame(frames['logic_tab'], text='Specific expected tricks', labelanchor=NW)

    #Other Tab
    frames['convenience'] = LabelFrame(frames['other_tab'], text='Speed Ups', labelanchor=NW)
    frames['other']       = LabelFrame(frames['other_tab'], text='Misc',      labelanchor=NW)

    #Aesthetics tab
    frames['tuniccolor'] = LabelFrame(frames['aesthetic_tab'], text='Tunic Color', labelanchor=NW)
    frames['navicolor']       = LabelFrame(frames['aesthetic_tab'], text='Navi Color',  labelanchor=NW)
    frames['lowhp']      = LabelFrame(frames['aesthetic_tab'], text='Low HP SFX',  labelanchor=NW)


    # shared
    settingsFrame = Frame(mainWindow)
    settings_string_var = StringVar()
    settingsEntry = Entry(settingsFrame, textvariable=settings_string_var)

    def show_settings(event=None):
        settings = guivars_to_settings(guivars)
        settings_string_var.set( settings.get_settings_string() )

        # Update any dependencies
        for info in setting_infos:
            if info.gui_params and 'dependency' in info.gui_params:
                dep_met = True
                for dep_var, dep_val in info.gui_params['dependency'].items():
                    if guivars[dep_var].get() != dep_val:
                        dep_met = False

                if widgets[info.name].winfo_class() == 'Frame':
                    for child in widgets[info.name].winfo_children():
                        child.configure(state= 'normal' if dep_met else 'disabled')
                else:
                    widgets[info.name].config(state = 'normal' if dep_met else 'disabled')


    def import_settings(event=None):
        try:
            settings = guivars_to_settings(guivars)
            text = settings_string_var.get().upper()
            settings.seed = guivars['seed'].get()
            settings.update_with_settings_string(text)
            settings_to_guivars(settings, guivars)
        except Exception as e:
            messagebox.showerror(title="Error", message="Invalid settings string")

    label = Label(settingsFrame, text="Settings String")
    importSettingsButton = Button(settingsFrame, text='Import Settings String', command=import_settings)
    label.pack(side=LEFT, anchor=W, padx=5)
    settingsEntry.pack(side=LEFT, anchor=W)
    importSettingsButton.pack(side=LEFT, anchor=W, padx=5)



    fileDialogFrame = Frame(frames['rom_tab'])

    romDialogFrame = Frame(fileDialogFrame)
    baseRomLabel = Label(romDialogFrame, text='Base Rom')
    guivars['rom'] = StringVar(value='ZOOTDEC.z64')
    romEntry = Entry(romDialogFrame, textvariable=guivars['rom'], width=40)

    def RomSelect():
        rom = filedialog.askopenfilename(filetypes=[("Rom Files", (".z64", ".n64")), ("All Files", "*")])
        if rom != '':
            guivars['rom'].set(rom)
    romSelectButton = Button(romDialogFrame, text='Select Rom', command=RomSelect, width=10)

    baseRomLabel.pack(side=LEFT, padx=(40,0))
    romEntry.pack(side=LEFT, padx=3)
    romSelectButton.pack(side=LEFT)

    romDialogFrame.pack()

    fileDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5,1))

    def open_output():
        open_file(output_path(''))
    
    def output_dir_select():
        rom = filedialog.askdirectory(initialdir = default_output_path(guivars['output_dir'].get()))
        if rom != '':
            guivars['output_dir'].set(rom)

    outputDialogFrame = Frame(frames['rom_tab'])
    outputDirLabel = Label(outputDialogFrame, text='Output Directory')
    guivars['output_dir'] = StringVar(value='')
    outputDirEntry = Entry(outputDialogFrame, textvariable=guivars['output_dir'], width=40)
    outputDirButton = Button(outputDialogFrame, text='Select Dir', command=output_dir_select, width=10)
    outputDirLabel.pack(side=LEFT, padx=(3,0))
    outputDirEntry.pack(side=LEFT, padx=3)
    outputDirButton.pack(side=LEFT)
    outputDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5,1))

    if os.path.exists(local_path('README.html')):
        def open_readme():
            open_file(local_path('README.html'))
        openReadmeButton = Button(outputDialogFrame, text='Open Documentation', command=open_readme)
        openReadmeButton.pack(side=LEFT, padx=5)

    outputDialogFrame.pack(side=TOP, anchor=W, pady=3)

    countDialogFrame = Frame(frames['rom_tab'])
    countLabel = Label(countDialogFrame, text='Generation Count')
    guivars['count'] = StringVar()
    countSpinbox = Spinbox(countDialogFrame, from_=1, to=100, textvariable=guivars['count'], width=3)

    countLabel.pack(side=LEFT)
    countSpinbox.pack(side=LEFT, padx=2)
    countDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(1,1))

    multiworldFrame = LabelFrame(frames['rom_tab'], text='Multi-World Generation')
    countLabel = Label(multiworldFrame, wraplength=300, justify=LEFT, text='This is used for co-op generations. Increasing World Count will drastically increase the generation time. For more information see https://github.com/TestRunnerSRL/bizhawk-co-op')
    countLabel.pack(side=TOP, anchor=W, padx=5, pady=(1,1))


    worldCountFrame = Frame(multiworldFrame)
    countLabel = Label(worldCountFrame, text='World Count')
    guivars['world_count'] = StringVar()
    countSpinbox = Spinbox(worldCountFrame, from_=1, to=100, textvariable=guivars['world_count'], width=3)

    countLabel.pack(side=LEFT)
    countSpinbox.pack(side=LEFT, padx=2)
    worldCountFrame.pack(side=LEFT, anchor=N, padx=5, pady=(1,1))

    playerNumFrame = Frame(multiworldFrame)
    countLabel = Label(playerNumFrame, text='Player Number')
    guivars['player_num'] = StringVar()
    countSpinbox = Spinbox(playerNumFrame, from_=1, to=100, textvariable=guivars['player_num'], width=3)

    countLabel.pack(side=LEFT)
    countSpinbox.pack(side=LEFT, padx=2)
    playerNumFrame.pack(side=LEFT, anchor=N, padx=5, pady=(1,1))
    multiworldFrame.pack(side=TOP, anchor=W, padx=5, pady=(1,1))




    # build gui
    ############

    widgets = {}

    for info in setting_infos:
        if info.gui_params:
            if info.gui_params['widget'] == 'Checkbutton':
                # determine the initial value of the checkbox
                default_value = 1 if info.gui_params['default'] == "checked" else 0
                # create a variable to access the box's state
                guivars[info.name] = IntVar(value=default_value)
                # create the checkbox
                widgets[info.name] = Checkbutton(frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=200, command=show_settings)
                widgets[info.name].pack(expand=False, anchor=W)
            elif info.gui_params['widget'] == 'Combobox':
                # create the variable to store the user's decision
                guivars[info.name] = StringVar(value=info.gui_params['default'])
                # create the option menu
                widgets[info.name] = Frame(frames[info.gui_params['group']])
                # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options']))
                if isinstance(info.gui_params['options'], list):
                    info.gui_params['options'] = dict(zip(info.gui_params['options'], info.gui_params['options']))
                dropdown = ttk.Combobox(widgets[info.name], textvariable=guivars[info.name], values=list(info.gui_params['options'].keys()), state='readonly', width=30)
                dropdown.bind("<<ComboboxSelected>>", show_settings)
                dropdown.pack(side=BOTTOM, anchor=W)
                # label the option
                if 'text' in info.gui_params:
                    label = Label(widgets[info.name], text=info.gui_params['text'])
                    label.pack(side=LEFT, anchor=W, padx=5)
                # pack the frame
                widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3)
            elif info.gui_params['widget'] == 'Scale':
                # create the variable to store the user's decision
                guivars[info.name] = IntVar(value=info.gui_params['default'])
                # create the option menu
                widgets[info.name] = Frame(frames[info.gui_params['group']])
                # dropdown = OptionMenu(widgets[info.name], guivars[info.name], *(info['options']))
                minval = 'min' in info.gui_params and info.gui_params['min'] or 0
                maxval = 'max' in info.gui_params and info.gui_params['max'] or 100
                stepval = 'step' in info.gui_params and info.gui_params['step'] or 1


                scale = Scale(widgets[info.name], variable=guivars[info.name], from_=minval, to=maxval, tickinterval=stepval, resolution=stepval, showvalue=0, orient=HORIZONTAL, sliderlength=15, length=200, command=show_settings)
                scale.pack(side=BOTTOM, anchor=W)
                # label the option
                if 'text' in info.gui_params:
                    label = Label(widgets[info.name], text=info.gui_params['text'])
                    label.pack(side=LEFT, anchor=W, padx=5)
                # pack the frame
                widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3)
            elif info.gui_params['widget'] == 'Entry':
                # create the variable to store the user's decision
                guivars[info.name] = StringVar(value=info.gui_params['default'])
                # create the option menu
                widgets[info.name] = Frame(frames[info.gui_params['group']])

                entry = Entry(widgets[info.name], textvariable=guivars[info.name], width=30)
                entry.pack(side=BOTTOM, anchor=W)
                # label the option
                if 'text' in info.gui_params:
                    label = Label(widgets[info.name], text=info.gui_params['text'])
                    label.pack(side=LEFT, anchor=W, padx=5)
                # pack the frame
                widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3)


    # pack the hierarchy

    frames['open'].pack(  fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )
    frames['logic'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )

    # Logic tab
    frames['rewards'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )
    frames['tricks'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )

    #Other Tab
    frames['convenience'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )
    frames['other'].pack(      fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1) )

    #Aesthetics tab
    frames['navicolor'].pack( fill=BOTH, expand=True, anchor=N, side=RIGHT, pady=(5,1) )
    frames['tuniccolor'].pack(fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5,1) )
    frames['lowhp'].pack(     fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5,1) )

    
    notebook.pack(fill=BOTH, expand=True, padx=5, pady=5)



    # didn't refactor the rest, sorry


    # create the option menu

    settingsFrame.pack(fill=BOTH, anchor=W, padx=5, pady=(10,0))

    def generateRom():
        settings = guivars_to_settings(guivars)

        try:
            if settings.count is not None:
                orig_seed = settings.seed
                for i in range(settings.count):
                    settings.update_seed(orig_seed + '-' + str(i))
                    main(settings)
            else:
                main(settings)
        except Exception as e:
            messagebox.showerror(title="Error while creating seed", message=str(e))
        else:
            messagebox.showinfo(title="Success", message="Rom patched successfully")

    generateSeedFrame = Frame(mainWindow)
    generateButton = Button(generateSeedFrame, text='Generate Patched Rom', command=generateRom)

    seedLabel = Label(generateSeedFrame, text='Seed')
    guivars['seed'] = StringVar()
    seedEntry = Entry(generateSeedFrame, textvariable=guivars['seed'])
    seedLabel.pack(side=LEFT)
    seedEntry.pack(side=LEFT)
    generateButton.pack(side=LEFT, padx=(5, 0))

    generateSeedFrame.pack(side=BOTTOM, anchor=W, padx=5, pady=10)

    if settings is not None:
        # load values from commandline args
        settings_to_guivars(settings, guivars)
    else:
        # try to load saved settings
        try:
            with open('settings.sav') as f:
                settings = Settings( json.load(f) )
                settings.update_seed("")
                settings_to_guivars(settings, guivars)
        except:
            pass

    show_settings()

    mainWindow.mainloop()

    # save settings on close
    with open('settings.sav', 'w') as outfile:
        settings = guivars_to_settings(guivars)
        json.dump(settings.__dict__, outfile)
Exemple #15
0
curve_n.set(50)
axis_label = Label(options_frame, text="mirror axis")
x_radio = Radiobutton(options_frame, text="X", variable=mirror_axis, value='x')
y_radio = Radiobutton(options_frame, text="Y", variable=mirror_axis, value='y')
xy_radio = Radiobutton(options_frame,
                       text="XY",
                       variable=mirror_axis,
                       value='xy')

#Set in GUI
load_button.pack(side="top")
load2_button.pack(side="top")
save_button.pack(side="bottom")
bg_color_sett.pack(side="left")
curve_n_label.pack(side="left")
curve_n.pack(side="left")
curve_guide_label.pack(side="left")
curve_guide_check.pack(side="left")
circle_guide_label.pack(side="left")
circle_guide_check.pack(side="left")
xy_radio.pack(side="bottom")
y_radio.pack(side="bottom")
x_radio.pack(side="bottom")
axis_label.pack(side="bottom")

#Help Text
help_text = Label(help_frame,
                  text="Click on 2 points on the screen to make a line")
help_text.pack()

#close window
Exemple #16
0
from tkinter import Tk,Scale,HORIZONTAL

master = Tk()

w = Scale(master, from_=0, to=100)
w.pack()

w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()

master.mainloop()
Exemple #17
0
 radio_button2 = Radiobutton(root, text='2', variable=var, value=2)
 radio_button3 = Radiobutton(root, text='3', variable=var, value=3)
 radio_button1.pack()
 radio_button2.pack()
 radio_button3.pack()
 # Scale
 # orient - как расположена шкала на окне. Возможные значения: horizontal, vertical (горизонтально, вертикально).
 # length - длина шкалы.
 # from_ - с какого значения начинается шкала.
 # to - каким значением заканчивается шкала.
 # tickinterval - интервал, через который отображаются метки шкалы.
 # resolution - шаг передвижения (минимальная длина, на которую можно передвинуть движок)
 scale1 = Scale(root, orient='horizontal', length=300, from_=50, to=80, tickinterval=5,
                resolution=5)
 button1 = Button(root, text="Получить значение", command=get_value)
 scale1.pack()
 button1.pack()
 # scrollbar
 text = Text(root, height=3, width=60)
 text.pack(side='left')
 scrollbar = Scrollbar(root)
 scrollbar.pack(side='left')
 # первая привязка
 scrollbar['command'] = text.yview
 # вторая привязка
 text['yscrollcommand'] = scrollbar.set
 # ListBox
 r = ['Linux', 'Python', 'Tk', 'Tkinter']
 lis = Listbox(root, selectmode='single', height=4)
 for i in r:
     lis.insert('end', i)
Exemple #18
0
 def __init__(self, root):
     s = Scale(root, from_=-100, to=100, tickinterval=1)
     s.set(0)
     #s.grid(row=0, column=0, columnspan=2, sticky=tk.N+tk.S+tk.W+tk.E)
     s.pack(side='right')
    def random_image(self, value):
        data[(int)(random() * value), (int)(random() * value)] = 255
        self.im = Image.frombytes('L', (data.shape[1], data.shape[0]),
                                  data.astype('b').tostring())
        self.photo = ImageTk.PhotoImage(image=self.im)
        self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
        self.canvas.update()
        self.master.update()


def method(value):
    app.random_image((int)(value))


root = tk.Tk()

var = DoubleVar()
app = Application(master=root)
w1 = Scale(root,
           from_=0,
           to_=150,
           tickinterval=1,
           variable=var,
           command=method)
w1.set(45)
w1.pack()
w1.command = method
logo = tk.PhotoImage()

app.mainloop()
Exemple #20
0
class MainWindow:

    def __init__(self, master):
        self.FORMAT = {0: '.pdf', 1: '.jpg'}
        self.SETTINGS_DPI = {0: 72, 1: 100, 2: 150}
        self.SETTINGS_COLOR = {0: '1', 1: 'RGB'}
        self.list_files = ''
        self.filename = ''
        self.lenght_list_files = ''
        ####################################################################################################
        # A1 # 1      # 2       # 3       # 4       # 5       # 6       # 7       # 8       # 9       # 10 #
        # A2 # BUTTON # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # VSCROLL # 10 #
        # A3 # BUTTON # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # VSCROLL # 10 #
        # A4 # BUTTON # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # VSCROLL # 10 #
        # A5 # BUTTON # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # TEXT    # VSCROLL # 10 #
        # A6 # 1      # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # HSCROLL # 10 #
        # A7 # FORMAT # SPLIT   # SPLIT   # DPI     # DPI     # COLOR   # COLOR   # QUALITY # QUALITY # 10 #
        # A8 # FORMAT # SPLIT   # SPLIT   # DPI     # DPI     # COLOR   # COLOR   # QUALITY # QUALITY # 10 #
        # A9 # FORMAT # SPLIT   # SPLIT   # DPI     # DPI     # COLOR   # COLOR   # QUALITY # QUALITY # 10 #
        # A10# P_BAR  # P_BAR   # P_BAR   # P_BAR   # P_BAR   # P_BAR   # P_BAR   # P_BAR   # P_BAR   # 10 #
        ####################################################################################################
        self.text_box = Text(master, wrap='char', width=80, height=16)
        self.vscroll_text_box = Scrollbar(
            master, orient='vertical', command=self.text_box.yview())
        self.hscroll_text_box = Scrollbar(
            master, orient='horizontal', command=self.text_box.xview())
        self.text_box.config(yscrollcommand=self.vscroll_text_box.set,
                             xscrollcommand=self.hscroll_text_box.set)
        self.text_box.grid(row=2, column=2, rowspan=4, columnspan=7)
        self.vscroll_text_box.grid(
            row=2, column=9, rowspan=4, sticky=('se', 'ne'))
        self.hscroll_text_box.grid(
            row=6, column=2, columnspan=8, sticky=('we', 'ne'))
        #
        #
        # Настройки формата файла
        self.labelframe_format = LabelFrame(
            master, text="Формат файла")
        self.labelframe_format.grid(
            row=7, column=1, columnspan=1, rowspan=3, sticky='wens')
        self.format_output_file = IntVar()
        self.format_output_file.set(0)
        self.radiobutton_pdf = Radiobutton(self.labelframe_format, text='Формат PDF',
                                           variable=self.format_output_file, value=0, command=self.shutdown_button)
        self.radiobutton_jpg = Radiobutton(self.labelframe_format, text='Формат JPEG',
                                           variable=self.format_output_file, value=1, command=self.shutdown_button)
        self.radiobutton_pdf.pack(fill='x')
        self.radiobutton_jpg.pack(fill='x')
        #
        #
        # Задаём фрейм в котором будем размещать настройки разделения
        self.labelframe_split = LabelFrame(master, text="Развибка на страницы")
        self.labelframe_split.grid(
            row=7, column=2, columnspan=2, rowspan=3, sticky='wens')
        self.scale_split = Scale(self.labelframe_split, from_=0, to=100,
                                 resolution=5, orient="horizontal")
        self.scale_split.pack(fill='both')
        #
        #
        # Задаём фрейм в котором будем размещать настройки качества файла
        self.labelframe_dpi = LabelFrame(master, text="Настройки качества")
        self.labelframe_dpi.grid(
            row=7, column=4, columnspan=2, rowspan=3, sticky='wens')
        self.dpi = IntVar()
        self.dpi.set(2)
        self.radiobutton_dpi_72 = Radiobutton(self.labelframe_dpi, text='Среднее',
                                              variable=self.dpi, value=0)
        self.radiobutton_dpi_100 = Radiobutton(self.labelframe_dpi, text='Хорошее',
                                               variable=self.dpi, value=1)
        self.radiobutton_dpi_150 = Radiobutton(self.labelframe_dpi, text='Отличное',
                                               variable=self.dpi, value=2)
        self.radiobutton_dpi_72.pack(fill='both')
        self.radiobutton_dpi_100.pack(fill='both')
        self.radiobutton_dpi_150.pack(fill='both')
        #
        #
        # Фрейм с настройками выбора цветное или ч/б
        self.labelframe_color = LabelFrame(master, text="Настройки цвета")
        self.labelframe_color.grid(
            row=7, column=6, columnspan=2, rowspan=3, sticky='wens')
        self.color = IntVar()
        self.color.set(0)
        self.radiobutton_bw = Radiobutton(self.labelframe_color, text='Чёрно/белое',
                                          variable=self.color, value=0)
        self.radiobutton_color = Radiobutton(self.labelframe_color, text='Цветное',
                                             variable=self.color, value=1)
        self.radiobutton_bw.pack(fill='both')
        self.radiobutton_color.pack(fill='both')
        #
        #
        # Фрейм с настройками качества сжатия JPEG
        self.labelframe_quality = LabelFrame(
            master, text="Настройка сжатия файла")
        self.labelframe_quality.grid(
            row=7, column=8, columnspan=2, rowspan=3, sticky='nw ne')
        self.scale_quality = Scale(self.labelframe_quality, label='Хуже                   Лучше', from_=1, to=100,
                                   resolution=1, orient="horizontal", state='active')
        self.scale_quality.set(100)
        self.scale_quality.pack(fill='both')
        #
        #
        # Чекбокс настройки оптимизации качества
        self.optimize_image = BooleanVar()
        self.optimize_image.set(False)
        self.checkbutton_optimize = Checkbutton(
            self.labelframe_quality, text='Автоматически', variable=self.optimize_image, onvalue=True, offvalue=False)
        self.checkbutton_optimize.pack()
        self.checkbutton_optimize.bind(
            '<Button>', lambda event: self.change_state(event))
        #
        #
        # Задаем фрейм в котором будем размещать основные кнопки команд
        self.button_frame = Frame(master)
        self.button_frame.grid(row=2, column=1, rowspan=4)
        self.button_open = Button(self.button_frame, text="Добавить файлы",
                                  command=self.listFiles, state='active', pady=5, padx=8)
        self.button_open.pack()
        self.button_save = Button(self.button_frame, text="Сохранить файл",
                                  command=self.savefileName, state='active', pady=5, padx=9)
        self.button_save.pack()
        self.button_run = Button(self.button_frame, text="Запустить",
                                 command=lambda x=True: ConvertFile().process(
                                     input_file=self.list_files, output_file=self.filename,
                                     format_file=self.FORMAT[self.format_output_file.get(
                                     )], dpi=self.SETTINGS_DPI[self.dpi.get()], color=self.SETTINGS_COLOR[self.color.get()],
                                     optimize=self.optimize_image.get(),
                                     quality=self.scale_quality.get(), split_step=self.scale_split.get()),
                                 state='active', pady=5, padx=26)
        self.button_run.pack()
        #
        #
        # Progressbar
        self.pbar = ttk.Progressbar(
            master, orient='horizontal', mode='determinate', length=100, maximum=100)
        self.pbar.grid(row=10, column=1, columnspan=9, sticky='wens')
        #
        #
        # Меню программы
        self.menu = Menu(master)
        master.config(menu=self.menu)
        self.sub_menu1 = Menu(self.menu)
        self.menu.add_cascade(label='Файл', menu=self.sub_menu1)
        self.sub_menu1.add_command(label='Выход', command=self.closed_window)
        self.sub_menu2 = Menu(self.menu)
        self.menu.add_cascade(label='Информация', menu=self.sub_menu2)
        self.sub_menu2.add_command(
            label='О программе', command=self.show_about)

    def frange(self, start, stop, step):
        while start < stop:
            yield start
            start += step

    def change_state(self, event):
        if self.optimize_image.get() is False:
            self.scale_quality.config(state='disable')
        else:
            self.scale_quality.config(state='active')

    def shutdown_button(self):
        if self.format_output_file.get() == 1:
            self.button_save.config(state='disable')
        else:
            self.button_save.config(state='active')

    def update_progressbar(self, page):
        step = 100 / self.lenght_list_files
        step_range = list(self.frange(0, 100, step))
        self.pbar['value'] = step_range[page] + step
        root.update()

    def show_about(self):
        messagebox.showinfo(
            title='О программе', message=ABOUT)

    def show_error(self, message):
        messagebox.showerror(title='ОШИБКА', message=message)

    def closed_window(self):
        root.quit()

    def listFiles(self):
        """ Функция привязана к кнопке "Добавить файлы". Результат работы функции - список файлов, который отображается в поле text_box """
        self.list_files = filedialog.askopenfilenames()
        self.lenght_list_files = len(self.list_files)
        self.text_box.delete(1.0, END)
        for i in self.list_files:
            self.text_box.insert(END, i)
            self.text_box.insert(END, '\n')
        return self.list_files

    def savefileName(self):
        """ Функция привязана к кнопке "Сохранить файл". Результат работы функции - полный путь к выходному файлу """
        default = self.FORMAT[0]
        setting_format = self.FORMAT[self.format_output_file.get()]
        self.filename = filedialog.asksaveasfilename(filetypes=[(f"Формат файла *{setting_format}",
                                                                 f"*{setting_format}")],
                                                     defaultextension=default)
        return self.filename
Exemple #21
0
	def start_options_frame(self,chosen_dir=None):
		self.p2d = par2deep(chosen_dir)

		self.args = {}

		subframe = Frame(self)

		basicset = LabelFrame(subframe, text="Basic Settings",pad=10)
		basicset.pack(fill=X,pady=(0,20))
		advset = LabelFrame(subframe, text="Advanced Settings",pad=10)
		advset.pack(fill=X)

		def pickdir():
			# self.args["directory"].delete(0,END)
			# self.args["directory"].insert(0,filedialog.askdirectory())
			# self.p2d.__init__(self.args["directory"].get())
			self.new_window(self.topbar_frame(0), self.start_options_frame(filedialog.askdirectory()), self.start_actions_frame())
		Button(basicset, text="Pick directory", command=pickdir).pack(side='left')
		self.args["directory"] = Entry(basicset)
		self.args["directory"].pack(fill=X)
		if chosen_dir == None:
			self.args["directory"].insert(0,self.p2d.args["directory"])
		else:
			self.args["directory"].insert(0,chosen_dir)

		self.args["overwrite"] = IntVar()
		self.args["overwrite"].set(self.p2d.args["overwrite"])
		cb1 = Checkbutton(advset, text="Overwrite all parity data", variable=self.args["overwrite"])
		cb1.pack(fill=X)
		CreateToolTip(cb1,"Any existing parity data found (any *.par* files) will be removed and overwritten.")

		self.args["noverify"] = IntVar()
		self.args["noverify"].set(self.p2d.args["noverify"])
		cb2 = Checkbutton(advset, text="Skip verification", variable=self.args["noverify"])
		cb2.pack(fill=X)
		CreateToolTip(cb2,"Skips verification of files with existing parity data. Use when you only want to create parity data for new files.")

		self.args["keep_old"] = IntVar()
		self.args["keep_old"].set(self.p2d.args["keep_old"])
		cb3 = Checkbutton(advset, text="Keep old parity files or par2 backup files", variable=self.args["keep_old"])
		cb3.pack(fill=X)
		CreateToolTip(cb3,"Do not remove par backup files (*.[0-9]) and do not remove unused parity files (*.par*).")

		Label(advset, text="Exclude directories (comma separated)").pack(fill=X)
		self.args["excludes"] = Entry(advset)
		self.args["excludes"].pack(fill=X)
		self.args["excludes"].insert(0,','.join(self.p2d.args["excludes"]))
		CreateToolTip(self.args["excludes"],"These subdirectories will be excluded from the analysis. Use 'root' for the root of the directory.")

		Label(advset, text="Exclude extensions (comma separated)").pack(fill=X)
		self.args["extexcludes"] = Entry(advset)
		self.args["extexcludes"].pack(fill=X)
		self.args["extexcludes"].insert(0,','.join(self.p2d.args["extexcludes"]))
		CreateToolTip(self.args["extexcludes"],"These extensions will be excluded from the analysis.")

		Label(advset, text="Path to par2.exe").pack(fill=X)
		self.args["par_cmd"] = Entry(advset)
		self.args["par_cmd"].pack(fill=X)
		self.args["par_cmd"].insert(0,self.p2d.args["par_cmd"])
		CreateToolTip(self.args["par_cmd"],"Should be set automatically and correctly, but can be overriden.")

		Label(advset, text="Percentage of protection").pack(fill=X)
		self.args["percentage"] = IntVar()
		self.args["percentage"].set(self.p2d.args["percentage"])
		s1 = Scale(advset,orient=HORIZONTAL,from_=5,to=100,resolution=1,variable=self.args["percentage"])
		s1.pack(fill=X)
		CreateToolTip(s1,"The maximum percentage of corrupted data you will be able to recover from. Higher is safer, but uses more data.")

		return subframe
Exemple #22
0
class ipGUI:
    def __init__(self, master):
        self.master = master
        self.master.minsize(width=800, height=600)

        menu = Menu(self.master)
        master.config(menu=menu)

        # ***** Main Menu *****
        # *** file menu ***
        fileMenu = Menu(menu)
        menu.add_cascade(label='File', menu=fileMenu)
        fileMenu.add_command(label="Open", command=self.openImage)
        fileMenu.add_command(label="Load Blur Kernel", command=self.loadKernel)
        fileMenu.add_command(label="Save", command=self.saveImage)
        fileMenu.add_command(label="Exit", command=master.destroy)

        # *** edit menu ***
        editMenu = Menu(menu)
        menu.add_cascade(label='Space', menu=editMenu)
        editMenu.add_command(label="Histogram Equalization",
                             command=self.histWrap)
        editMenu.add_command(label="Gamma Correction",
                             command=self.gammaCorWrap)
        editMenu.add_command(label="Log Transform", command=self.logTranWrap)
        editMenu.add_command(label="Sharpen", command=self.sharpWrap)
        editMenu.add_command(label="Cartoonify", command=self.cartoonifyWrap)

        # *** blur menu ***
        blurMenu = Menu(editMenu)
        editMenu.add_cascade(label='Blur', menu=blurMenu)
        blurMenu.add_command(label="Box", command=self.boxBlurWrap)
        blurMenu.add_command(label="Gaussian", command=self.gaussianBlurWrap)
        blurMenu.add_command(label="Median", command=self.medianBlurWrap)

        # *** frequency filtering ***
        freqMenu = Menu(menu)
        menu.add_cascade(label='Frequency', menu=freqMenu)
        freqMenu.add_command(label="DFT", command=self.dftWrap)
        freqMenu.add_command(label="Load Mask", command=self.freqMaskWrap)

        # *** Mask Menu ***
        maskMenu = Menu(freqMenu)
        freqMenu.add_cascade(label='Create Mask', menu=maskMenu)
        maskMenu.add_command(label='Low Pass', command=self.lpmWrap)
        maskMenu.add_command(label='High Pass', command=self.hpmWrap)
        maskMenu.add_command(label='Band Pass', command=self.bppmWrap)
        maskMenu.add_command(label='Band Stop', command=self.bspmWrap)

        # *** frequency filtering ***
        restorationMenu = Menu(menu)
        menu.add_cascade(label='Restoration', menu=restorationMenu)
        restorationMenu.add_command(label="Full Inverse",
                                    command=self.fullInverseWrap)
        restorationMenu.add_command(label="Radially Limited Inverse",
                                    command=self.truncatedInverseWrap)
        restorationMenu.add_command(label="Approximate Weiner",
                                    command=self.approximateWeinerWrap)
        restorationMenu.add_command(label="Constrained LS",
                                    command=self.contrainedLSWrap)

        # ***** Toolbar *****
        toolbar = Frame(master, bg="grey")
        undoButton = Button(toolbar, text="Undo", command=self.undoFunc)
        undoButton.pack(side=LEFT)
        origButton = Button(toolbar, text="Original", command=self.origFunc)
        origButton.pack(side=LEFT)
        toolbar.pack(side=TOP, fill=X)

        # ***** Image Display Area *****
        self.frame = Frame(self.master)
        self.frame.pack()
        self.panel = Label(self.frame)
        self.panel.pack(padx=10, pady=10)
        self.img = None
        self.origImg = None
        self.prevImg = None

        # ***** Gamma Controls *****
        self.gammaFrame = Frame(self.master)
        self.gammaSlider = Scale(self.gammaFrame,
                                 from_=0.1,
                                 to=2,
                                 orient=HORIZONTAL,
                                 resolution=0.1)
        self.gammaSlider.pack(side=TOP)
        self.gammaExitButton = Button(self.gammaFrame,
                                      text="Exit",
                                      command=self.gammaFrame.pack_forget)
        self.gammaExitButton.pack(side=TOP)

        # ***** Box Blur Controls *****
        self.boxFrame = Frame(self.master)
        self.boxSlider = Scale(self.boxFrame, from_=1, to=5, orient=HORIZONTAL)
        self.boxSlider.pack(side=TOP)
        self.boxExitButton = Button(self.boxFrame,
                                    text="Exit",
                                    command=self.boxFrame.pack_forget)
        self.boxExitButton.pack(side=TOP)

        # ***** Truncated Inverse Controls *****
        self.truncatedInverseFrame = Frame(self.master)
        self.truncatedInverseSlider = Scale(self.truncatedInverseFrame,
                                            from_=-3,
                                            to=2,
                                            orient=HORIZONTAL,
                                            resolution=0.1)
        self.truncatedInverseSlider.pack(side=TOP)
        self.truncatedInverseExitButton = Button(
            self.truncatedInverseFrame,
            text="Exit",
            command=self.truncatedInverseFrame.pack_forget)
        self.truncatedInverseExitButton.pack(side=TOP)

        # ***** Weiner Controls *****
        self.weinerFrame = Frame(self.master)
        self.weinerSlider = Scale(self.weinerFrame,
                                  from_=-3,
                                  to=2,
                                  orient=HORIZONTAL,
                                  resolution=0.1)
        self.weinerSlider.pack(side=TOP)
        self.weinerExitButton = Button(self.weinerFrame,
                                       text="Exit",
                                       command=self.weinerFrame.pack_forget)
        self.weinerExitButton.pack(side=TOP)

        # ***** CLS Controls *****
        self.clsFrame = Frame(self.master)
        self.clsSlider = Scale(self.clsFrame,
                               from_=-3,
                               to=2,
                               orient=HORIZONTAL,
                               resolution=0.1)
        self.clsSlider.pack(side=TOP)
        self.clsExitButton = Button(self.clsFrame,
                                    text="Exit",
                                    command=self.clsFrame.pack_forget)
        self.clsExitButton.pack(side=TOP)

        # ***** DFT Display Area ******
        self.dftFrame = Frame(self.master)
        self.magPanel = Label(self.dftFrame)
        self.magPanel.pack(padx=10, pady=10, side=TOP)
        self.freqPanel = Label(self.dftFrame)
        self.freqPanel.pack(padx=10, pady=10, side=TOP)
        self.dftExitButton = Button(
            self.dftFrame,
            text="Exit",
            command=lambda: self.displayImg(np.array(self.img)))
        self.dftExitButton.pack(side=TOP, fill=X)

        # ***** Low Pass Mask Creation *****
        self.lpmFrame = Frame(self.master)
        self.lpmPanel = Label(self.lpmFrame)
        self.lpmPanel.pack(padx=10, pady=10, side=TOP)
        self.lpmSubButton = Button(self.lpmFrame, text="submit")
        self.lpmSubButton.pack(side=TOP)
        self.lpmExitButton = Button(
            self.lpmFrame,
            text="Exit",
            command=lambda: self.displayImg(np.array(self.img)))
        self.lpmExitButton.pack(side=TOP)
        self.lpmSlider = Scale(self.lpmFrame,
                               from_=1,
                               to=2,
                               orient=HORIZONTAL,
                               resolution=1)

        # ***** High Pass Mask Creation *****
        self.hpmFrame = Frame(self.master)
        self.hpmPanel = Label(self.hpmFrame)
        self.hpmPanel.pack(padx=10, pady=10, side=TOP)
        self.hpmSubButton = Button(self.hpmFrame, text="submit")
        self.hpmSubButton.pack(side=TOP)
        self.hpmExitButton = Button(
            self.hpmFrame,
            text="Exit",
            command=lambda: self.displayImg(np.array(self.img)))
        self.hpmExitButton.pack(side=TOP)
        self.hpmSlider = Scale(self.hpmFrame,
                               from_=1,
                               to=2,
                               orient=HORIZONTAL,
                               resolution=1)

        # ***** Band Pass Mask Creation *****
        self.bppmFrame = Frame(self.master)
        self.bppmPanel = Label(self.bppmFrame)
        self.bppmPanel.pack(padx=10, pady=10, side=TOP)
        self.bppmSubButton = Button(self.bppmFrame, text="submit")
        self.bppmSubButton.pack(side=TOP)
        self.bppmExitButton = Button(
            self.bppmFrame,
            text="Exit",
            command=lambda: self.displayImg(np.array(self.img)))
        self.bppmExitButton.pack(side=TOP)
        self.bppmSliderLow = Scale(self.bppmFrame,
                                   from_=1,
                                   to=2,
                                   orient=HORIZONTAL,
                                   resolution=1)
        self.bppmSliderHigh = Scale(self.bppmFrame,
                                    from_=1,
                                    to=2,
                                    orient=HORIZONTAL,
                                    resolution=1)

        # ***** Band Pass Mask Creation *****
        self.bspmFrame = Frame(self.master)
        self.bspmPanel = Label(self.bspmFrame)
        self.bspmPanel.pack(padx=10, pady=10, side=TOP)
        self.bspmSubButton = Button(self.bspmFrame, text="submit")
        self.bspmSubButton.pack(side=TOP)
        self.bspmExitButton = Button(
            self.bspmFrame,
            text="exit",
            command=lambda: self.displayImg(np.array(self.img)))
        self.bspmExitButton.pack(side=TOP)
        self.bspmSliderLow = Scale(self.bspmFrame,
                                   from_=1,
                                   to=2,
                                   orient=HORIZONTAL,
                                   resolution=1)
        self.bspmSliderHigh = Scale(self.bspmFrame,
                                    from_=1,
                                    to=2,
                                    orient=HORIZONTAL,
                                    resolution=1)

    def displayImg(self, img):
        # input image in RGB
        self.frame.pack()
        self.dftFrame.pack_forget()
        self.lpmFrame.pack_forget()
        self.hpmFrame.pack_forget()
        self.bppmFrame.pack_forget()
        self.bspmFrame.pack_forget()
        self.img = Image.fromarray(img)
        imgtk = ImageTk.PhotoImage(self.img)

        self.panel.configure(image=imgtk)
        self.panel.image = imgtk

    def openImage(self):
        # can change the image
        path = filedialog.askopenfilename()
        if len(path) > 0:
            imgRead = cv2.imread(path)
            if imgRead is not None:
                imgRead = cv2.cvtColor(imgRead, cv2.COLOR_BGR2RGB)
                self.origImg = Image.fromarray(imgRead)
                self.prevImg = Image.fromarray(imgRead)
                self.displayImg(imgRead)
            else:
                raise ValueError("Not a valid image")
        else:
            raise ValueError("Not a valid path")

    def loadKernel(self):
        path = filedialog.askopenfilename()
        if len(path) > 0:
            self.filter_kernel = np.mean(cv2.imread(path), axis=-1)
            self.filter_kernel = self.filter_kernel / np.sum(
                self.filter_kernel)
        else:
            raise ValueError("Not a valid path")

    def saveImage(self):
        if self.img is not None:
            toSave = filedialog.asksaveasfilename()
            self.img.save(toSave)
        else:
            messagebox.showerror(title="Save Error",
                                 message="No image to be saved!")

    def histWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.histEqlFunc(img)
        self.displayImg(imgNew)

    # Gamma Correction
    def gammaCallback(self, event, img):
        gamma = self.gammaSlider.get()
        self.prevImg = self.img
        imgNew = image_utils.gammaCorFunc(img, 255.0 / (255.0**gamma), gamma)
        self.displayImg(imgNew)

    def truncatedInverseCallback(self, event, img):
        th = 10**self.truncatedInverseSlider.get()
        imgNew = self.truncatedInverseFilter(th)
        self.displayImg(imgNew)

    def weinerCallback(self, event, img):
        gamma = 10**self.weinerSlider.get()
        imgNew = self.weinerFilter(gamma)
        self.displayImg(imgNew)

    def clsCallback(self, event, img):
        K = 10**self.clsSlider.get()
        imgNew = self.clsFilter(K)
        self.displayImg(imgNew)

    def gammaCorWrap(self):
        img = np.array(self.img)
        self.gammaFrame.pack()
        self.gammaSlider.set(1.0)
        self.gammaSlider.bind(
            "<ButtonRelease-1>",
            lambda event, img=img: self.gammaCallback(event, img))

    def logTranWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.logTranFunc(img, 255.0 / np.log10(256))
        self.displayImg(imgNew)

    def sharpWrap(self):
        # Sharpen Wrapper
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.sharpFunc(img)
        self.displayImg(imgNew)

    def boxBlurWrap(self):
        # Box Blur Wrapper
        img = np.array(self.img)
        self.prevImg = self.img
        self.boxFrame.pack()
        self.boxSlider.set(1)
        self.boxSlider.bind("<ButtonRelease-1>",
                            lambda event, img=img: self.displayImg(
                                image_utils.boxBlurFunc(
                                    event, img, 2 * self.boxSlider.get() + 1)))

    def gaussianBlurWrap(self):
        # Gaussian Blur Wrapper
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.gaussianBlurFunc(img)
        self.displayImg(imgNew)

    def medianBlurWrap(self):
        # Median Blur Wrapper
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.medianBlurFunc(img)
        self.displayImg(imgNew)

    def cartoonifyWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = image_utils.cartoonifyFunc(img)
        self.displayImg(imgNew)

    def undoFunc(self):
        self.img = self.prevImg
        self.displayImg(np.array(self.img))

    def origFunc(self):
        self.prevImg = self.img
        self.img = self.origImg
        self.displayImg(np.array(self.img))

    def displayDFT(self, x_fft):
        m, n = x_fft.shape[:]
        self.frame.pack_forget()
        self.dftFrame.pack()

        x_mag = np.log10(np.absolute(x_fft)) * 255 / np.log10(m * n * 255)
        x_mag = Image.fromarray(x_mag)
        x_mag = x_mag.resize((min(256, m), min(int(256 * n / m), n)),
                             Image.ANTIALIAS)
        x_mag = ImageTk.PhotoImage(x_mag)

        x_freq = (np.angle(x_fft) % 360) * 255 / 360
        x_freq = Image.fromarray(x_freq)
        x_freq = x_freq.resize((min(256, m), min(int(256 * n / m), n)),
                               Image.ANTIALIAS)
        x_freq = ImageTk.PhotoImage(x_freq)

        self.magPanel.configure(image=x_mag)
        self.magPanel.image = x_mag

        self.freqPanel.configure(image=x_freq)
        self.freqPanel.image = x_freq

    def dftWrap(self):
        img = np.array(self.img)
        x = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        x_outp_img = fft.fft2d_img(x)
        self.displayDFT(x_outp_img)

    def freqMaskWrap(self):
        m, n = np.array(self.img).shape[:2]
        lm, ln = np.log2(m), np.log2(m)
        dm, dn = int(2**np.ceil(lm)) + 1, int(2**np.ceil(ln)) + 1
        messagebox.showinfo(
            "Mask Size",
            "Mask Size should be (" + str(dm) + "," + str(dn) + ")")
        path = filedialog.askopenfilename()
        if len(path) > 0:
            maskRead = cv2.imread(path, 0)
            if (maskRead.shape != (dm, dn)):
                messagebox.showerror(
                    title="Shape Error",
                    message="Shape of mask and image don't match")
            else:
                self.prevImg = self.img
                self.display(image_utils.freqMask(np.array(self.img),
                                                  maskRead))
        else:
            raise ValueError("Not a valid path")

    def maskWrap(self):
        img = np.array(self.img)
        x = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        x_outp_img = fft.fft2d_img(x)
        x_mag = image_utils.xMagCreate(x_outp_img)

        return x_outp_img, x_mag

    def maskFinal(self, x_outp_img):
        self.prevImg = self.img
        img = np.array(self.img)
        img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
        m = len(img)
        res = fft.ifft2d_img(x_outp_img)
        res = np.array(res * 255 / np.max(res), dtype=np.uint8)
        res = np.array([[[img[i][j][0], img[i][j][1], res[i][j]]
                         for j in range(m)] for i in range(m)])
        res = cv2.cvtColor(res, cv2.COLOR_HSV2RGB)
        self.displayImg(res)

    def lpmCallBack(self, event, slider, x_outp_img):
        m = len(x_outp_img)
        m2 = int((m - 1) / 2)
        r = slider.get()
        x_outp_copy = np.copy(x_outp_img)

        nCircle = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(m)]
                            for i in range(m)])
        nCircle = np.where(nCircle > r**2)
        x_outp_copy[nCircle] = 1

        x_mag = image_utils.xMagCreate(x_outp_copy)

        self.lpmPanel.configure(image=x_mag)
        self.lpmPanel.image = x_mag

    def lpmFinal(self, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r = self.lpmSlider.get()
        nCircle = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                            for i in range(mx)])
        nCircle = np.where(nCircle > r**2)
        x_outp_img[nCircle] = 0

        self.maskFinal(x_outp_img)

    def lpmWrap(self):
        x_outp_img, x_mag = self.maskWrap()
        m = len(x_outp_img)

        self.lpmPanel.configure(image=x_mag)
        self.lpmPanel.image = x_mag

        self.lpmSlider.configure(to=int(np.ceil(m / 2)))
        self.lpmSlider.set(1)
        self.lpmSlider.pack(side=TOP)
        self.lpmSlider.bind(
            "<ButtonRelease-1>",
            lambda event, slider=self.lpmSlider, x_outp_img=x_outp_img: self.
            lpmCallBack(event, slider, x_outp_img))

        self.lpmSubButton.configure(
            command=lambda x_outp_img=x_outp_img: self.lpmFinal(x_outp_img))

        self.dftFrame.pack_forget()
        self.frame.pack_forget()
        self.hpmFrame.pack_forget()
        self.bppmFrame.pack_forget()
        self.bspmFrame.pack_forget()
        self.lpmFrame.pack()

    def hpmCallBack(self, event, slider, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r = slider.get()
        x_outp_copy = np.copy(x_outp_img)

        circle = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                           for i in range(mx)])
        circle = np.where(circle <= r**2)
        x_outp_copy[circle] = 1

        x_mag = image_utils.xMagCreate(x_outp_copy)

        self.hpmPanel.configure(image=x_mag)
        self.hpmPanel.image = x_mag

    def hpmFinal(self, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r = self.hpmSlider.get()
        circle = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                           for i in range(mx)])
        circle = np.where(circle <= r**2)
        x_outp_img[circle] = 0

        self.maskFinal(x_outp_img)

    def hpmWrap(self):
        x_outp_img, x_mag = self.maskWrap()
        m = len(x_outp_img)

        self.hpmPanel.configure(image=x_mag)
        self.hpmPanel.image = x_mag

        self.hpmSlider.configure(to=m // 2)
        self.hpmSlider.set(1)
        self.hpmSlider.pack(side=TOP)
        self.hpmSlider.bind(
            "<ButtonRelease-1>",
            lambda event, slider=self.hpmSlider, x_outp_img=x_outp_img: self.
            hpmCallBack(event, slider, x_outp_img))

        self.hpmSubButton.configure(
            command=lambda x_outp_img=x_outp_img: self.hpmFinal(x_outp_img))

        self.dftFrame.pack_forget()
        self.frame.pack_forget()
        self.lpmFrame.pack_forget()
        self.bppmFrame.pack_forget()
        self.bspmFrame.pack_forget()
        self.hpmFrame.pack()

    def bppmCallBack(self, event, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r1 = self.bppmSliderLow.get()
        r2 = self.bppmSliderHigh.get()
        assert (r1 <= r2)

        self.bppmSliderLow.configure(to=r2)
        self.bppmSliderHigh.configure(from_=r1)

        x_outp_copy = np.copy(x_outp_img)
        allVals = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                            for i in range(mx)])
        nullVals = np.where(allVals < r1**2)
        x_outp_copy[nullVals] = 1
        nullVals = np.where(allVals > r2**2)
        x_outp_copy[nullVals] = 1

        x_mag = image_utils.xMagCreate(x_outp_copy)

        self.bppmPanel.configure(image=x_mag)
        self.bppmPanel.image = x_mag

    def bppmFinal(self, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r1 = self.bppmSliderLow.get()
        r2 = self.bppmSliderHigh.get()

        allVals = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                            for i in range(mx)])
        nullVals = np.where(allVals < r1**2)
        x_outp_img[nullVals] = 0
        nullVals = np.where(allVals > r2**2)
        x_outp_img[nullVals] = 0

        self.maskFinal(x_outp_img)

    def bppmWrap(self):
        x_outp_img, x_mag = self.maskWrap()
        m = len(x_outp_img)

        self.bppmPanel.configure(image=x_mag)
        self.bppmPanel.image = x_mag

        self.bppmSliderHigh.configure(from_=1)
        self.bppmSliderHigh.configure(to=m // 2)
        self.bppmSliderHigh.set(m // 2)
        self.bppmSliderHigh.pack(side=TOP)
        self.bppmSliderHigh.bind("<ButtonRelease-1>",
                                 lambda event, x_outp_img=x_outp_img: self.
                                 bppmCallBack(event, x_outp_img))

        self.bppmSliderLow.configure(from_=1)
        self.bppmSliderLow.configure(to=m // 2)
        self.bppmSliderLow.set(1)
        self.bppmSliderLow.pack(side=TOP)
        self.bppmSliderLow.bind("<ButtonRelease-1>",
                                lambda event, x_outp_img=x_outp_img: self.
                                bppmCallBack(event, x_outp_img))

        self.bppmSubButton.configure(
            command=lambda x_outp_img=x_outp_img: self.bppmFinal(x_outp_img))

        self.dftFrame.pack_forget()
        self.frame.pack_forget()
        self.lpmFrame.pack_forget()
        self.hpmFrame.pack_forget()
        self.bspmFrame.pack_forget()
        self.bppmFrame.pack()

    def bspmCallBack(self, event, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r1 = self.bspmSliderLow.get()
        r2 = self.bspmSliderHigh.get()
        assert (r1 <= r2)

        self.bspmSliderLow.configure(to=r2)
        self.bspmSliderHigh.configure(from_=r1)

        x_outp_copy = np.copy(x_outp_img)
        allVals = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                            for i in range(mx)])
        nullVals = np.where((allVals - r1**2) * (allVals - r2**2) < 0)
        x_outp_copy[nullVals] = 1

        x_mag = image_utils.xMagCreate(x_outp_copy)

        self.bspmPanel.configure(image=x_mag)
        self.bspmPanel.image = x_mag

    def bspmFinal(self, x_outp_img):
        mx = len(x_outp_img)
        m2 = int((mx - 1) / 2)
        r1 = self.bspmSliderLow.get()
        r2 = self.bspmSliderHigh.get()

        allVals = np.array([[(i - m2)**2 + (j - m2)**2 for j in range(mx)]
                            for i in range(mx)])
        nullVals = np.where((allVals - r1**2) * (allVals - r2**2) < 0)
        x_outp_img[nullVals] = 0

        self.maskFinal(x_outp_img)

    def bspmWrap(self):
        x_outp_img, x_mag = self.maskWrap()
        m = len(x_outp_img)

        self.bspmPanel.configure(image=x_mag)
        self.bspmPanel.image = x_mag

        self.bspmSliderHigh.configure(from_=1)
        self.bspmSliderHigh.configure(to=m // 2)
        self.bspmSliderHigh.set(m // 2)
        self.bspmSliderHigh.pack(side=TOP)
        self.bspmSliderHigh.bind("<ButtonRelease-1>",
                                 lambda event, x_outp_img=x_outp_img: self.
                                 bspmCallBack(event, x_outp_img))

        self.bspmSliderLow.configure(from_=1)
        self.bspmSliderLow.configure(to=m // 2)
        self.bspmSliderLow.set(1)
        self.bspmSliderLow.pack(side=TOP)
        self.bspmSliderLow.bind("<ButtonRelease-1>",
                                lambda event, x_outp_img=x_outp_img: self.
                                bspmCallBack(event, x_outp_img))

        self.bspmSubButton.configure(
            command=lambda x_outp_img=x_outp_img: self.bspmFinal(x_outp_img))

        self.dftFrame.pack_forget()
        self.frame.pack_forget()
        self.lpmFrame.pack_forget()
        self.hpmFrame.pack_forget()
        self.bppmFrame.pack_forget()
        self.bspmFrame.pack()

    def fullInverseWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        imgNew = filtering.inverseFilter2D(img, self.filter_kernel)
        self.displayImg(imgNew)

    def truncatedInverseWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        self.truncatedInverseFilter = filtering.getTruncatedInverseFilter2D(
            img, self.filter_kernel)
        self.truncatedInverseFrame.pack()
        self.truncatedInverseSlider.set(1.0)
        self.truncatedInverseSlider.bind(
            "<ButtonRelease-1>",
            lambda event, img=img: self.truncatedInverseCallback(event, img))

    def approximateWeinerWrap(self):
        img = np.array(self.img)
        self.prevImg = self.img
        self.weinerFilter = filtering.getApproximateWeinerFilter2D(
            img, self.filter_kernel)
        self.weinerFrame.pack()
        self.weinerSlider.set(1.0)
        self.weinerSlider.bind(
            "<ButtonRelease-1>",
            lambda event, img=img: self.weinerCallback(event, img))

    def contrainedLSWrap(self):  # TODO: implement
        img = np.array(self.img)
        self.prevImg = self.img
        self.clsFilter = filtering.getConstrainedLSFilter2D(
            img, self.filter_kernel)
        self.clsFrame.pack()
        self.clsSlider.set(1.0)
        self.clsSlider.bind(
            "<ButtonRelease-1>",
            lambda event, img=img: self.clsCallback(event, img))
class TLight(TObject):
    def __init__(self, send_func, light, master=None):
        super().__init__(send_func, light, master)
        self._power_property_label.configure(text="Power:")
        self.__brightness_frame = None
        self.__brightness_property_label = None
        self.__brightness_property_scale = None
        self.__brightness_property_status_label = None
        self.__brightness_property_button = None
        self.__set_brightness_property__()
        self.__color_frame = None
        self.__color_property_label = None
        self.__color_property_combobox = None
        self.__color_property_status_label = None
        self.__color_property_button = None
        self.__set_color_property__()

    def __set_brightness_property__(self):
        self.__brightness_frame = Frame(self)
        self.__brightness_frame.pack()
        self.__brightness_property_label = Label(self.__brightness_frame,
                                                 text='Brightness:')
        self.__brightness_property_label.pack(side=LEFT, padx=3)
        self.__brightness_property_status_label = Label(
            self.__brightness_frame, text=f'(currently {self.obj.brightness})')
        self.__brightness_property_status_label.pack(side=LEFT, padx=3)
        self.__brightness_property_scale = Scale(self.__brightness_frame,
                                                 from_=0,
                                                 to=100,
                                                 orient=HORIZONTAL)
        self.__brightness_property_scale.set(50)
        self.__brightness_property_scale.pack(side=LEFT, padx=3)
        self.__brightness_property_button = Button(
            self.__brightness_frame,
            text='Change',
            command=self.__brightness_button_event__)
        self.__brightness_property_button.pack(side=LEFT, padx=3)

    def __set_color_property__(self):
        if self.obj.colors:
            self.__color_frame = Frame(self)
            self.__color_frame.pack()
            self.__color_property_label = Label(self.__color_frame,
                                                text='Color:')
            self.__color_property_label.pack(side=LEFT, padx=3)
            self.__color_property_status_label = Label(
                self.__color_frame,
                text=f'(currently {self.obj.current_color})')
            self.__color_property_status_label.pack(side=LEFT, padx=3)
            self.__color_property_combobox = ttk.Combobox(self.__color_frame,
                                                          state='readonly')
            self.__color_property_combobox['values'] = self.obj.colors
            self.__color_property_combobox.current(0)
            self.__color_property_combobox.pack(side=LEFT, padx=3, pady=5)
            self.__color_property_button = Button(
                self.__color_frame,
                text='Change',
                command=self.__color_button_event__)
            self.__color_property_button.pack(side=LEFT, padx=3)

    def __brightness_button_event__(self):
        self._send_func(
            self.obj.location,
            str('brightness=' + str(self.__brightness_property_scale.get())))

    def __update_brightness_property__(self):
        self.__brightness_property_status_label.configure(
            text=f'(currently {self.obj.brightness})')

    def __color_button_event__(self):
        self._send_func(self.obj.location,
                        str('color=' + self.__color_property_combobox.get()))

    def __update_color_property(self):
        self.__color_property_status_label.configure(
            text=f'(currently {self.obj.current_color})')

    def notify(self, information=None):
        if information is None:
            return
        elif information == 'power':
            self.__update_power_property__()
        elif information == 'brightness':
            self.__update_brightness_property__()
        elif information == 'color':
            self.__update_color_property()
class TelloUI(object):
    """
    Wrapper class to enable the GUI.
    """
    def __init__(self, tello):
        """
        Initializes all the element of the GUI, supported by Tkinter

        :param tello: class interacts with the Tello drone.
        """
        self.tello = tello  # videostream device
        self.thread = None  # thread of the Tkinter mainloop
        self.stopEvent = None

        # control variables
        self.distance = 0.1  # default distance for 'move' cmd
        self.degree = 30  # default degree for 'cw' or 'ccw' cmd

        # if the flag is TRUE,the auto-takeoff thread will stop waiting
        # for the response from tello
        self.quit_waiting_flag = False

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None

        # create buttons
        self.btn_landing = tki.Button(self.root,
                                      text='Open Command Panel',
                                      relief='raised',
                                      command=self.openCmdWindow)
        self.btn_landing.pack(side='bottom',
                              fill='both',
                              expand='yes',
                              padx=10,
                              pady=5)

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.stopEvent = threading.Event()

        # set a callback to handle when the window is closed
        self.root.wm_title('TELLO Controller')
        self.root.wm_protocol('WM_DELETE_WINDOW', self.on_close)

        # the sending_command will send command to tello every 5 seconds
        self.sending_command_thread = threading.Thread(
            target=self._sendingCommand)

    def _sendingCommand(self):
        """
        Starts a while loop that sends 'command' to tello every 5 second.

        :return: None
        """

        while True:
            self.tello.send_command('command')
            time.sleep(5)

    def _setQuitWaitingFlag(self):
        """
        Set the variable as TRUE; it will stop computer waiting for response from tello.

        :return: None
        """
        self.quit_waiting_flag = True

    def openCmdWindow(self):
        """
        Open the cmd window and initial all the button and text.

        :return: None
        """
        panel = Toplevel(self.root)
        panel.wm_title('Command Panel')

        # create text input entry
        text0 = tki.Label(
            panel,
            text=
            'This Controller map keyboard inputs to Tello control commands\n'
            'Adjust the trackbar to reset distance and degree parameter',
            font='Helvetica 10 bold')
        text0.pack(side='top')

        text1 = tki.Label(
            panel,
            text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n'
            'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n'
            'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n'
            'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right',
            justify='left')
        text1.pack(side='top')

        self.btn_landing = tki.Button(panel,
                                      text='Land',
                                      relief='raised',
                                      command=self.telloLanding)
        self.btn_landing.pack(side='bottom',
                              fill='both',
                              expand='yes',
                              padx=10,
                              pady=5)

        self.btn_takeoff = tki.Button(panel,
                                      text='Takeoff',
                                      relief='raised',
                                      command=self.telloTakeOff)
        self.btn_takeoff.pack(side='bottom',
                              fill='both',
                              expand='yes',
                              padx=10,
                              pady=5)

        # binding arrow keys to drone control
        self.tmp_f = tki.Frame(panel, width=100, height=2)
        self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w)
        self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s)
        self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a)
        self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d)
        self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)
        self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down)
        self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left)
        self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right)
        self.tmp_f.pack(side='bottom')
        self.tmp_f.focus_set()

        self.btn_landing = tki.Button(panel,
                                      text='Flip',
                                      relief='raised',
                                      command=self.openFlipWindow)
        self.btn_landing.pack(side='bottom',
                              fill='both',
                              expand='yes',
                              padx=10,
                              pady=5)

        self.distance_bar = Scale(panel,
                                  from_=0.02,
                                  to=5,
                                  tickinterval=0.01,
                                  digits=3,
                                  label='Distance(m)',
                                  resolution=0.01)
        self.distance_bar.set(0.2)
        self.distance_bar.pack(side='left')

        self.btn_distance = tki.Button(
            panel,
            text='Reset Distance',
            relief='raised',
            command=self.updateDistancebar,
        )
        self.btn_distance.pack(side='left',
                               fill='both',
                               expand='yes',
                               padx=10,
                               pady=5)

        self.degree_bar = Scale(panel,
                                from_=1,
                                to=360,
                                tickinterval=10,
                                label='Degree')
        self.degree_bar.set(30)
        self.degree_bar.pack(side='right')

        self.btn_distance = tki.Button(panel,
                                       text='Reset Degree',
                                       relief='raised',
                                       command=self.updateDegreebar)
        self.btn_distance.pack(side='right',
                               fill='both',
                               expand='yes',
                               padx=10,
                               pady=5)

    def openFlipWindow(self):
        """
        Open the flip window and initial all the button and text.

        :return: None
        """
        panel = Toplevel(self.root)
        panel.wm_title('Gesture Recognition')

        self.btn_flipl = tki.Button(panel,
                                    text='Flip Left',
                                    relief='raised',
                                    command=self.telloFlip_l)
        self.btn_flipl.pack(side='bottom',
                            fill='both',
                            expand='yes',
                            padx=10,
                            pady=5)

        self.btn_flipr = tki.Button(panel,
                                    text='Flip Right',
                                    relief='raised',
                                    command=self.telloFlip_r)
        self.btn_flipr.pack(side='bottom',
                            fill='both',
                            expand='yes',
                            padx=10,
                            pady=5)

        self.btn_flipf = tki.Button(panel,
                                    text='Flip Forward',
                                    relief='raised',
                                    command=self.telloFlip_f)
        self.btn_flipf.pack(side='bottom',
                            fill='both',
                            expand='yes',
                            padx=10,
                            pady=5)

        self.btn_flipb = tki.Button(panel,
                                    text='Flip Backward',
                                    relief='raised',
                                    command=self.telloFlip_b)
        self.btn_flipb.pack(side='bottom',
                            fill='both',
                            expand='yes',
                            padx=10,
                            pady=5)

    def telloTakeOff(self):
        return self.tello.takeoff()

    def telloLanding(self):
        return self.tello.land()

    def telloFlip_l(self):
        return self.tello.flip('l')

    def telloFlip_r(self):
        return self.tello.flip('r')

    def telloFlip_f(self):
        return self.tello.flip('f')

    def telloFlip_b(self):
        return self.tello.flip('b')

    def telloCW(self, degree):
        return self.tello.rotate_cw(degree)

    def telloCCW(self, degree):
        return self.tello.rotate_ccw(degree)

    def telloMoveForward(self, distance):
        return self.tello.move_forward(distance)

    def telloMoveBackward(self, distance):
        return self.tello.move_backward(distance)

    def telloMoveLeft(self, distance):
        return self.tello.move_left(distance)

    def telloMoveRight(self, distance):
        return self.tello.move_right(distance)

    def telloUp(self, dist):
        return self.tello.move_up(dist)

    def telloDown(self, dist):
        return self.tello.move_down(dist)

    def updateDistancebar(self):
        self.distance = self.distance_bar.get()
        print(f'reset distance to {self.distance:.1f}')

    def updateDegreebar(self):
        self.degree = self.degree_bar.get()
        print(f'reset distance to {self.degree}')

    def on_keypress_w(self, event):
        print(f'up {self.distance} m')
        self.telloUp(self.distance)

    def on_keypress_s(self, event):
        print(f'down {self.distance} m')
        self.telloDown(self.distance)

    def on_keypress_a(self, event):
        print(f'ccw {self.degree} degree')
        self.tello.rotate_ccw(self.degree)

    def on_keypress_d(self, event):
        print(f'cw {self.degree} m')
        self.tello.rotate_cw(self.degree)

    def on_keypress_up(self, event):
        print(f'forward {self.distance} m')
        self.telloMoveForward(self.distance)

    def on_keypress_down(self, event):
        print(f'backward {self.distance} m')
        self.telloMoveBackward(self.distance)

    def on_keypress_left(self, event):
        print(f'left {self.distance} m')
        self.telloMoveLeft(self.distance)

    def on_keypress_right(self, event):
        print(f'right {self.distance} m')
        self.telloMoveRight(self.distance)

    def on_close(self):
        """
        Sets the stop event, cleanup the camera, and allow the rest of
        the quit process to continue.
        :return: None
        """
        print('[INFO] closing...')
        self.stopEvent.set()
        del self.tello
        self.root.quit()
FullScreen_state = tk.IntVar()
FullScreen_state.set(False) #set check state
chk = Checkbutton(window, text='Fullscreen', var=FullScreen_state)

#Volume Label
Volume_lbl = tk.Label(text="Volume", fg="black", width=15, height=1, font=ConfigFont)
Volume_lbl.pack(anchor=tk.W)

#Background Music Volume Label
BGMVolume_lbl = tk.Label(text="Background Music Volume", fg="black", width=25, height=1, font=ConfigFont)
BGMVolume_lbl.pack(anchor=tk.W)

#Background Music Volume Slider
BGMVol_Slider = Scale(window, from_=0, to=100, orient=HORIZONTAL, font=ConfigFont)
BGMVol_Slider.set(50)
BGMVol_Slider.pack(anchor=tk.W)

BGVolume = BGMVol_Slider.get()/10

#Sound Effects Volume Label
SFXVolume_lbl = tk.Label(text="Sound Effects Volume", fg="black", width=25, height=1, font=ConfigFont)
SFXVolume_lbl.pack(anchor=tk.W)

#Sound Effects Volume Slider
SFXVol_Slider = Scale(window, from_=0, to=100, orient=HORIZONTAL, font=ConfigFont)
SFXVol_Slider.set(50)
SFXVol_Slider.pack(anchor=tk.W)

Sound_Output = tk.IntVar()
Sound_Output.set(2)
Exemple #26
0
# 第8章.pptx, P155 & 156, program that uses a Scale control

from tkinter import Tk, Scale

winForm = Tk()

scale = Scale(winForm, from_=0, to=100, resolution=1, orient="horizontal")
scale.pack()

winForm.mainloop()
Exemple #27
0
    def start_options_frame(self, chosen_dir=None):
        self.p2d = par2deep(chosen_dir)

        self.args = {}

        subframe = Frame(self)

        basicset = LabelFrame(subframe, text="Basic Settings", pad=10)
        basicset.pack(fill=X, pady=(0, 20))
        advset = LabelFrame(subframe, text="Advanced Settings", pad=10)
        advset.pack(fill=X)

        def pickdir():
            # self.args["directory"].delete(0,END)
            # self.args["directory"].insert(0,filedialog.askdirectory())
            # self.p2d.__init__(self.args["directory"].get())
            self.new_window(
                self.topbar_frame(0),
                self.start_options_frame(filedialog.askdirectory()),
                self.start_actions_frame())

        Button(basicset, text="Pick directory",
               command=pickdir).pack(side='left')
        self.args["directory"] = Entry(basicset)
        self.args["directory"].pack(fill=X)
        if chosen_dir == None:
            self.args["directory"].insert(0, self.p2d.args["directory"])
        else:
            self.args["directory"].insert(0, chosen_dir)

        self.args["overwrite"] = IntVar()
        self.args["overwrite"].set(self.p2d.args["overwrite"])
        cb1 = Checkbutton(advset,
                          text="Overwrite all parity data",
                          variable=self.args["overwrite"])
        cb1.pack(fill=X)
        CreateToolTip(
            cb1,
            "Any existing parity data found (any *.par* files) will be removed and overwritten."
        )

        self.args["noverify"] = IntVar()
        self.args["noverify"].set(self.p2d.args["noverify"])
        cb2 = Checkbutton(advset,
                          text="Skip verification",
                          variable=self.args["noverify"])
        cb2.pack(fill=X)
        CreateToolTip(
            cb2,
            "Skips verification of files with existing parity data. Use when you only want to create parity data for new files."
        )

        self.args["keep_orphan"] = IntVar()
        self.args["keep_orphan"].set(self.p2d.args["keep_orphan"])
        cb3 = Checkbutton(advset,
                          text="Keep orphaned par2 files.",
                          variable=self.args["keep_orphan"])
        cb3.pack(fill=X)
        CreateToolTip(cb3, "Do not remove unused parity files (*.par*).")

        self.args["clean_backup"] = IntVar()
        self.args["clean_backup"].set(self.p2d.args["clean_backup"])
        cb3 = Checkbutton(advset,
                          text="Remove backup files",
                          variable=self.args["clean_backup"])
        cb3.pack(fill=X)
        CreateToolTip(cb3, "Remove backup files (*.[0-9]).")

        Label(advset,
              text="Exclude directories (comma separated)").pack(fill=X)
        self.args["excludes"] = Entry(advset)
        self.args["excludes"].pack(fill=X)
        self.args["excludes"].insert(0, ','.join(self.p2d.args["excludes"]))
        CreateToolTip(
            self.args["excludes"],
            "These subdirectories will be excluded from the analysis. Use 'root' for the root of the directory."
        )

        Label(advset, text="Exclude extensions (comma separated)").pack(fill=X)
        self.args["extexcludes"] = Entry(advset)
        self.args["extexcludes"].pack(fill=X)
        self.args["extexcludes"].insert(0,
                                        ','.join(self.p2d.args["extexcludes"]))
        CreateToolTip(self.args["extexcludes"],
                      "These extensions will be excluded from the analysis.")

        Label(advset, text="Path to par2.exe").pack(fill=X)
        self.args["par_cmd"] = Entry(advset)
        self.args["par_cmd"].pack(fill=X)
        self.args["par_cmd"].insert(0, self.p2d.args["par_cmd"])
        CreateToolTip(
            self.args["par_cmd"],
            "Should be set automatically and correctly, but can be overriden.")

        Label(advset, text="Percentage of protection").pack(fill=X)
        self.args["percentage"] = IntVar()
        self.args["percentage"].set(self.p2d.args["percentage"])
        s1 = Scale(advset,
                   orient=HORIZONTAL,
                   from_=5,
                   to=100,
                   resolution=1,
                   variable=self.args["percentage"])
        s1.pack(fill=X)
        CreateToolTip(
            s1,
            "The maximum percentage of corrupted data you will be able to recover from. Higher is safer, but uses more data."
        )

        return subframe
Exemple #28
0
class Simulator:
    def __init__(self):
        # MQTT Client
        self.client = mqtt.Client(client_id="simulator")
        self.client.connect("localhost", port=1883)

        # Window settings
        self.window = Tk()
        self.window.title(cnst.WINDOW_TITLE)
        self.window.geometry(
            str(cnst.WINDOW_WIDTH) + 'x' + str(cnst.WINDOW_HEIGHT))

        # Temperature slider
        self.temp_lbl = Label(self.window, text="Temperature")
        self.temp_lbl.pack(anchor=CENTER)
        self.temp_var = DoubleVar(value=cnst.DEFAULT_TEMP)
        self.slider_temperature = Scale(self.window,
                                        variable=self.temp_var,
                                        from_=cnst.MIN_TEMP,
                                        to_=cnst.MAX_TEMP,
                                        resolution=-1,
                                        orient=HORIZONTAL)
        self.slider_temperature.pack(anchor=CENTER)

        # API Temperature slider
        self.api_temp_lbl = Label(self.window, text="API Temperature")
        self.api_temp_lbl.pack(anchor=CENTER)
        self.api_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP)
        self.slider_api_temperature = Scale(self.window,
                                            variable=self.api_temp_var,
                                            from_=cnst.MIN_TEMP,
                                            to_=cnst.MAX_TEMP,
                                            resolution=-1,
                                            orient=HORIZONTAL)
        self.slider_api_temperature.pack(anchor=CENTER)

        # API Min temperature slider
        self.api_min_temp_lbl = Label(self.window, text="API Min Temperature")
        self.api_min_temp_lbl.pack(anchor=CENTER)
        self.api_min_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP)
        self.slider_api_min_temperature = Scale(self.window,
                                                variable=self.api_min_temp_var,
                                                from_=cnst.MIN_TEMP,
                                                to_=cnst.MAX_TEMP,
                                                resolution=-1,
                                                orient=HORIZONTAL)
        self.slider_api_min_temperature.pack(anchor=CENTER)

        # API Max temperature slider
        self.api_max_temp_lbl = Label(self.window, text="API Max Temperature")
        self.api_max_temp_lbl.pack(anchor=CENTER)
        self.api_max_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP)
        self.slider_api_max_temperature = Scale(self.window,
                                                variable=self.api_max_temp_var,
                                                from_=cnst.MIN_TEMP,
                                                to_=cnst.MAX_TEMP,
                                                resolution=-1,
                                                orient=HORIZONTAL)
        self.slider_api_max_temperature.pack(anchor=CENTER)

        # API Feels temperature slider
        self.api_feels_temp_lbl = Label(self.window,
                                        text="API Feels Temperature")
        self.api_feels_temp_lbl.pack(anchor=CENTER)
        self.api_feels_temp_var = DoubleVar(value=cnst.DEFAULT_TEMP)
        self.slider_api_feels_temperature = Scale(
            self.window,
            variable=self.api_feels_temp_var,
            from_=cnst.MIN_TEMP,
            to_=cnst.MAX_TEMP,
            resolution=-1,
            orient=HORIZONTAL)
        self.slider_api_feels_temperature.pack(anchor=CENTER)

        # API Humidity slider
        self.api_humidity_lbl = Label(self.window, text="API Humidity")
        self.api_humidity_lbl.pack(anchor=CENTER)
        self.api_humidity_var = DoubleVar(value=cnst.DEFAULT_HUMIDITY)
        self.slider_api_humidity = Scale(self.window,
                                         variable=self.api_humidity_var,
                                         from_=cnst.MIN_HUMIDITY,
                                         to_=cnst.MAX_HUMIDITY,
                                         resolution=-1,
                                         orient=HORIZONTAL)
        self.slider_api_humidity.pack(anchor=CENTER)

        # Luminosity slider
        self.luminosity_lbl = Label(self.window, text="Luminosity")
        self.luminosity_lbl.pack(anchor=CENTER)
        self.luminosity_var = DoubleVar(value=cnst.DEFAULT_LUMINOSITY)
        self.slider_luminosity = Scale(self.window,
                                       variable=self.luminosity_var,
                                       from_=cnst.MIN_LUMINOSITY,
                                       to_=cnst.MAX_LUMINOSITY,
                                       resolution=-1,
                                       orient=HORIZONTAL)
        self.slider_luminosity.pack(anchor=CENTER)

        # Humidity slider
        self.humidity_lbl = Label(self.window, text="Humidity")
        self.humidity_lbl.pack(anchor=CENTER)
        self.humidity_var = DoubleVar(value=cnst.DEFAULT_HUMIDITY)
        self.slider_humidity = Scale(self.window,
                                     variable=self.humidity_var,
                                     from_=cnst.MIN_HUMIDITY,
                                     to_=cnst.MAX_HUMIDITY,
                                     resolution=-1,
                                     orient=HORIZONTAL)
        self.slider_humidity.pack(anchor=CENTER)

        # Noise slider
        self.noise_lbl = Label(self.window, text="Noise")
        self.noise_lbl.pack(anchor=CENTER)
        self.noise_var = DoubleVar(value=cnst.DEFAULT_NOISE)
        self.slider_noise = Scale(self.window,
                                  variable=self.noise_var,
                                  from_=cnst.MIN_NOISE,
                                  to_=cnst.MAX_NOISE,
                                  resolution=-1,
                                  orient=HORIZONTAL)
        self.slider_noise.pack(anchor=CENTER)

        # Air Quality slider
        self.airquality_lbl = Label(self.window, text="AirQuality")
        self.airquality_lbl.pack(anchor=CENTER)
        self.airquality_var = DoubleVar(value=cnst.DEFAULT_AIRQUALITY)
        self.slider_airquality = Scale(self.window,
                                       variable=self.airquality_var,
                                       from_=cnst.MIN_AIRQUALITY,
                                       to_=cnst.MAX_AIRQUALITY,
                                       resolution=-1,
                                       orient=HORIZONTAL)
        self.slider_airquality.pack(anchor=CENTER)

        # Button to publish the data
        self.submit_btn = Button(self.window,
                                 text="Simulate",
                                 command=self.publish)
        self.submit_btn.pack(anchor=CENTER)

    def publish(self):
        self.client.publish(topic="temperature",
                            payload=self.slider_temperature.get(),
                            qos=1)
        self.client.publish(topic="weather_temp",
                            payload=self.slider_api_temperature.get(),
                            qos=1)
        self.client.publish(topic="weather_temp_min",
                            payload=self.slider_api_min_temperature.get(),
                            qos=1)
        self.client.publish(topic="weather_temp_max",
                            payload=self.slider_api_max_temperature.get(),
                            qos=1)
        self.client.publish(topic="weather_temp_feels",
                            payload=self.slider_api_feels_temperature.get(),
                            qos=1)
        self.client.publish(topic="weather_humidity",
                            payload=self.slider_api_humidity.get(),
                            qos=1)
        self.client.publish(topic="luminosity",
                            payload=self.slider_luminosity.get(),
                            qos=1)
        self.client.publish(topic="humidity",
                            payload=self.slider_humidity.get(),
                            qos=1)
        self.client.publish(topic="noise",
                            payload=self.slider_noise.get(),
                            qos=1)
        self.client.publish(topic="airquality",
                            payload=self.slider_airquality.get(),
                            qos=1)
        self.client.loop()

    def loop(self):
        self.window.mainloop()
Exemple #29
0
class GUI:
    def __init__(self):
        self.canvas_widget = None
        # create the maps from data source
        self.df = pd.read_csv(
            'datasets/data/time-series-19-covid-combined.txt')
        self.map_source = MapSource(self.df)

        # create main window- start of program
        self.root = tkinter.Tk()

        # user information (titles, instructions)
        self.root.wm_title('COVID-19 Case Growth')
        self.title = tkinter.Label(text="Covid-19 Interactive Data Explorer")
        self.title.pack(side='top')

        # shape of window
        self.root.geometry('800x700+100+100')

        # initialize map
        self.canvas_widget = self.get_map('0')

        # make the date chooser slider
        self.num_of_dates = self.df['Date'].nunique()
        self.dates = self.df['Date'].unique()
        self.scale = Scale(self.root,
                           label='Drag the slider to move forward in time.',
                           showvalue=0,
                           tickinterval=0,
                           from_=0,
                           to=self.num_of_dates,
                           command=lambda value: self.get_map(value),
                           orient='horizontal',
                           length=800)
        self.scale.pack(side='top')

        # bind escape to close program
        # bind a keystroke to a function
        self.root.bind('<Escape>', self.end_run)

        quit_button = tkinter.Button(text='Quit Explorer',
                                     command=self.end_run)
        quit_button.pack(side='bottom', fill='both')

        # creates the frame
        self.frame = tkinter.Frame(self.root)
        self.frame.pack(side='bottom')

        # activate the window-once everything is ready
        self.root.mainloop()

    def get_map(self, event):
        # create the drawing canvas to display the map
        if self.canvas_widget:
            self.canvas_widget.destroy()
        fig = self.map_source.date_world_map(event)
        canvas = FigureCanvasTkAgg(fig, master=self.root)
        canvas.draw()
        self.canvas_widget = canvas.get_tk_widget()
        self.canvas_widget.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

        self.root.update()
        return self.canvas_widget

    def end_run(self, event=None):
        self.root.destroy()
Exemple #30
0
class GUI:
    def __init__(self, master):

        self.master = master
        master.title("GUI")

        self.label = Label(master, text="Fluid Cell Control")
        self.label.pack()

        self.var1 = IntVar()
        self.check1 = Checkbutton(master,
                                  text="1",
                                  variable=self.var1,
                                  command=self.update_valve)
        self.check1.pack()

        self.var2 = IntVar()
        self.check2 = Checkbutton(master,
                                  text="2",
                                  variable=self.var2,
                                  command=self.update_valve)
        self.check2.pack()

        self.var3 = IntVar()
        self.check3 = Checkbutton(master,
                                  text="3",
                                  variable=self.var3,
                                  command=self.update_valve)
        self.check3.pack()

        self.var4 = IntVar()
        self.check4 = Checkbutton(master,
                                  text="4",
                                  variable=self.var4,
                                  command=self.update_valve)
        self.check4.pack()

        self.var5 = IntVar()
        self.check5 = Checkbutton(master,
                                  text="5",
                                  variable=self.var5,
                                  command=self.update_valve)
        self.check5.pack()

        self.var6 = IntVar()
        self.check6 = Checkbutton(master,
                                  text="6",
                                  variable=self.var6,
                                  command=self.update_valve)
        self.check6.pack()

        self.apply_button = Button(master,
                                   text="Apply",
                                   command=self.print_valve)
        self.apply_button.pack()

        self.speed = StringVar()
        self.speed_entry = Entry(master, textvariable=self.speed)
        self.speed_entry.pack()

        self.speed_scale = Scale(master,
                                 from_=0,
                                 to=255,
                                 variable=self.speed,
                                 orient=HORIZONTAL)
        self.speed_scale.pack()

        self.apply_speed = Button(master,
                                  text="Apply",
                                  command=self.print_speed)
        self.apply_speed.pack()

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

    def update_valve(self):
        return (str(self.var1.get()) + str(self.var2.get()) +
                str(self.var3.get()) + str(self.var4.get()) +
                str(self.var5.get()) + str(self.var6.get()))

    def print_valve(self):
        print(GUI.update_valve(self))
        valve_arr(GUI.update_valve(self))

    def print_speed(self):
        print(format(int(self.speed.get()), "08b"))
        s = format(int(self.speed.get()), "08b")
        pump_speed(s)
Exemple #31
0
def main():
    """
    основной метод - создание графического интерфейса TKinter
    :return:
    """
    global params
    window = Tk()
    window.title("Отражение в параболическом зеркале")
    window.geometry('500x400')
    canv = Frame(window)
    setup = LabelFrame(window, text='Настройки', width=450, height=150)
    c = Canvas(canv, width=450, height=230, bg='black')
    c.pack(side=TOP, padx=10)

    setup1 = Frame(setup)
    butFrame = Frame(setup1)

    scal = Scale(setup1,
                 orient=HORIZONTAL,
                 length=200,
                 from_=0.002,
                 to=0.01,
                 tickinterval=0.002,
                 resolution=0.002)
    scal.set(0.002)
    scal.pack(side=TOP, pady=(0, 10), padx=(10, 10))
    scal.bind("<ButtonRelease-1>",
              lambda event, draw_canv=c: redraw(event, draw_canv))

    Button(butFrame, text='Очистить', width=12,
           command=lambda event=None, draw_canv=c, flag=True: redraw(event, draw_canv,
                                                                     setarrow=flag)) \
        .pack(side=LEFT, padx=(10, 5), pady=(5, 10))
    Button(butFrame,
           text='Закрыть',
           width=12,
           command=lambda flag=0: sys.exit(flag)).pack(side=LEFT,
                                                       padx=(5, 10),
                                                       pady=(5, 10))

    butFrame.pack(side=TOP)

    setup1.pack(side=LEFT)

    columns = ('#1', '#2')
    params = Treeview(setup, show='headings', columns=columns)
    params.heading('#1', text='Параметр')
    params.heading('#2', text='Значение')
    params.column('#1', width=100, minwidth=50, stretch=NO, anchor=N)
    params.column('#2', width=100, minwidth=50, stretch=NO, anchor=N)
    params.pack(side=LEFT, padx=(5, 10), pady=(0, 10))

    canv.pack(side=TOP, pady=(10, 10))
    setup.pack(side=TOP, pady=(0, 10), padx=(25, 25))

    draw_parabola(c)

    window.bind('<Button-1>', press)
    window.bind('<ButtonRelease-1>',
                lambda event, draw_canv=c: release(event, draw_canv))
    window.mainloop()
class TelloUI:
    """Wrapper class to enable the GUI."""
    def __init__(self, tello, outputpath):
        """
        Initial all the element of the GUI,support by Tkinter

        :param tello: class interacts with the Tello drone.

        Raises:
            RuntimeError: If the Tello rejects the attempt to enter command mode.
        """

        self.tello = tello  # videostream device
        self.outputPath = outputpath  # the path that save pictures created by clicking the takeSnapshot button
        self.frame = None  # frame read from h264decoder and used for pose recognition
        self.thread = None  # thread of the Tkinter mainloop
        self.stopEvent = None

        # control variables
        self.distance = 0.1  # default distance for 'move' cmd
        self.degree = 30  # default degree for 'cw' or 'ccw' cmd
        # if the pose recognition mode is opened
        self.pose_mode = False
        # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello
        self.quit_waiting_flag = False

        # if the flag is TRUE,the pose recognition skeleton will be drawn on the GUI picture
        self.draw_skeleton_flag = False
        # pose recognition
        self.my_tello_pose = Tello_Pose()

        # record the coordinates of the nodes in the pose recognition skeleton
        self.points = []
        #list of all the possible connections between skeleton nodes
        self.POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6],
                           [6, 7], [1, 14], [14, 8], [8, 9], [9, 10], [14, 11],
                           [11, 12], [12, 13]]

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None
        # self.panel_for_pose_handle_show = None

        # create buttons
        self.btn_snapshot = tki.Button(self.root,
                                       text="Snapshot!",
                                       command=self.takeSnapshot)
        self.btn_snapshot.pack(side="bottom",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

        self.btn_pose = tki.Button(self.root,
                                   text="Pose Recognition Status: Off",
                                   command=self.setPoseMode)
        self.btn_pose.pack(side="bottom",
                           fill="both",
                           expand="yes",
                           padx=10,
                           pady=5)

        self.btn_pause = tki.Button(self.root,
                                    text="Pause",
                                    relief="raised",
                                    command=self.pauseVideo)
        self.btn_pause.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_landing = tki.Button(self.root,
                                      text="Open Command Panel",
                                      relief="raised",
                                      command=self.openCmdWindow)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

        # set a callback to handle when the window is closed
        self.root.wm_title("TELLO Controller")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose)

        # the auto-takeoff thread will start if the 'takeoff' button on command window is clicked
        self.auto_takeoff_thread = threading.Thread(target=self._autoTakeoff)
        # the sending_command will send command to tello every 5 seconds
        self.sending_command_thread = threading.Thread(
            target=self._sendingCommand)
        self.get_GUI_Image_thread = threading.Thread(target=self._getGUIImage)

    def videoLoop(self):
        """
        The mainloop thread of Tkinter 
        Raises:
            RuntimeError: To get around a RunTime error that Tkinter throws due to threading.
        """
        try:
            # start the thread that get GUI image and drwa skeleton
            time.sleep(0.5)
            self.get_GUI_Image_thread.start()
            while not self.stopEvent.is_set():
                # read the frame for pose recognition
                self.frame = self.tello.read()
                if self.frame is None or self.frame.size == 0:
                    continue
                # smoothing filter
                self.frame = cv2.bilateralFilter(self.frame, 5, 50, 100)

                cmd = ''
                self.points.append(None)
                # process pose-recognition
                if self.pose_mode:
                    cmd, self.draw_skeleton_flag, self.points = self.my_tello_pose.detect(
                        self.frame)

                # process command - map your motion to whatever Tello movement you want!
                if cmd == 'moveback':
                    self.telloMoveBackward(0.50)
                elif cmd == 'moveforward':
                    self.telloMoveForward(0.50)
                elif cmd == 'land':
                    self.telloLanding()

        except RuntimeError as e:
            print("[INFO] caught a RuntimeError")

    def _getGUIImage(self):
        """
        Main operation to read frames from h264decoder and draw skeleton on 
        frames if the pose mode is opened
        """
        # read the system of your computer
        system = platform.system()
        while not self.stopEvent.is_set():
            # read the frame for GUI show
            frame = self.tello.read()
            if frame is None or frame.size == 0:
                continue
            if self.pose_mode:
                # Draw the detected skeleton points
                for i in range(15):
                    if self.draw_skeleton_flag == True:
                        cv2.circle(frame,
                                   self.points[i],
                                   8, (0, 255, 255),
                                   thickness=-1,
                                   lineType=cv2.FILLED)
                        cv2.putText(frame,
                                    "{}".format(i),
                                    self.points[i],
                                    cv2.FONT_HERSHEY_SIMPLEX,
                                    1, (0, 0, 255),
                                    2,
                                    lineType=cv2.LINE_AA)
                # Draw Skeleton
                for pair in self.POSE_PAIRS:
                    partA = pair[0]
                    partB = pair[1]
                    if self.points[partA] and self.points[partB]:
                        cv2.line(frame, self.points[partA], self.points[partB],
                                 (0, 255, 255), 2)
                        cv2.circle(frame,
                                   self.points[partA],
                                   8, (0, 0, 255),
                                   thickness=-1,
                                   lineType=cv2.FILLED)

            # transfer the format from frame to image
            image = Image.fromarray(frame)

            # we found compatibility problem between Tkinter,PIL and Macos,and it will
            # sometimes result the very long preriod of the "ImageTk.PhotoImage" function,
            # so for Macos,we start a new thread to execute the _updateGUIImage function.
            if system == "Windows" or system == "Linux":
                self._updateGUIImage(image)

            else:
                thread_tmp = threading.Thread(target=self._updateGUIImage,
                                              args=(image, ))
                thread_tmp.start()
                time.sleep(0.03)

    def _updateGUIImage(self, image):
        """
        Main operation to initial the object of image,and update the GUI panel 
        """
        image = ImageTk.PhotoImage(image)
        # if the panel none ,we need to initial it
        if self.panel is None:
            self.panel = tki.Label(image=image)
            self.panel.image = image
            self.panel.pack(side="left", padx=10, pady=10)
        # otherwise, simply update the panel
        else:
            self.panel.configure(image=image)
            self.panel.image = image

    def _autoTakeoff(self):
        """
        Firstly,it will waiting for the response that will be sent by Tello if Tello 
        
        finish the takeoff command.If computer doesn't receive the response,it may be
        
        because tello doesn't takeoff normally,or because the UDP pack of response is
        
        lost.So in order to confirm the reason,computer will send 'height?'command to
        
        get several real-time height datas and get a average value.If the height is in
        
        normal range,tello will execute the moveup command.Otherwise,tello will land.
        
        Finally,the sending-command thread will start.
        """
        response = None
        height_tmp = 0  # temp variable to content value of height
        height_val = 0  # average value of height
        cnt = 0  # effective number of height reading
        timeout = 6  # max waiting time of tello's response

        timer = threading.Timer(timeout, self._setQuitWaitingFlag)
        timer.start()

        # waiting for the response from tello
        while response != 'ok':
            if self.quit_waiting_flag is True:
                break
            response = self.tello.get_response()
            print("ack:%s" % response)
        timer.cancel()

        # receive the correct response
        if response == 'ok':
            self.tello.move_up(0.5)

        # calculate the height of tello
        else:
            for i in range(0, 50):
                height_tmp = self.tello.get_height()
                try:
                    height_val = height_val + height_tmp
                    cnt = cnt + 1
                    print(height_tmp, cnt)
                except:
                    height_val = height_val

            height_val = height_val / cnt

            # if the height value is in normal range
            if height_val == 9 or height_val == 10 or height_val == 11:
                self.tello.move_up(0.5)
            else:
                self.tello.land()
        # start the sendingCmd thread
        self.sending_command_thread.start()

    def _sendingCommand(self):
        """
        start a while loop that sends 'command' to tello every 5 second
        """

        while True:
            self.tello.send_command('command')
            time.sleep(5)

    def _setQuitWaitingFlag(self):
        """
        set the variable as TRUE,it will stop computer waiting for response from tello  
        """
        self.quit_waiting_flag = True

    def openCmdWindow(self):
        """
        open the cmd window and initial all the button and text
        """
        panel = Toplevel(self.root)
        panel.wm_title("Command Panel")

        # create text input entry
        text0 = tki.Label(
            panel,
            text=
            'This Controller map keyboard inputs to Tello control commands\n'
            'Adjust the trackbar to reset distance and degree parameter',
            font='Helvetica 10 bold')
        text0.pack(side='top')

        text1 = tki.Label(
            panel,
            text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n'
            'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n'
            'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n'
            'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right',
            justify="left")
        text1.pack(side="top")

        self.btn_landing = tki.Button(panel,
                                      text="Land",
                                      relief="raised",
                                      command=self.telloLanding)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.btn_takeoff = tki.Button(panel,
                                      text="Takeoff",
                                      relief="raised",
                                      command=self.telloTakeOff)
        self.btn_takeoff.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        # binding arrow keys to drone control
        self.tmp_f = tki.Frame(panel, width=100, height=2)
        self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w)
        self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s)
        self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a)
        self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d)
        self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)
        self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down)
        self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left)
        self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right)
        self.tmp_f.pack(side="bottom")
        self.tmp_f.focus_set()

        self.btn_landing = tki.Button(panel,
                                      text="Flip",
                                      relief="raised",
                                      command=self.openFlipWindow)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.distance_bar = Scale(panel,
                                  from_=0.02,
                                  to=5,
                                  tickinterval=0.01,
                                  digits=3,
                                  label='Distance(m)',
                                  resolution=0.01)
        self.distance_bar.set(0.2)
        self.distance_bar.pack(side="left")

        self.btn_distance = tki.Button(
            panel,
            text="Reset Distance",
            relief="raised",
            command=self.updateDistancebar,
        )
        self.btn_distance.pack(side="left",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

        self.degree_bar = Scale(panel,
                                from_=1,
                                to=360,
                                tickinterval=10,
                                label='Degree')
        self.degree_bar.set(30)
        self.degree_bar.pack(side="right")

        self.btn_distance = tki.Button(panel,
                                       text="Reset Degree",
                                       relief="raised",
                                       command=self.updateDegreebar)
        self.btn_distance.pack(side="right",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

    def openFlipWindow(self):
        """
        open the flip window and initial all the button and text
        """

        panel = Toplevel(self.root)
        panel.wm_title("Gesture Recognition")

        self.btn_flipl = tki.Button(panel,
                                    text="Flip Left",
                                    relief="raised",
                                    command=self.telloFlip_l)
        self.btn_flipl.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipr = tki.Button(panel,
                                    text="Flip Right",
                                    relief="raised",
                                    command=self.telloFlip_r)
        self.btn_flipr.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipf = tki.Button(panel,
                                    text="Flip Forward",
                                    relief="raised",
                                    command=self.telloFlip_f)
        self.btn_flipf.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

        self.btn_flipb = tki.Button(panel,
                                    text="Flip Backward",
                                    relief="raised",
                                    command=self.telloFlip_b)
        self.btn_flipb.pack(side="bottom",
                            fill="both",
                            expand="yes",
                            padx=10,
                            pady=5)

    def takeSnapshot(self):
        """
        save the current frame of the video as a jpg file and put it into outputpath
        """

        # grab the current timestamp and use it to construct the filename
        ts = datetime.datetime.now()
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))

        p = os.path.sep.join((self.outputPath, filename))

        # save the file
        cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR))
        print(("[INFO] saved {}".format(filename)))

    def setPoseMode(self):
        """
        Toggle the open/close of pose recognition mode
        """
        if self.pose_mode is False:
            self.pose_mode = True
            self.btn_pose.config(text='Pose Recognition Status: On')
        else:
            self.pose_mode = False
            self.btn_pose.config(text='Pose Recognition Status: Off')

    def pauseVideo(self):
        """
        Toggle the freeze/unfreze of video
        """
        if self.btn_pause.config('relief')[-1] == 'sunken':
            self.btn_pause.config(relief="raised")
            self.tello.video_freeze(False)
        else:
            self.btn_pause.config(relief="sunken")
            self.tello.video_freeze(True)

    def telloTakeOff(self):
        """
        send the takeoff command to tello,and wait for the first response,
        
        if get the 'error'response,remind the "battery low" warning.Otherwise,
        
        start the auto-takeoff thread
        """
        takeoff_response = None

        self.tello.takeoff()
        time.sleep(0.2)

        takeoff_response = self.tello.get_response()

        if takeoff_response != 'error':
            self.auto_takeoff_thread.start()
        else:
            print("battery low,please repalce with a new one")

    def telloLanding(self):
        return self.tello.land()

    def telloFlip_l(self):
        return self.tello.flip('l')

    def telloFlip_r(self):
        return self.tello.flip('r')

    def telloFlip_f(self):
        return self.tello.flip('f')

    def telloFlip_b(self):
        return self.tello.flip('b')

    def telloCW(self, degree):
        return self.tello.rotate_cw(degree)

    def telloCCW(self, degree):
        return self.tello.rotate_ccw(degree)

    def telloMoveForward(self, distance):
        return self.tello.move_forward(distance)

    def telloMoveBackward(self, distance):
        return self.tello.move_backward(distance)

    def telloMoveLeft(self, distance):
        return self.tello.move_left(distance)

    def telloMoveRight(self, distance):
        return self.tello.move_right(distance)

    def telloUp(self, dist):
        return self.tello.move_up(dist)

    def telloDown(self, dist):
        return self.tello.move_down(dist)

    def updateTrackBar(self):
        self.my_tello_hand.setThr(self.hand_thr_bar.get())

    def updateDistancebar(self):
        self.distance = self.distance_bar.get()
        print('reset distance to %.1f' % self.distance)

    def updateDegreebar(self):
        self.degree = self.degree_bar.get()
        print('reset distance to %d' % self.degree)

    def on_keypress_w(self, event):
        print("up %d m" % self.distance)
        self.telloUp(self.distance)

    def on_keypress_s(self, event):
        print("down %d m" % self.distance)
        self.telloDown(self.distance)

    def on_keypress_a(self, event):
        print("ccw %d degree" % self.degree)
        self.tello.rotate_ccw(self.degree)

    def on_keypress_d(self, event):
        print("cw %d m" % self.degree)
        self.tello.rotate_cw(self.degree)

    def on_keypress_up(self, event):
        print("forward %d m" % self.distance)
        self.telloMoveForward(self.distance)

    def on_keypress_down(self, event):
        print("backward %d m" % self.distance)
        self.telloMoveBackward(self.distance)

    def on_keypress_left(self, event):
        print("left %d m" % self.distance)
        self.telloMoveLeft(self.distance)

    def on_keypress_right(self, event):
        print("right %d m" % self.distance)
        self.telloMoveRight(self.distance)

    def on_keypress_enter(self, event):
        if self.frame is not None:
            self.registerFace()
        self.tmp_f.focus_set()

    def onClose(self):
        """
        set the stop event, cleanup the camera, and allow the rest of
        
        the quit process to continue
        """
        print("[INFO] closing...")
        self.stopEvent.set()
        del self.tello
        self.root.quit()
Exemple #33
0
class Report(Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.root = self.winfo_toplevel()
        self.root.title(" ".join((APPNAME, VERSION, "| Report")))
        self.root.resizable(0, 0)
        self.items = None
        headers = ('Page', 'Rank', 'PageRank Value', 'Incoming')
        self.t = Scale(self,
                       from_=0,
                       to=1,
                       label='n-th iteration',
                       bd=1,
                       width=7,
                       orient='horizontal',
                       command=self.__set_t)
        self.t.pack(fill='x')
        self.label = Label(self, anchor='e')
        self.label.pack(fill='x')
        self.tree = Treeview(self,
                             columns=headers,
                             show="headings",
                             height=REPORT_HEIGHT)
        self.tree.column(0, anchor='center', width=55)
        self.tree.column(1, anchor='center', width=55)
        self.tree.column(2, width=175)
        self.tree.column(3, anchor='center', width=55)
        self.scroll = Scrollbar(self, command=self.tree.yview)
        self.scroll.pack(side='right', fill='y')
        self.tree.config(yscrollcommand=self.scroll.set)
        for col in headers:
            self.tree.heading(col, text=col.title())
        self.root.master.focus_force()
        self.root.bind('<Key>', self.__keys)

    def __keys(self, event):
        if event.char == 'i':
            self.t.set(self.t.get() - 1)
        elif event.char == 'I':
            self.t.set(0)
        elif event.char == 'o':
            self.t.set(self.t.get() + 1)
        elif event.char == 'O':
            self.t.set(self.pagerank[1])

    def __set_t(self, t=None):
        self.render(self.pagerank, self.edge_counts, self.d, self.e, t=int(t))

    def render(self, pagerank, edge_counts, d, e, t=None):
        self.d, self.e = d, e
        self.edge_counts = edge_counts
        self.pagerank = pagerank
        if t is not None:
            pr = pagerank[0][t]
        else:
            self.t.config(command=None)
            self.t.config(to=self.pagerank[1])
            self.t.set(self.pagerank[1])
            self.t.config(command=self.__set_t)
            pr = pagerank[0][-1]
        label_text = '# of ranks:{0:>3}     # of iterations:{1:>3}'.format(
            len(set(pr.values())), self.pagerank[1])
        self.label.config(text=label_text)
        in_map = {k: 0 for k in pr.keys()}  # incoming edges by nodes
        for (tail, head), n in edge_counts.items():
            if tail is not head:
                in_map[head] += n

        get_rank = lambda k: sorted(pr.values())[::-1].index(pr[k]) + 1
        data = tuple(
            (k, get_rank(k), pr[k], in_map[k]) for k in sorted(pr.keys()))
        if self.items: self.tree.delete(*self.items)
        self.items = [
            self.tree.insert('', 'end', values=line) for line in data
        ]
        self.tree.pack(side='left', fill='y')
        #self.root.master.focus_force()

    def destroy(self):
        super().destroy()
        self.root.master.r_win = False
        self.root.master.windowsmenu.entryconfig(0, label='[ ] Report window')
        self.root.destroy()
Exemple #34
0
class StartPage(tk.Frame):
    def callbackserial(self):
        global com
        com = self.combo.get()
        com = com.replace('- FT231X USB UART', '')
        print(com)

    def callbacktime(self):
        global stime
        stime = int(self.slider.get())
        print(stime)

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="#1959B3")
        self.controller = controller

        canvas = Canvas(self, bg="#1959B3", height=583, width=673)
        canvas.pack()
        canvas.create_line(320, 157, 320, 500, dash=(6, 4),
                           fill="white")  #Linea punteada
        canvas.place(x=10, y=10)  #Linea externa

        label = tk.Label(self,
                         text="OpenBCI",
                         font=("Times", 70),
                         fg="white",
                         bg="#1959B3")
        label.pack(side="top", fill="x", pady=10)
        label.place(relx=0.32, rely=0.07)
        label2 = tk.Label(self,
                          text="Camila Andrea Navarrete Cataño",
                          fg="white",
                          bg="#1959B3",
                          font=("Verdana"))
        label2.pack(side="bottom", fill="x", pady=10)
        label2.place(relx=0.08, rely=0.96)
        label3 = tk.Label(self,
                          text="Seleccionar puerto USB:",
                          font=("Helvetica", 17),
                          fg="white",
                          bg="#1959B3")
        label3.pack(fill="x", pady=5)
        label3.place(relx=0.50, rely=0.31)
        label4 = tk.Label(self,
                          text="Bluetooth:",
                          font=("Helvetica", 17),
                          fg="white",
                          bg="#1959B3")
        label4.pack(fill="x", pady=5)
        label4.place(relx=0.50, rely=0.39)
        label6 = tk.Label(self,
                          text="Seleccionar tiempo de grabación:",
                          font=("Helvetica", 17),
                          fg="white",
                          bg="#1959B3")
        label6.pack(side="top", fill="x", pady=10)
        label6.place(relx=0.50, rely=0.58)
        label7 = tk.Label(
            self,
            text=
            "Este programa le ayudará a interactuar con las interfaces cerebro - computadora mediante el movimiento de una barra virtual y el robot mBot Ranger, en tiempo real."
            " En la siguiente página podra visualizar la señal de EEG del canal 8, el espectro de frecuencias y la barra  ",
            font=("Helvetica", 17),
            fg="white",
            bg="#1959B3",
            justify="left",
            wraplength=250)
        label7.pack(side="top", fill="x", pady=10)
        label7.place(relx=0.1, rely=0.35)

        button1 = tk.Button(self,
                            text="Iniciar",
                            command=lambda: controller.show_frame("PageOne"))
        button1.pack()
        button1.place(relx=0.64, rely=0.81, height=50, width=80)
        button3 = tk.Button(self, text="OK", command=self.callbackserial)
        button3.pack()
        button3.place(relx=0.87, rely=0.46, height=35, width=60)
        button2 = tk.Button(self, text="OK", command=self.callbacktime)
        button2.pack()
        button2.place(relx=0.87, rely=0.67, height=35, width=60)

        number = tk.StringVar()
        self.combo = ttk.Combobox(
            self, textvariable=number)  #Seleccionar puerto serial
        self.combo.place(x=355, y=285, width=240)
        self.combo["values"] = serial_ports()

        self.slider = Scale(self,
                            orient='horizontal',
                            from_=1,
                            to=10,
                            tickinterval=1)  #Barra de tiempos
        self.slider.pack()
        self.slider.place(relx=0.50, rely=0.65, width=240)
class AdjustFrame(Toplevel):
    def __init__(self, master=None):
        Toplevel.__init__(self, master=master)

        self.brightness_value = 0
        self.previous_brightness_value = 0

        self.original_image = self.master.processed_image
        self.processing_image = self.master.processed_image

        self.brightness_label = Label(self, text="Brightness")
        self.brightness_scale = Scale(self,
                                      from_=0,
                                      to_=2,
                                      length=250,
                                      resolution=0.1,
                                      orient=HORIZONTAL)

        self.r_label = Label(self, text="R")
        self.r_scale = Scale(self,
                             from_=-100,
                             to_=100,
                             length=250,
                             resolution=1,
                             orient=HORIZONTAL)

        self.g_label = Label(self, text="G")
        self.g_scale = Scale(self,
                             from_=-100,
                             to_=100,
                             length=250,
                             resolution=1,
                             orient=HORIZONTAL)

        self.b_label = Label(self, text="B")
        self.b_scale = Scale(self,
                             from_=-100,
                             to_=100,
                             length=250,
                             resolution=1,
                             orient=HORIZONTAL)

        self.apply_button = Button(self, text="Apply")
        self.preview_button = Button(self, text="Preview")
        self.cancel_button = Button(self, text="Cancel")

        self.brightness_scale.set(1)

        self.apply_button.bind("<ButtonRelease>", self.apply_button_released)
        self.preview_button.bind("<ButtonRelease>", self.show_button_released)
        self.cancel_button.bind("<ButtonRelease>", self.cancel_button_released)

        self.brightness_label.pack()
        self.brightness_scale.pack()
        self.r_label.pack()
        self.r_scale.pack()
        self.g_label.pack()
        self.g_scale.pack()
        self.b_label.pack()
        self.b_scale.pack()
        self.cancel_button.pack(side=RIGHT)
        self.preview_button.pack(side=RIGHT)
        self.apply_button.pack()

    def apply_button_released(self, event):
        self.master.processed_image = self.processing_image
        self.close()

    def show_button_released(self, event):
        self.processing_image = cv2.convertScaleAbs(
            self.original_image, alpha=self.brightness_scale.get())
        b, g, r = cv2.split(self.processing_image)

        for b_value in b:
            cv2.add(b_value, self.b_scale.get(), b_value)
        for g_value in g:
            cv2.add(g_value, self.g_scale.get(), g_value)
        for r_value in r:
            cv2.add(r_value, self.r_scale.get(), r_value)

        self.processing_image = cv2.merge((b, g, r))
        self.show_image(self.processing_image)

    def cancel_button_released(self, event):
        self.close()

    def show_image(self, img=None):
        self.master.image_viewer.show_image(img=img)

    def close(self):
        self.show_image()
        self.destroy()