Exemple #1
0
class TkLightSensor(TkDevice):
    def __init__(self, root, x, y, name, pin):
        super().__init__(root, x, y, name)

        self._pin = Device.pin_factory.pin(pin,
                                           pin_class=PreciseMockChargingPin)

        self._scale = Scale(root,
                            from_=0,
                            to=90,
                            showvalue=0,
                            orient=VERTICAL,
                            command=self._scale_changed,
                            sliderlength=20,
                            length=150,
                            highlightthickness=0,
                            background="white")
        self._scale.place(x=x + 90, y=y)
        self._scale.set(30)
        self._scale_changed(self._scale.get())

        self._set_image_for_state("light_sensor.png", "normal", (75, 150))
        self._create_main_widget(Label, "normal")

    def _scale_changed(self, value):
        self._pin.charge_time = float(value) / 10000
    def initUI(self):
        self.parent.title("Multimedia")
        self.pack(fill=BOTH, expand=1)

        menuBar = Menu(self.parent)
        self.parent.config(menu=menuBar)

        fileMenu = Menu(menuBar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        menuBar.add_cascade(label="File", menu=fileMenu)
        menuBar.add_command(label="About", command=self.onInfo)
        menuBar.add_command(label="Exit", command=self.quit)

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

        lbl1 = Label(self, text="Original Image", width=20)
        lbl1.place(x=20, y=50)
        lbl2 = Label(self, text="Output Image", width=20)
        lbl2.place(x=350, y=50)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.place(x=250, y=50)
        self.var = IntVar()

        start = Button(self, text="Start")
        start.place(x=250, y=170)
        self.a = 0
Exemple #3
0
class ZoomBar(Frame):
    master: Frame
    slider: Scale
    value: int

    def __init__(self, master):
        self.master = master
        self.slider = None
        self.value = 100

        super().__init__(self.master, width=800, height=30, bg="light blue")
        self.add_zoom_slider()
        self.value_label = Label(self, textvariable=self.value)
        self.value_label.place(x=450, y=5, width=50, height=20)

    def add_zoom_slider(self):
        self.slider = Scale(self,
                            variable=self.value,
                            from_=100,
                            to=1000,
                            orient=HORIZONTAL,
                            showvalue=0,
                            command=self._set_image_zoom)
        self.slider.place(x=500, y=5, width=300, height=20)

    def _set_image_zoom(self, event):
        self.master.canvas.set_image_zoom(int(event))
Exemple #4
0
class TkDistanceSensor(TkDevice):
    def __init__(self, root, x, y, name, trigger_pin, echo_pin, min_distance=0, max_distance=50):
        super().__init__(root, x, y, name)

        self._echo_pin = Device.pin_factory.pin(echo_pin)
        self._trigger_pin = Device.pin_factory.pin(trigger_pin,
                                                   pin_class=PreciseMockTriggerPin, echo_pin=self._echo_pin,
                                                   echo_time=0.004)

        self._echo_pin._bounce = 0
        self._trigger_pin._bounce = 0

        self._set_image_for_state("distance_sensor.png", "normal", (86, 50))
        self._create_main_widget(Label, "normal")

        self._scale = Scale(root, from_=min_distance, to=max_distance,
                            orient=HORIZONTAL, command=self._scale_changed, sliderlength=20, length=150,
                            highlightthickness=0, background="white")
        self._scale.place(x=x + 100, y=y)
        self._scale.set(round((min_distance + max_distance) / 2))
        self._scale_changed(self._scale.get())

    def _scale_changed(self, value):
        speed_of_sound = 343.26  # m/s
        distance = float(value) / 100  # cm -> m
        self._trigger_pin.echo_time = distance * 2 / speed_of_sound
class NewAdaptiveSliderWindow(NewSliderWindow):
    def set_basic(self):
        self.overrideredirect(1)
        self.set_geometry()
        self.set_scale()
        self.set_save_closeButtons()

    def fix(self, n):
        n = int(n)
        if not n % 2:
            self.scale.set(n + 1 if n > self.past else n - 1)
            self.past = self.scale.get()
        self.update_preview(int(self.var.get()))

    def set_scale(self):
        self.var = IntVar()
        self.scale = Scale(self,
                           length=300,
                           from_=3,
                           to=255,
                           orient=VERTICAL,
                           command=self.fix,
                           variable=self.var,
                           digits=1)
        self.update_preview(int(self.var.get()))
        self.scale.place(relx=0, rely=0.1, relwidth=0.9, relheight=0.7)
        self.scale.set(0)

    def update_preview(self, windowSize):
        self.master.image.threshold_adapt(windowSize)
        self.master.update_visible_image()

    def __init__(self, master=None):
        self.past = 3
        super().__init__(master)
 def init_slider(self):
     lost_packages_slider = Scale(self.settings_frame,
                                  from_=0,
                                  to=50,
                                  orient=HORIZONTAL,
                                  variable=self.widgets.lost_percentage)
     lost_packages_slider.place(x=225, y=347)
Exemple #7
0
def VentanaFourierLineal (ventana):
    """
    Ventana en la que el usuario define los parámetros para el cálculo.

    Parámetros de la función:
    ------------------------
    ventana: Variable que cierra una ventana ya abierta.
    
    Salida de la función:
    ---------------------
    Interfaz gráfica con la que el usuario elije un método de simulación.
    """

    ventana.destroy ()

    ventanaFourLineal = Tk ()
    ventanaFourLineal.minsize (1300,600)
    ventanaFourLineal.config (bg='White')

    barraLadoX = Scale(ventanaFourLineal, from_=7, to=20, tickinterval=13, length=400, bg = 'White',
    resolution=1, showvalue=True, orient='horizontal', label="Tamaño del Lado (Lx)", cursor = "hand1")
    barraLadoX.set(10)
    tamañoLadoX = barraLadoX.get()
    barraLadoX.place (relx=0.3, rely=0.35, anchor=CENTER)

    barraTérminosN = Scale(ventanaFourLineal, from_=2, to=20, tickinterval=18,length=400, bg = 'White',
    resolution=1, showvalue=True, orient='horizontal', label="Número de Términos N", cursor = "hand1")
    barraTérminosN.set(10)
    númeroTérminosN = barraTérminosN.get()
    barraTérminosN.place (relx=0.7, rely=0.35, anchor=CENTER)

    barraLadoY = Scale(ventanaFourLineal, from_=7, to=20, tickinterval=13, length=400, bg = 'White',
    resolution=1, showvalue=True, orient='horizontal', label="Tamaño del Lado (Ly)", cursor = "hand1")
    barraLadoY.set(10)
    tamañoLadoY = barraLadoY.get()
    barraLadoY.place (relx=0.3, rely=0.55, anchor=CENTER)

    barraTérminosM = Scale(ventanaFourLineal, from_=2, to=20, tickinterval=18,length=400, bg = 'White',
    resolution=1, showvalue=True, orient='horizontal', label="Número de Términos M", cursor = "hand1")
    barraTérminosM.set(10)
    númeroTérminosM = barraTérminosM.get()
    barraTérminosM.place (relx=0.7, rely=0.55, anchor=CENTER)

    etiquetaParámetros = Label (ventanaFourLineal, text = ('Defina los parámetros iniciales: '))
    etiquetaParámetros.config (bg = 'white', font = ('Verdana', 12))
    etiquetaParámetros.place (relx=0.1225, rely=0.2, anchor=CENTER)

    boton3D = Button(ventanaFourLineal, text='Abrir Gráfica 3D', 
    command = lambda: AbrirGrafica3D (tamañoLadoX, 0, númeroTérminosN, tamañoLadoY, 0, númeroTérminosM, 0))
    boton3D.place (relx=0.42, rely=0.7, anchor=CENTER)

    botonLatInt = Button(ventanaFourLineal, text='Abrir Grafica de Intensidad',
    command = lambda: AbrirGraficaLateralIntensidad (tamañoLadoX, 0, númeroTérminosN, tamañoLadoY, 0, númeroTérminosM, 0))
    botonLatInt.place (relx=0.6, rely=0.7, anchor=CENTER)

    botonRegresarPrincipal = Button(ventanaFourLineal, text='Regresar', command = lambda: VentanaFourierPrincipal (ventanaFourLineal))
    botonRegresarPrincipal.place (relx=0.835, rely=0.85, anchor=CENTER) 

    ventanaFourLineal.title ("Cálculo de la ecuación de difusión de calor")
    ventanaFourLineal.mainloop()
Exemple #8
0
def Ventana1Temp (ventana):
    """
        Ventana en la que el usuario elige la orientación de los spines y la temperatura específica con la que realizar la simulación.

        Parámetros de la función:
        ------------------------
        ventana: Variable que cierra una ventana ya abierta.
        
        Salida de la función
        ---------------------
        Interfaz gráfica con la que el usuario define los parámetros de la simulación.
        """
        
    # Función para cerrar una ventana definida.
    ventana.destroy ()

    # Parametros iniciales para la ventana gráfica.
    ventana1 = Tk ()
    ventana1.minsize (800, 750)
    ventana1.config (bg='White')

    # Etiquetas que indican al usuario lo que debe seleccionar.
    etiqueta1 = Label (ventana1, text = ('Seleccione la temperatura '
    "\n" 
        r"a analizar" ))
    etiqueta1.config (bg = 'white', font = ('Verdana', 15))
    etiqueta1.place (relx=0.5, rely=0.2, anchor=CENTER)

    etiqueta2 = Label (ventana1, text = ('Seleccione la orientación '
    "\n" 
        r"inicial de los Spines" ))
    etiqueta2.config (bg = 'white', font = ('Verdana', 15))
    etiqueta2.place (relx=0.5, rely=0.45, anchor=CENTER)

    # Se define el slider para la temperatura con la que realizar los cálculos.
    barraTemp = Scale(ventana1, from_=0.1, to=5, tickinterval=4.9, length=400, bg = 'White',
    resolution=0.1, showvalue=True, orient='horizontal', label="Temperatura", cursor = "hand1")
    barraTemp.set(1)
    barraTemp.place (relx=0.5, rely=0.325, anchor=CENTER)

    # Obtiene los valores dados por el slider en la ventana.
    temperatura = barraTemp.get()

    # Se definen los diferentes botones.
    botonArriba = Button(ventana1, text='Hacia arriba', command = lambda: EjecutarUnaTemperatura(1, temperatura), cursor = 'hand1')
    botonArriba.place (relx=0.25, rely=0.575, anchor=CENTER)

    botonAbajo = Button(ventana1, text='Hacia abajo', command = lambda: EjecutarUnaTemperatura(-1, temperatura), cursor = 'hand1')
    botonAbajo.place (relx=0.5, rely=0.575, anchor=CENTER)

    botonAleatorio = Button(ventana1, text='Spines aleatorios', command = lambda: EjecutarUnaTemperatura(0, temperatura), cursor = 'hand1')
    botonAleatorio.place (relx=0.75, rely=0.575, anchor=CENTER)

    botonRegresar = Button(ventana1, text='Regresar', command = lambda: VentanaPrincipal(ventana1), cursor = 'hand1')
    botonRegresar.place (relx=0.775, rely=0.85, anchor=CENTER)

    # Se configura el título de la ventana y se ejecuta.
    ventana1.title ("Cálculo de R para un Sistema Estocástico con base a una sola temperatura")
    ventana1.mainloop()
Exemple #9
0
class DPIChanger():
    def __init__(self, winTitle, xSize, ySize, *args):
        self.window = tk.Tk()
        if args:
            self.window.configure(bg=args)
        self.window.geometry(f'{xSize}x{ySize}')
        self.window.title(winTitle)
        self.window.iconbitmap("ImageDPI.ico")
        self.window.resizable(False, False)
        self.chooseImageButton = Button(text="Choose Image",
                                        bd=3,
                                        command=self.chooseImageFunc)
        self.chooseImageButton.place(x=23, y=20)
        self.chooseSaveTo = Button(text="Choose folder to save to",
                                   bd=3,
                                   command=self.chooseSaveFunc)
        self.chooseSaveTo.place(x=150, y=20)
        self.dpiScale = Scale(from_=5000, to=0)
        self.dpiScale.place(x=0, y=70)
        self.dpiScaleTwo = Scale(from_=5000, to=0)
        self.dpiScaleTwo.place(x=40, y=70)
        self.newImageName = Label(text="Enter new image name",
                                  font=("Courier", 12))
        self.newImageName.place(x=110, y=70)
        self.newImageEntry = Entry(bd=3)
        self.newImageEntry.place(x=110, y=100)
        self.changeDPIBtn = Button(text="Submit", bd=3, command=self.changeDPI)
        self.changeDPIBtn.place(x=110, y=145)
        self.window.mainloop()

    def chooseImageFunc(self):
        self.getImage = filedialog.askopenfilename()
        messagebox.showinfo("Image ", self.getImage)
        self.getImageExtension = self.getImage.rsplit(".", 1)
        self.imageExtension = self.getImageExtension[1]

    def chooseSaveFunc(self):
        self.savedFolder = filedialog.askdirectory()
        messagebox.showinfo("Folder", self.savedFolder)

    def changeDPI(self):
        try:
            self.scaleNum = self.dpiScale.get()
            self.scaleNumTwo = self.dpiScaleTwo.get()
            self.theNewImage = PILImage.open(self.getImage)
            self.theNewImage.save(self.savedFolder + "/" +
                                  self.newImageEntry.get() + "." +
                                  self.imageExtension,
                                  dpi=(self.scaleNum, self.scaleNumTwo))
            messagebox.showinfo(
                "Saved", self.savedFolder + "/" + self.newImageEntry.get() +
                "." + self.imageExtension)
        except:
            messagebox.showwarning("Error", "Something went wrong")
Exemple #10
0
def settings():
    data.timergo = False
    dat = open('config.cnf', 'r').read().split()
    words = dat[0]
    recordes = dat[1:]
    t = StringVar()

    def prnt(event):
        t.set('Слова: ' + str(event))

    def save():
        temp = ''
        for i in recordes:
            temp += ' ' + i
        open('config.cnf', 'w').write(str(w.get()) + temp)
        wind.destroy()
        start()

    def reset():
        open('config.cnf', 'w').write(str(words) + ' 0 0 0 0 0 0 0 0 0 0')
        recordes.clear()
        recordes.extend(' 0 0 0 0 0 0 0 0 0 0'.split())

    def close():
        wind.destroy()
        data.timergo = True

    wind = Toplevel(root, relief=SUNKEN)
    wind.minsize(width=350, height=350)
    Label(wind, textvariable=t, font='Arial 18').place(x=125, y=20)
    w = Scale(wind,
              from_=1,
              to=20,
              orient=HORIZONTAL,
              width=20,
              length=200,
              showvalue=False,
              command=prnt)
    w.set(int(words))
    w.place(x=75, y=75)
    Button(wind, text='Сохранить', command=save, font='Arial 14',
           width=8).place(x=60, y=250)
    Button(wind, text='Закрыть', command=close, font='Arial 14',
           width=6).place(x=220, y=250)
    Label(wind, text='Сбросить рекорды:', font='Arial 18').place(x=80, y=120)
    Button(wind, text='СБРОС', font='Arial 14', command=reset).place(x=140,
                                                                     y=160)
Exemple #11
0
    def initUI(self):
        self.parent.title("Phương pháp nén ảnh JPEG")
        self.pack(fill=BOTH, expand=1)

        menuBar = Menu(self.parent)
        self.parent.config(menu=menuBar)

        fileMenu = Menu(menuBar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        menuBar.add_cascade(label="File", menu=fileMenu)
        menuBar.add_command(label="About", command=self.onInfo)
        menuBar.add_command(label="Exit", command=self.quit)

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

        lbl0 = Label(
            self,
            text=
            "Xin gửi lời cảm ơn đến thầy Nguyễn Linh Giang đã giúp đỡ chúng em hoàn thành đề tài này, mở ảnh chọn File/Open"
        )
        lbl0.place(x=20, y=10)
        lbl1 = Label(self, text="Original Image", width=20)
        lbl1.place(x=20, y=50)
        lbl2 = Label(self, text="Output Image", width=20)
        lbl2.place(x=400, y=50)
        lbl3 = Label(self, text="Size:", width=10)
        lbl3.place(x=20, y=300)
        lbl4 = Label(self, text="Size:", width=10)
        lbl4.place(x=400, y=300)
        lbl5 = Label(self, text="Tỷ lệ nén", width=10)
        lbl5.place(x=250, y=50)
        scale = Scale(self, from_=1, to=90, command=self.onScale)
        scale.place(x=270, y=80)
        self.var = IntVar()

        start = Button(self, text="Start", command=self.onRelease)
        start.place(x=270, y=200)
        self.a = 0
        self.b = 0
Exemple #12
0
    etiqueta = Label (ventana, text = ('Iteraciones necesarias: ' + str (iteracionesTotales)))
    etiqueta.config (bg = 'white', font = ('Verdana', 15))
    etiqueta.place (relx=0.5, rely=0.37, anchor=CENTER)

    #Función que permite graficar a tiempo real. Esta ejecuta nuevamente la función Graficar para realizar nuevamente el cálculo.
    animation.FuncAnimation (fig, Graficar, interval = 1000)
    plt.close ()
 

# Se define el slider para el tamaño del lado.
barraL = Scale(ventana, from_=7, to=20, tickinterval=13, length=400, bg = 'White',
resolution=1, showvalue=True, orient='horizontal', label="Tamaño del Lado (Lx)", cursor = "hand1")
barraL.bind ("<ButtonRelease-1>",Graficar)
barraL.set(10)

barraL.place (relx=0.175, rely=0.05, anchor=CENTER)

# Se define el slider para el tiempo a evaluar.
barraTiempos = Scale(ventana, from_=1, to=5, tickinterval=4,length=400, bg = 'White',
resolution=0.5, showvalue=True, orient='horizontal', label="Tiempo (s)", cursor = "hand1")
barraTiempos.bind ("<ButtonRelease-1>",Graficar)
barraTiempos.set(3)

barraTiempos.place (relx=0.5, rely=0.05, anchor=CENTER)

# Se define el slider para el número de términos.
barraPresición = Scale(ventana, from_=0.001, to=1, tickinterval=0.999,length=400, bg = 'White',
resolution=0.001, showvalue=True, orient='horizontal', label="Presición", cursor = "hand1")
barraPresición.bind ("<ButtonRelease-1>",Graficar)
barraPresición.set(0.05
)
Exemple #13
0
    main.execute_command(terminal_entry.get())
    terminal_entry.delete(0, 'end')
terminal_entry.bind('<Return>', commandEntered)

# Fan Widgets
f1_slider = Scale(root, command=main.set_fan1, from_=100, to=0, label='Fan 1', length=570, width=30, font=('Roboto Slab', 10))
f2_slider = Scale(root, command=main.set_fan2, from_=100, to=0, label='Fan 2', length=570, width=30, font=('Roboto Slab', 10))

# Motor Widget
motor_label = Label(root, text='Motor Position: \t0', font=('Roboto Slab', 30))

# --------- Drawing to the Screen ---------
canvasWidget.place(x=800, y=0)
title_label.place(x=10, y=10)
motor_label.place(x=10, y=100)
f1_slider.place(x=550, y=15)
f2_slider.place(x=650, y=15)
diameter_label.place(x=800, y=480)
graph_pause_button.place(x=800, y=540)
reset_button.place(x=1000, y=540)
save_button.place(x=1200, y=540)
terminal_label.place(x=10, y=500)
terminal_entry.place(x=10, y=550)

ax1 = fig.add_subplot(1,1,1)
line, = ax1.plot(xAxis, data)

def animate(i):
    if update_graph:
        main.loop()
        ax1.clear()
Exemple #14
0
    def __init__(self):
        # The main window
        self.root = Tk(className=" Virtual led matrix")
        self.root.geometry("%sx%s"
                           % (WINDOW_WIDTH, WINDOW_HEIGHT))
        self.root.configure(background=BG_COLOR)

        # The canvas we draw LEDs on
        self.canvas = Canvas(self.root, background=BG2_COLOR,
                             highlightthicknes=0,
                             width=CANVAS_WIDTH,
                             height=CANVAS_HEIGHT)
        self.canvas.place(x=GENERAL_SPACING, y=GENERAL_SPACING)

        # The widgets posing as leds
        self.grid_leds = [[self.canvas.create_oval(
            i * LED_SIZE + 2, j * LED_SIZE + 2, (i + 1) * LED_SIZE - 2,
            (j + 1) * LED_SIZE - 2,
            fill="#000000") for j in range(MATRIX_HEIGHT)]
            for i in range(MATRIX_WIDTH)]

        # Let's create a canvas for the buttons
        self.button_canvas = Canvas(self.root, background=BG2_COLOR,
                                    highlightthicknes=0)
        self.button_canvas.place(x=CANVAS_WIDTH + GENERAL_SPACING * 2,
                                 y=GENERAL_SPACING,
                                 width=BUTTON_CANVAS_WIDTH,
                                 height=BUTTON_CANVAS_HEIGHT)

        # Now let's place the buttons and put them in the list
        self.buttons = []
        self.buttons_down = []
        for i in range(NUM_BUTTONS):
            x = (i + 1) * BUTTON_SPACING + i * BUTTON_WIDTH
            y = BUTTON_SPACING
            button = self.button_canvas.create_rectangle(
                x,
                y,
                (i + 1) * BUTTON_SPACING + (i + 1) * BUTTON_WIDTH,
                BUTTON_SPACING + BUTTON_HEIGHT,
                fill=BUTTON_UP_COLOR,
            )
            self.buttons.append(button)
            self.buttons_down.append(False)

        for i in range(NUM_BUTTONS):
            x = (i + 1) * BUTTON_SPACING + (i + 0.5) * BUTTON_WIDTH
            y = BUTTON_SPACING + BUTTON_HEIGHT*0.5
            self.button_canvas.create_text(x, y, text="BTN%i" % i)

        # When buttons are pressed/released, execute functions to handle it
        self.button_canvas.bind('<Button-1>', self.button_clicked)
        self.button_canvas.bind('<ButtonRelease-1>', self.button_released)

        # Let's create a canvas for the switches
        self.switch_canvas = Canvas(self.root, background=BG2_COLOR,
                                    highlightthicknes=0)
        self.switch_canvas.place(x=CANVAS_WIDTH + GENERAL_SPACING * 2,
                                 y=BUTTON_CANVAS_HEIGHT + GENERAL_SPACING * 2,
                                 width=SWITCH_CANVAS_WIDTH,
                                 height=SWITCH_CANVAS_HEIGHT)

        # Now let's place the switches and put them in the list
        self.switches = []
        self.switches_activated = []
        for i in range(NUM_SWITCHES):
            self.switches_activated.append(IntVar())

            switch = Checkbutton(self.switch_canvas,
                                 text="SW%i" % i,
                                 var=self.switches_activated[i])
            switch.place(x=(i + 1) * SWITCH_SPACING + i * SWITCH_WIDTH,
                         y=SWITCH_SPACING,
                         width=SWITCH_WIDTH,
                         height=SWITCH_HEIGHT)

            self.switches.append(switch)

        self.slider_canvas = Canvas(self.root, background=BG2_COLOR,
                                    highlightthicknes=0)
        self.slider_canvas.place(x=GENERAL_SPACING,
                                 y=CANVAS_HEIGHT + GENERAL_SPACING * 2,
                                 width=SLIDER_CANVAS_WIDTH,
                                 height=SLIDER_CANVAS_HEIGHT)

        self.sliders = []
        for i in range(NUM_SLIDERS):
            slider = Scale(self.slider_canvas,
                           from_=SLIDER_MIN,
                           to=SLIDER_MAX,
                           orient="horizontal",
                           label="Sensor %i:" % i)
            slider.place(x=SLIDER_SPACING,
                         y=i*SLIDER_HEIGHT + (i+1)*SLIDER_SPACING,
                         width=SLIDER_WIDTH,
                         height=SLIDER_HEIGHT)

            self.sliders.append(slider)

            self.closed = False
            self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
Exemple #15
0
                  fg=theme[1])
ans_label.place(x=50, y=600)

Dx = Scale(root,
           bg=theme[0],
           fg=theme[1],
           from_=0.001,
           to=0.00001,
           resolution=0.00001,
           orient='horizontal',
           length=250,
           relief='groove',
           label='<== SPEED              ::           ACCURACY ==>',
           activebackground=theme[0])
Dx.set(0.0005)
Dx.place(x=50, y=450)

Button(root,
       bg=theme[0],
       fg=theme[1],
       text='Reset',
       command=reset,
       width=8,
       relief='groove',
       activebackground=theme[0]).place(x=380, y=480)

Button(root,
       bg=theme[0],
       fg=theme[1],
       text='Integrate',
       command=integrate,
Exemple #16
0
class Configure:

    def __init__(self):
        # Initialize window
        self._window = Tk()

        self._players = [PlayerSelector(0, "Player 1", '#f6b93b', self._window),
                         PlayerSelector(1, "Player 2", '#e74c3c', self._window)]

        # Setting up window
        self._window.title("Connect4 Deluxe")
        self._window.resizable(width=False, height=False)
        self._window.geometry("300x350+{}+{}".format(int((self._window.winfo_screenwidth() / 2) - (300 / 2)),
                                                     int((self._window.winfo_screenheight() / 2) - (350 / 2))))
        self._window.iconphoto(False, PhotoImage(file="assets/logo.png"))

        # Initialize canvas
        self._canvas = Canvas(self._window, width=300, height=450, background='#ecf0f1')

        # Set title
        Label(self._window, text="Connect4", foreground='#2c3e50', font=("The Bold Font", 15)).place(x=162, y=30,
                                                                                                     anchor="e")
        Label(self._window, text="Deluxe", foreground='#6c5ce7', font=("The Bold Font", 15)).place(x=162, y=30,
                                                                                                   anchor="w")

        # Create configurable parameters
        self._connect = Scale(self._window, from_=4, to=10, label="Connect", font=("The Bold Font", 7), length=200,
                              orient=HORIZONTAL)
        self._width = Scale(self._window, from_=7, to=15, label="Width", font=("The Bold Font", 7), length=200,
                            orient=HORIZONTAL)
        self._height = Scale(self._window, from_=6, to=15, label="Height", font=("The Bold Font", 7), length=200,
                             orient=HORIZONTAL)
        self._connect.place(x=150, y=80, anchor="center")
        self._width.place(x=150, y=140, anchor="center")
        self._height.place(x=150, y=200, anchor="center")

        # Create player's configuration
        for player in self._players:
            self.create_button(player)

        # Create play button
        Button(self._window, text="Play", foreground='#2c3e50', font=("The Bold Font", 10), command=self.launch).place(
            x=120, y=315, width=60, height=25)

        self._window.mainloop()

    def create_button(self, player):
        # Creation of input field for player name
        Entry(self._window, textvariable=player.entry, font=("The Bold Font", 10), width=10).place(x=50,
                                                                                                   y=250 + player.id * (
                                                                                                               20 + 10))
        # Create color picker
        player.button = Button(self._window, width=5, background=player.color, borderwidth=0,
                               command=lambda: self.on_change_color(player))
        player.button.place(x=180, y=250 + (player.id * (20 + 10)))

    def on_change_color(self, player):
        # Ask for color
        _, color = askcolor(parent=self._window, initialcolor=player.color)
        player.button.configure(background=color)
        player.color = color

    def launch(self):
        # Launch Game and destroy configuration window
        connect = self._connect.get()
        width = self._width.get()
        height = self._height.get()

        self._window.destroy()

        players = []
        for player in self._players:
            players.append(Player(player.id, player.entry.get(), player.color))

        Display(Game(players, width, height, connect))
Exemple #17
0
bouton.grid(row=3, column=0)

#-------------Slider first finger-------------
slider_group_x_offset = 4
slider_group_y_offset = 150

l_Finger1 = Label(root, text="Finger 1")
l_Finger1.place(x=slider_group_x_offset, y=slider_group_y_offset + 20)

sliderFinger1 = Scale(root,
                      from_=0,
                      to=180,
                      orient=constants.HORIZONTAL,
                      length=150,
                      command=finger1_event)
sliderFinger1.place(x=slider_group_x_offset + 66, y=slider_group_y_offset)

#-------------Slider second finger-------------

l_Finger2 = Label(root, text="Finger 2")
l_Finger2.place(x=slider_group_x_offset, y=slider_group_y_offset + 20 + 40)

sliderFinger2 = Scale(root,
                      from_=0,
                      to=180,
                      orient=constants.HORIZONTAL,
                      length=150,
                      command=finger2_event)
sliderFinger2.place(x=slider_group_x_offset + 66, y=slider_group_y_offset + 40)

#-------------Slider third finger-------------
progressbar = Progressbar(root, length=545)
progressbar.start(10)
progressbar.place(x=1, y=465)
volume_indict_ = Label(root, text='Volume:', font=('Arial', 15, 'bold'))
volume_indict_.place(y=500)
volume = Scale(root,
               from_=0,
               to=100,
               orient=HORIZONTAL,
               tickinterval=20,
               length=150,
               background='#3C3C3C',
               fg='white',
               activebackground='#3C3C3C',
               command=set_volume1)
volume.place(y=530, x=1)
volume.set(50)
lyrics_indict = Label(root, text='Lyrics', font=('Arial', 20, 'bold'))
lyrics_indict.place(x=200, y=150)
lyrics = Listbox(root,
                 bg='#3C3C3C',
                 width=55,
                 fg='orange',
                 font=('Arial', 12, 'bold'))
lyrics.place(x=1, y=200)
lyrics.insert(0, "blackpink!".upper())
play_list = Listbox(root,
                    width=32,
                    bg="#3C3C3C",
                    fg='cyan',
                    font=('Arial', 12, 'bold'),
Exemple #19
0
class NicerGui:
    def __init__(self, master, screen_size):
        if screen_size[0] > 1920:
            screen_size = list(screen_size)  # when multiscreen, use only 1 screen
            screen_size[0] = 1920
            screen_size[1] = 1080
        self.master = master
        self.height = int(0.85 * screen_size[1])
        self.width = int(0.85 * screen_size[0])
        master.title("NICER - Neural Image Correction and Enhancement Routine")
        master.geometry(str(self.width) + 'x' + str(self.height))  # let gui be x% of screen, centered
        sliderlength = 200

        self.nicer = NICER(checkpoint_can=config.can_checkpoint_path, checkpoint_nima=config.nima_checkpoint_path,
                           can_arch=config.can_filter_count)

        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.can = CAN(no_of_filters=8) if config.can_filter_count == 8 else CAN(no_of_filters=7)
        self.can.load_state_dict(torch.load(config.can_checkpoint_path, map_location=self.device)['state_dict'])
        self.can.eval()
        self.can.to(self.device)

        # keep references to the images for further processing, bc tk.PhotoImage cannot be converted back
        self.reference_img1 = None
        self.reference_img2 = None
        self.reference_img1_fullSize = None
        self.img_namestring = None
        self.img_extension = None
        self.helper_x = None
        self.helper_y = None
        self.epochCount = None  # for display only
        self.threadKiller = threading.Event()

        # labels:
        if True:
            self.fixlabel = Label(master, text="fix?")
            self.saturation_label = Label(master, text="Saturation")
            self.contrast_label = Label(master, text="Contrast")
            self.brightness_label = Label(master, text="Brightness")
            self.shadows_label = Label(master, text="Shadows")
            self.highlights_label = Label(master, text="Highlights")
            self.exposure_label = Label(master, text="Exposure")
            self.locallaplacian_label = Label(master, text="Local Laplacian Filtering")
            self.nonlocaldehazing_label = Label(master, text="Non-Local Dehazing")
            self.gamma_label = Label(master, text="Gamma")
            self.epoch_label = Label(master, text="Epochs:")
            self.print_label = Label(master, text="Open an image to get started!")
            self.print_label.place(x=int(0.635 * self.width), y=int(0.96 * self.height))
            self.slider_labels = [self.saturation_label, self.contrast_label, self.brightness_label, self.shadows_label,
                                  self.highlights_label, self.exposure_label, self.locallaplacian_label,
                                  self.nonlocaldehazing_label]

        # sliders:
        if True:
            self.saturation = DoubleVar()
            self.saturation_isfixed = IntVar()
            self.saturation_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                           var=self.saturation)
            self.saturation_checkbox = Checkbutton(master, var=self.saturation_isfixed)

            self.contrast = DoubleVar()
            self.contrast_isfixed = IntVar()
            self.contrast_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                         var=self.contrast)
            self.contrast_checkbox = Checkbutton(master, var=self.contrast_isfixed)

            self.brightness = DoubleVar()
            self.brightess_isfixed = IntVar()
            self.brightness_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                           var=self.brightness)
            self.brigtness_checkbox = Checkbutton(master, var=self.brightess_isfixed)

            self.shadows = DoubleVar()
            self.shadows_isfixed = IntVar()
            self.shadows_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                        var=self.shadows)
            self.shadows_checkbox = Checkbutton(master, var=self.shadows_isfixed)

            self.highlights = DoubleVar()
            self.highlighs_isfixed = IntVar()
            self.highlights_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                           var=self.highlights)
            self.highlights_checkbox = Checkbutton(master, var=self.highlighs_isfixed)

            self.exposure = DoubleVar()
            self.exposure_isfixed = IntVar()
            self.exposure_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                         var=self.exposure)
            self.exposure_checkbox = Checkbutton(master, var=self.exposure_isfixed)

            self.locallaplacian = DoubleVar()
            self.locallaplacian_isfixed = IntVar()
            self.locallaplacian_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                               var=self.locallaplacian)
            self.locallaplacian_checkbox = Checkbutton(master, var=self.locallaplacian_isfixed)

            self.nonlocaldehazing = DoubleVar()
            self.nonlocaldehazing_isfixed = IntVar()
            self.nonlocaldehazing_slider = Scale(master, from_=-100, to=100, length=sliderlength, orient=HORIZONTAL,
                                                 var=self.nonlocaldehazing)
            self.nonlocaldehazing_checkbox = Checkbutton(master, var=self.nonlocaldehazing_isfixed)

            self.gamma = DoubleVar()
            self.gamma_slider = Scale(master, from_=0.005, to=0.5, length=sliderlength, orient=HORIZONTAL,
                                      var=self.gamma, resolution=0.005)
            self.gamma_slider.set(0.1)

            self.slider_variables = [self.saturation, self.contrast, self.brightness, self.shadows,
                                     self.highlights, self.exposure, self.locallaplacian, self.nonlocaldehazing]
            self.checkbox_variables = [self.saturation_isfixed, self.contrast_isfixed, self.brightess_isfixed,
                                       self.shadows_isfixed, self.highlighs_isfixed, self.exposure_isfixed,
                                       self.locallaplacian_isfixed, self.nonlocaldehazing_isfixed]
            self.checkboxes = [self.saturation_checkbox, self.contrast_checkbox, self.brigtness_checkbox,
                               self.shadows_checkbox, self.highlights_checkbox, self.exposure_checkbox,
                               self.locallaplacian_checkbox, self.nonlocaldehazing_checkbox]
            self.sliders = [self.saturation_slider, self.contrast_slider, self.brightness_slider, self.shadows_slider,
                            self.highlights_slider, self.exposure_slider, self.locallaplacian_slider,
                            self.nonlocaldehazing_slider]

        # create images and line, and place them
        if True:
            w = Canvas(master, width=20, height=self.height)
            w.place(x=int(0.365 * self.width), y=10)
            w.create_line(10, 20, 10, int(0.9 * self.height), fill="#476042", dash=(4, 4))

            pil_img_one = Image.new('RGB', (224, 224), (255, 255, 255))
            pil_img_two = Image.new('RGB', (224, 224), (150, 150, 150))
            tk_img_one = ImageTk.PhotoImage(pil_img_one)
            tk_img_two = ImageTk.PhotoImage(pil_img_two)
            self.tk_img_panel_one = Label(master, image=tk_img_one)
            self.tk_img_panel_two = Label(master, image=tk_img_two)
            self.tk_img_panel_one.image = tk_img_one
            self.tk_img_panel_two.image = tk_img_two
            # image pack happens later when open Image button is clicked

        # place sliders and their labels:
        if True:
            # get 65% of screen height:
            three_quarters = int(0.65 * self.height)
            space = (three_quarters - 30) / 7

            for idx, label in enumerate(self.slider_labels):
                label.place(x=20, y=30 + idx * space)
            for idx, slider in enumerate(self.sliders):
                slider.place(x=150, y=10 + idx * space)
            for idx, chckbx in enumerate(self.checkboxes):
                chckbx.place(x=150 + sliderlength + 10, y=30 + idx * space)

            self.fixlabel.place(x=360, y=10)
            gamma_space = 2 * space if space < 60 else 120
            self.gamma_label.place(x=20, y=50 + 6 * space + gamma_space)
            self.gamma_slider.place(x=150, y=30 + 6 * space + gamma_space)

        # create buttons and place
        if True:
            self.open_button = Button(master, text="Open Image", command=self.open_image)
            self.save_button = Button(master, text="Save Image", command=self.save_image)
            self.reset_button = Button(master, text="Reset", command=self.reset_all)
            self.preview_button = Button(master, text="Preview", command=self.preview)
            self.nicer_button = Button(master, text="NICER!", command=self.nicer_routine)
            self.stop_button = Button(master, text="Stop!", command=self.stop)
            self.about_button = Button(master, text="About", command=self.about)

            button_y = 50 + 6 * space + gamma_space + 50
            self.open_button.place(x=40, y=button_y + 20)
            self.save_button.place(x=40, y=button_y + 60)
            self.nicer_button.place(x=40 + 105, y=button_y + 20)
            self.stop_button.place(x=40 + 105, y=button_y + 60)
            self.preview_button.place(x=40 + 200, y=button_y + 20)
            self.reset_button.place(x=40 + 200, y=button_y + 60)
            self.about_button.place(x=40 + 105, y=button_y + 100)

            self.epoch_label.place(x=40 + 105, y=button_y - 5)
            self.epochVar = IntVar()
            self.epochBox = tk.Entry(master, width=3)
            self.epochBox.insert(-1, '50')
            self.epochBox.place(x=40 + 160, y=button_y - 5)

    def about(self):
        url = 'https://github.com/mr-Mojo/NICER'
        webbrowser.open(url, new=1)

    def stop(self):
        global running
        running = False

    def open_image(self, img_path=None):
        """
        opens an image, if the image extension is supported in config.py. Currently supported extensions are jpg, png and dng, although
        more might work. The image is resized for displaying. A reference for further processing is stored in self.reference_img_fullSize.
        """

        filepath = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select an image to open",
                                              filetypes=(
                                                  ("jpg files", "*.jpg"), ("png files", "*.png"), ("all files", "*.*")))
        if filepath is None: return

        if filepath.split('.')[-1] in config.supported_extensions:

            self.img_namestring = filepath.split('.')[0]
            self.img_extension = filepath.split('.')[-1]

            pil_img = Image.open(filepath)

            img_width = pil_img.size[0]
            img_height = pil_img.size[1]

            # dirty hack to avoid errors when image is a square:
            if img_width == img_height:
                pil_img = pil_img.resize((img_width, img_height - 1))
                img_width = pil_img.size[0]
                img_height = pil_img.size[1]

            self.reference_img1_fullSize = pil_img

            print_msg("Full image size: {}x{}".format(img_width, img_height), 3)

            # resize images so that they can fit next to each other:

            # margins of the display canvas: 0.6*windowwidth, 0.9*windowheight
            if img_width > img_height:
                max_width = int(0.6 * self.width)  # images wider than high: place above each other
                max_height = int(0.5 * 0.9 * self.height)  # max height is half the display canvas

            elif img_height > img_width:
                max_width = int(0.5 * 0.6 * self.width)  # images higher than wide: place next to each other
                max_height = int(0.9 * self.width)

            max_size = int(0.9 * self.height) if img_height > img_width else int(0.6 * self.width)

            # just to that there are no errors if image is not resized:
            new_img_width = img_width
            new_img_height = img_height

            # img too large: either exceeds max size, or it is too broad / high to be displayed next to each other
            if max(pil_img.size) > max_size or pil_img.size[1] > max_height or pil_img.size[0] > max_width:
                longer_side = max(pil_img.size)
                factor = max_size / longer_side
                new_img_width = int(img_width * factor)
                new_img_height = int(img_height * factor)

                if img_width > img_height and new_img_height > max_height:  # landscape format
                    while new_img_height > max_height:
                        factor *= 0.99
                        print_msg("reduced factor to %f" % factor, 3)
                        new_img_width = int(img_width * factor)
                        new_img_height = int(img_height * factor)

                elif img_height > img_width and new_img_width > max_width:  # portrait format
                    while new_img_width > max_width:
                        factor *= 0.99
                        print_msg("reduced factor to %f" % factor, 3)
                        new_img_width = int(img_width * factor)
                        new_img_height = int(img_height * factor)

                # img is now resized in a way for 2 images to fit next to each other
                pil_img = pil_img.resize((new_img_width, new_img_height))

            self.reference_img1 = pil_img
            tkImage = ImageTk.PhotoImage(pil_img)
            self.tk_img_panel_one.image = tkImage
            self.tk_img_panel_one.configure(image=tkImage)
            print_msg("Display image size: {}x{}".format(new_img_width, new_img_height), 3)

            pil_img_dummy = Image.new('RGB', (new_img_width, new_img_height), (200, 200, 200))
            tkImage_dummy = ImageTk.PhotoImage(pil_img_dummy)
            self.reference_img2 = pil_img_dummy
            self.tk_img_panel_two.image = tkImage_dummy
            self.tk_img_panel_two.configure(image=tkImage_dummy)

            offset_y = int(0.05 * self.height)
            offset_x = int(0.365 * self.width) + 10  # bc line is offset for 10
            space_btwn_imgs = 10

            # "place" geometry manager has 0/0 in the upper left corner

            if img_width > img_height:  # wider than high: place above each other
                space_right_of_line = 0.635 * 0.5 * self.width  # get free space right of line
                img_x = offset_x + int(
                    (space_right_of_line - 0.5 * pil_img.size[0]))  # shift it by line offset, get half
                vertical_middle = 0.9 * 0.5 * self.height  # get available vertical space, middle it
                img_y1 = offset_y + vertical_middle - pil_img.size[1]
                img_y2 = offset_y + vertical_middle + space_btwn_imgs
                self.tk_img_panel_one.place(x=img_x, y=img_y1)
                self.tk_img_panel_two.place(x=img_x, y=img_y2)
                self.helper_x = img_x
                self.helper_y = img_y2

            if img_height > img_width:  # higher than wide: place next to each other
                img_x1 = offset_x + int(0.635 * 0.5 * self.width) - pil_img.size[
                    0]  # get space right of line, divide it by two, subtract img width
                img_x2 = offset_x + int(
                    0.635 * 0.5 * self.width) + space_btwn_imgs  # get space right of line, add small constant
                vertical_middle = 0.9 * 0.5 * self.height  # get available vertical space, middle it
                img_y = offset_y + vertical_middle - int(pil_img.size[1] * 0.5)
                self.tk_img_panel_one.place(x=img_x1, y=img_y)
                self.tk_img_panel_two.place(x=img_x2, y=img_y)
                self.helper_x = img_x2
                self.helper_y = img_y

            self.print_label['text'] = "Image loaded successfully!"
            return pil_img

        else:
            self.print_label['text'] = "No valid image format. Use a format specified in the config."
            return None

    # final can pass with found filter intensities happens in save_image for the full resolution image
    # (to save time during optimization, we optimize on the rescaled image)
    def save_image(self, save_path=None):
        """
        saves an image, if it has previously been modified (i.e., if the slider values != 0).
        The unedited full size reference image is stored in self.reference_img_1_fullSize.
        """

        if self.tk_img_panel_two.winfo_ismapped() and self.slider_variables:
            filepath = filedialog.asksaveasfilename(initialdir=os.getcwd(), title="Save the edited image",
                                                    filetypes=(("as jpg file", "*.jpg"),
                                                               # ("as raw file", "*.png"),
                                                               ("all files", "*.*")))

            if len(filepath.split('.')) == 1:
                filepath += '.jpg'

            self.print_label['text'] = 'Saving image...'

        else:
            self.print_label['text'] = 'Load and edit an image first!'
            return

        current_filer_values, current_gamma = self.get_all_slider_values()
        self.nicer.set_filters(current_filer_values)
        self.nicer.set_gamma(current_gamma)

        # calc a factor for resizing to config.final_size
        width, height = self.reference_img1_fullSize.size  # img.size: (width, height)

        if width > config.final_size or height > config.final_size:
            print("resize")
            print_msg("Resizing to {}p before saving".format(str(config.final_size)), 3)
            factor = config.final_size / height if (height > width) else config.final_size / width

            width = int(width * factor)
            height = int(height * factor)

            try:
                hd_image = self.nicer.single_image_pass_can(self.reference_img1_fullSize.resize((width, height)),
                                                            abn=True)
            except RuntimeError:
                # image and model too large for GPU
                hd_image = self.nicer.single_image_pass_can(self.reference_img1_fullSize.resize((width, height)),
                                                            abn=True, mapToCpu=True)


        else:
            # dims < config.final_size on the longest side, no resizing
            try:
                hd_image = self.nicer.single_image_pass_can(self.reference_img1, abn=True)
            except RuntimeError:
                hd_image = self.nicer.single_image_pass_can(self.reference_img1, abn=True, mapToCpu=True)

        if hd_image is not None:
            hd_image_pil = Image.fromarray(hd_image)
            hd_image_pil.save(filepath)
            self.print_label['text'] = 'Image saved successfully!'
        else:
            self.print_label['text'] = 'Could not save image. See console output.'

    def reset_all(self):
        """ reset GUI and slider values """
        for slider in self.sliders:
            slider.set(0)
        self.gamma_slider.set(0.100)
        for variable in self.slider_variables:
            variable.set(0)
        for checkbox in self.checkboxes:
            checkbox.deselect()
        for variable in self.checkbox_variables:
            variable.set(0)

        self.epochBox.delete(0, 'end')
        self.epochBox.insert(-1, '50')
        self.threadKiller.clear()

        # self.tk_img_panel_one.place_forget()       # leave the current image, reset only filters and edited img
        self.tk_img_panel_two.place_forget()

    def preview(self, filterList=None):
        """ apply the currently set slider combination onto the image (using resized img for increased speed) """
        # check if image is yet available, else do nothing
        if not self.tk_img_panel_one.winfo_ismapped():
            self.print_label['text'] = "Load image first."
            return

        current_filter_values, current_gamma = self.get_all_slider_values()

        self.nicer.set_gamma(current_gamma)
        self.nicer.set_filters(current_filter_values)
        preview_image = self.nicer.single_image_pass_can(self.reference_img1, abn=True)
        self.reference_img2 = Image.fromarray(preview_image)
        self.display_img_two()

    def display_img_two(self):
        tk_preview = ImageTk.PhotoImage(self.reference_img2)
        self.tk_img_panel_two.place(x=self.helper_x, y=self.helper_y)
        self.tk_img_panel_two.image = tk_preview
        self.tk_img_panel_two.configure(image=tk_preview)

    def get_all_slider_values(self):
        values = [var.get() / 100.0 for var in self.slider_variables]
        print_msg("Sliders values: {} -- Gamma: {}".format(values, self.gamma.get()), 3)
        return values, self.gamma.get()

    def get_all_checkbox_values(self):
        values = [var.get() for var in self.checkbox_variables]
        print_msg("Fixed Filters: {}".format(values), 3)
        gui_exp = values[5]
        gui_llf = values[6]
        gui_nld = values[7]
        values[5] = gui_llf
        values[6] = gui_nld
        values[7] = gui_exp  # change indices bc exp in CAN is #8 but in GUI is #5
        return values

    def set_all_image_filter_sliders(self, valueList):
        # does not set gamma. called by nicer_enhance routine to display final outcome of enhancement
        for i in range(5):
            self.sliders[i].set(valueList[i])
            self.slider_variables[i].set(valueList[i])

        # valueList is returned by NICER and has format sat-con-bri-sha-hig-llf-nld-exp
        # sliders is controlled by gui and has format sat-con-bri-sha-hig-exp-llf-nld
        self.sliders[6].set(valueList[5])
        self.sliders[7].set(valueList[6])
        self.sliders[5].set(valueList[7])
        self.slider_variables[6].set(valueList[5])
        self.slider_variables[7].set(valueList[6])
        self.slider_variables[5].set(valueList[7])

    def checkqueue(self):
        while self.nicer.queue.qsize():
            try:
                msg = self.nicer.queue.get(0)
                if isinstance(msg, int):  # passed the epoch count
                    self.print_label['text'] = 'Optimizing epoch {} of {}'.format(str(msg), self.epochCount)
                elif isinstance(msg, list):  # passed the filter values
                    self.set_all_image_filter_sliders([x * 100 for x in msg])
                elif isinstance(msg, np.ndarray):  # thread terminated, passed the last enhanced image
                    enhanced_img_pil = Image.fromarray(msg)
                    self.reference_img2 = enhanced_img_pil
                    self.display_img_two()

                else:  # passed 'dummy' string to get here

                    if not config.preview: return
                    # previewing while optimization, need to do filter setting and can pass manually
                    # cannot use enhanced img from can optimization, as its wrong format (224x224)
                    current_filter_values, gamma = self.get_all_slider_values()
                    filterValues = [0.0] * 8
                    for i in range(5):
                        filterValues[i] = current_filter_values[i]
                    filterValues[5] = current_filter_values[6]  # llf is 5 in can but 6 in gui (bc exp is inserted)
                    filterValues[6] = current_filter_values[7]  # nld is 6 in can but 7 in gui
                    filterValues[7] = current_filter_values[5]  # exp is 7 in can but 5 in gui

                    preview_image = self.alternate_can(self.reference_img1, filterValues)
                    self.reference_img2 = Image.fromarray(preview_image)
                    self.display_img_two()

            except queue.Queue.Empty:
                pass

    def periodiccall(self):
        self.checkqueue()
        if self.thread.is_alive() and running:  # running is set to false by stop button
            self.master.after(100, self.periodiccall)
        elif not self.thread.is_alive() and running:  # thread terminated naturally, after optimization
            self.print_label['text'] = "Optimization finished."
            self.nicer_button.config(state="active")
            self.nicer.queue = queue.Queue()
        else:
            self.threadKiller.set()  # thread killed by stop button
            self.thread.join()
            self.print_label['text'] = "Stopped optimization."
            self.nicer_button.config(state="active")
            self.threadKiller.clear()
            self.nicer.queue = queue.Queue()

    def nicer_routine(self):
        global running
        running = True
        self.nicer_button.config(state="disabled")

        self.nicer_enhance()

    def nicer_enhance(self):

        # check if image is yet available, else do nothing
        if self.tk_img_panel_one.winfo_ismapped():

            self.nicer.re_init()  # reset everything, especially optimizers, for a fresh optimization

            # get slider values and set them for the optimization routine
            slider_vals, gamma = self.get_all_slider_values()
            checkbox_vals = self.get_all_checkbox_values()
            self.nicer.set_filters(slider_vals)
            self.nicer.set_gamma(gamma)

            custom_filters = False
            for value in slider_vals:
                if value != 0.0: custom_filters = True

            self.epochCount = int(self.epochBox.get())

            if not custom_filters:
                print_msg("All filters are zero.", 2)
                self.thread = threading.Thread(target=self.nicer.enhance_image, args=(self.reference_img1,
                                                                                      True, checkbox_vals,
                                                                                      self.epochCount,
                                                                                      self.threadKiller), daemon=True)
            else:
                print_msg("Using user-defined filter preset", 2)
                self.thread = threading.Thread(target=self.nicer.enhance_image, args=(self.reference_img1,
                                                                                      False, checkbox_vals,
                                                                                      self.epochCount,
                                                                                      self.threadKiller), daemon=True)

            self.thread.start()
            self.periodiccall()

        else:
            self.print_label['text'] = "Load image first."

    def alternate_can(self, image, filterList):
        # alternate CAN for previewing the images, as NICER's CAN is used for gradient computation
        # filterList is passable since while optimizing, we cannot use nicer.filters, as these hold the gradients

        # gets called from periodiccall queue handler
        bright_norm_img = normalize_brightness(image, input_is_PIL=True)
        image = Image.fromarray(bright_norm_img)
        image_tensor = transforms.ToTensor()(image)

        filter_tensor = torch.zeros((8, image_tensor.shape[1], image_tensor.shape[2]),
                                    dtype=torch.float32).to(self.device)  # tensorshape [c,w,h]
        for l in range(8):
            filter_tensor[l, :, :] = filterList[l]  # construct uniform filtermap
        mapped_img = torch.cat((image_tensor.cpu(), filter_tensor.cpu()), dim=0).unsqueeze(dim=0).to(self.device)

        enhanced_img = self.can(mapped_img)  # enhance img with CAN
        enhanced_img = enhanced_img.cpu()
        enhanced_img = enhanced_img.detach().permute(2, 3, 1, 0).squeeze().numpy()

        enhanced_clipped = np.clip(enhanced_img, 0.0, 1.0) * 255.0
        enhanced_clipped = enhanced_clipped.astype('uint8')

        # returns a np.array of type np.uint8
        return enhanced_clipped
                     text="Number of Players:",
                     anchor="center",
                     font=("Helvetica", 25),
                     bg=BACKGROUND_COLOR)
playersLabel.place(x=WELCOME_WIDTH * 0.2,
                   y=WELCOME_HEIGHT * 0.7,
                   anchor="center")
playersSlider = Scale(welcomeWindow,
                      from_=1,
                      to=20,
                      orient='horizontal',
                      length=WELCOME_WIDTH * 0.5,
                      font=("Helvetica", 20),
                      bg=BACKGROUND_COLOR)
playersSlider.place(x=WELCOME_WIDTH * 0.65,
                    y=WELCOME_HEIGHT * 0.7,
                    anchor="center")

## -- Functions -- ##


## Runs when an answer choice is made
def answered(a):
    global currentAnswers
    global currentTeam
    if currentAnswers[a] == correctAnswer:
        global scores
        scores[currentTeam] += 1
    global currentQuestion
    currentQuestion = newQuestion()
    currentAnswers = newAnswers()
class Gui(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)

        self.pack()
        global buienradarAPI

        #define master variables (geometry and background)
        master.geometry('{}x{}'.format(1600, 900))
        master.resizable(width=False, height=False)

        master.filename = PhotoImage(file="achtergrond.png")
        master.background_label = Label(master, image=master.filename)
        master.background_label.place(x=0, y=0, relwidth=1, relheight=1)

        #define variables needed to get information from checkboxes in the gui
        self.IntVarWaterHeight = IntVar()
        self.IntVarRainLevel = IntVar()
        self.IntVarWindDirection = IntVar()
        self.IntVarWindSpeed = IntVar()

        #define graph dimensions
        self.graphHeight = 178
        self.graphWidth = 698
        self.startYvar = self.graphHeight + 2
        self.startYvar = self.graphHeight + 2
        self.waterLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.rainLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.windDirectionCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.windSpeedCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.keringStatus = 'OPEN'

        #define frame for gui
        box = Frame(master, relief=SUNKEN, borderwidth=2).pack()
        #define gui elements (graphs, buttons, checkboxes, sliders)
        self.waterLevelGraph = Canvas(box,
                                      height=self.graphHeight,
                                      width=self.graphWidth,
                                      relief=SUNKEN,
                                      borderwidth=1)
        self.waterLevelGraph.place(x=10, y=30)

        self.rainLevelGraph = Canvas(box,
                                     height=self.graphHeight,
                                     width=self.graphWidth,
                                     relief=SUNKEN,
                                     borderwidth=1)
        self.rainLevelGraph.place(x=10, y=250)

        self.windDirectionGraph = Canvas(box,
                                         height=self.graphHeight,
                                         width=self.graphWidth,
                                         relief=SUNKEN,
                                         borderwidth=1)
        self.windDirectionGraph.place(x=10, y=470)

        self.windSpeedGraph = Canvas(box,
                                     height=self.graphHeight,
                                     width=self.graphWidth,
                                     relief=SUNKEN,
                                     borderwidth=1)
        self.windSpeedGraph.place(x=10, y=690)

        self.statusLabel = Label(box,
                                 text=self.keringStatus,
                                 font=('Helvetica', 16),
                                 relief=SUNKEN,
                                 borderwidth=5)
        self.statusLabel.place(x=890, y=50, width=700, height=100)

        self.exitButton = Button(box,
                                 text='Afsluiten',
                                 font=('Helvetica', 16),
                                 command=exit,
                                 borderwidth=2)
        self.exitButton.place(x=1245, y=800, height=90, width=345)

        self.historyButton = Button(box,
                                    text='Historie',
                                    font=('Helvetica', 16),
                                    borderwidth=2,
                                    command=lambda: self.showHistoryWindow())
        self.historyButton.place(x=890, y=800, height=40, width=345)

        self.historyStartEntry = Entry(box, borderwidth=2)
        self.historyStartEntry.insert(0, 'jjjj-mm-dd uu:mm')
        self.historyStartEntry.place(x=890, y=850, height=40, width=170)

        self.historyEndEntry = Entry(box, borderwidth=2)
        self.historyEndEntry.insert(0, 'jjjj-mm-dd uu:mm')
        self.historyEndEntry.place(x=1065, y=850, height=40, width=170)

        self.waterLevelSlider = Scale(box,
                                      from_=0,
                                      to=75,
                                      resolution=25,
                                      relief=RAISED)
        self.waterLevelSlider.place(x=910, y=230, height=265)
        self.waterLevelCheck = Checkbutton(box,
                                           variable=self.IntVarWaterHeight)
        self.waterLevelCheck.place(x=1120, y=350)

        self.rainLevelSlider = Scale(box,
                                     from_=0,
                                     to=250,
                                     resolution=10,
                                     relief=RAISED)
        self.rainLevelSlider.place(x=910, y=505, height=265)
        self.rainLevelCheck = Checkbutton(box, variable=self.IntVarRainLevel)
        self.rainLevelCheck.place(x=1140, y=626)

        self.windDirectionSlider = Scale(box,
                                         from_=0,
                                         to=350,
                                         resolution=10,
                                         relief=RAISED)
        self.windDirectionSlider.place(x=1245, y=230, height=265)

        self.windSpeedSlider = Scale(box, from_=0, to=35, relief=RAISED)
        self.windSpeedSlider.place(x=1245, y=505, height=265)
        self.windSpeedCheck = Checkbutton(box, variable=self.IntVarWindSpeed)
        self.windSpeedCheck.place(x=1505, y=485)

        self.applyConfigButton = Button(box,
                                        text='toepassen',
                                        font=('Helvetica', 16),
                                        command=self.updateConfig)
        self.applyConfigButton.place(x=1462, y=180, height=30, width=117)

    #function used to test checkboxes
    def getConfig(self):
        waterHeightConfigCheck = self.IntVarWaterHeight.get()
        rainLevelConfigCheck = self.IntVarRainLevel.get()
        windDirectionConfigCheck = self.IntVarWindDirection.get()
        windSpeedConfigCheck = self.IntVarWindSpeed.get()
        checksList = []
        checksList.append(waterHeightConfigCheck)
        checksList.append(rainLevelConfigCheck)
        checksList.append(windDirectionConfigCheck)
        checksList.append(windSpeedConfigCheck)
        return checksList

    #function use to create window with title and text as argument
    def create_window(self, title, text):
        t = Toplevel(self)
        t.wm_title(title)
        i = Text(t, relief="flat", height=50, width=93)
        i.insert(1.0, text)
        i.config(state='disabled')
        print(text)
        i.pack()

    #function used to show the historywindow
    def showHistoryWindow(self):
        string = self.getHistoryString()
        self.create_window('Historie', string)

    #function used to format the data from the database into a string for the database
    def getHistoryWindowTextString(self, data):
        formatString = '| {:17}| {:9}| {:12}| {:11}| {:13}| {:7}| {:9}|'
        string = ''
        titles = formatString.format('Tijd', 'Status', 'Waterstand',
                                     'Windkracht', 'Windrichting', 'Server',
                                     'Neerslag')
        string += titles + '\n'

        for item in data:
            string += formatString.format(
                data[data.index(item)]['Tijd'],
                data[data.index(item)]['Status'],
                str(data[data.index(item)]['Waterstand']),
                str(data[data.index(item)]['Windkracht']),
                str(data[data.index(item)]['Windrichting']),
                str(data[data.index(item)]['Instantie']),
                str(data[data.index(item)]['Neerslag'])) + '\n'

        return string

    #function used to generate the textstring for the history window
    def getHistoryString(self):
        self.startEntryString = self.historyStartEntry.get()
        self.endEntryString = self.historyEndEntry.get()
        returnValue = 'beginwaarde'

        if validDateString(self.startEntryString) == True:
            if validDateString(self.endEntryString) == True:
                if time.mktime(
                        time.strptime(self.startEntryString,
                                      '%Y-%m-%d %H:%M')) < time.mktime(
                                          time.strptime(
                                              self.endEntryString,
                                              '%Y-%m-%d %H:%M')):
                    dateTuple = (self.startEntryString, self.endEntryString)
                    historyData = database.getHistory(dateTuple)
                    returnValue = self.getHistoryWindowTextString(historyData)

                else:
                    returnValue = 'Begintijd gelijk aan of later dan eindtijd'
                    print(validDateString(self.endEntryString))
            else:

                returnValue = 'Eindtijd onjuist'
        else:
            returnValue = 'Begintijd onjuist'
        print('functie doorlopen')
        print(returnValue)
        return returnValue

    #function used to read config from the GUI and write to file
    def updateConfig(self):
        print('config updated')
        if self.IntVarWaterHeight.get() == 0:
            waterheightParameter = '-'
        else:
            waterheightParameter = self.waterLevelSlider.get()

        if self.IntVarWindSpeed.get() == 0:
            windSpeedParameter = '-'
        else:
            windSpeedParameter = self.windSpeedSlider.get()

        if self.IntVarRainLevel.get() == 0:
            rainLevelParameter = '-'
        else:
            rainLevelParameter = self.rainLevelSlider.get()

        windDirectionParameter = self.windDirectionSlider.get()

        writeParameters('./parameters.json', windDirectionParameter,
                        windSpeedParameter, waterheightParameter,
                        rainLevelParameter)

    #function used to update the list with y-coordinates for the tkinter canvaess
    def updateYCoordList(self, list, type):
        if type == 'rainLevel':
            list.append(self.getRainLevelYCoord())
            list.remove(list[0])

        elif type == 'waterLevel':
            list.append(self.getWaterLevelYCoord())
            list.remove(list[0])

        elif type == 'windDirection':
            list.append(self.getWindDirectionYCoord())
            list.remove(list[0])

        elif type == 'windSpeed':
            list.append(self.getWindSpeedYCoord())
            list.remove(list[0])

        else:
            list.append(36)
            list.remove(list[0])
        return list

    #function used to draw a graph using tkinter canvas module with a list of y-coordinates and a canvas as arguments
    def drawGraph(self, list, canvas):
        canvas.delete('all')
        startX = 0
        for index in range(len(list) - 1):
            startY = self.startYvar - list[index]
            try:
                endY = self.startYvar - list[index + 1]
            except:
                print('error')
                pass
            endX = startX + 100
            canvas.create_line(startX, startY, endX, endY)
            startX += 100

    #function used to update graph with graph type and update interval as arguments
    def updateGraph(self, list, canvas, type, miliseconds):
        self.drawGraph(self.updateYCoordList(list, type), canvas)
        canvas.after(miliseconds, self.updateGraph, list, canvas, type,
                     miliseconds)

    #function used to update statuslabel ever quarter of a second
    def updateStatusLabel(self, label):
        text = self.getKeringStatus()
        label.configure(text=text)
        label.after(250, self.updateStatusLabel, label)

    #function used to get the status of the kering from the gpio system
    def getKeringStatus(self):
        try:
            data = serverFunctions.gpioRequest()
            statusString = 'status:' + data[1]
            return statusString
        except:
            return 'ERROR'

    #function used to generate y-coordinate for rainFall
    def getRainLevelYCoord(self):
        rainLevel = buienradarAPI['regenMMPU']
        if rainLevel == '-':
            rainLevel = 0
        rainLevelY = int(float(rainLevel) * 1.388888888888889)
        return rainLevelY

    #function used to generate y-coordinate for wind speed
    def getWindSpeedYCoord(self):
        windSpeed = buienradarAPI['windsnelheidMS']
        windSpeedY = int(float(windSpeed) * 5)
        return windSpeedY

    #function used to generate y-coordinate for wind direction
    def getWindDirectionYCoord(self):
        windDirection = buienradarAPI['windrichtingGR']
        windDirectionY = int(float(windDirection) * 0.4)
        return windDirectionY

    #function used to generate y-coordinate for water level
    def getWaterLevelYCoord(self):
        data = serverFunctions.gpioRequest()
        return data[0] * 2
wdScale.set(95)
wdScale2.set(720)
thresholdSlider.set(28)

frame2.pack(anchor='ne')
frame3.pack(anchor='se')
lmain.place(x=camFrameWidth / 2, y=cam1FrameHeight / 2, anchor="center")
lmain2.place(x=camFrameWidth / 2, y=cam2FrameHeight / 2 - 70, anchor="center")
lslave.place(x=20, y=cam1FrameHeight / 2, anchor="w")
lOptions.place(x=20, y=cam1FrameHeight / 2 + 30, anchor="w")
lslave2.place(x=20, y=50, anchor="w")
lOptions2.place(x=20, y=80, anchor="w")
labelTitle = Label(frame, text="Eye Tracker", font=("Times New Roman", 30))
labelTitle.place(x=menuFrameWidth / 2, y=30, anchor="center")
lslave3.place(x=20, y=110, anchor="w")
htScale.place(x=20, y=150, anchor="w")
htScale2.place(x=20, y=190, anchor="w")
wdScale.place(x=20, y=240, anchor="w")
wdScale2.place(x=20, y=280, anchor="w")
thresholdSlider.place(x=20, y=320, anchor="w")

beaconCount = StringVar()
beaconCount.set("Program not running")

labelTrackingTitle = Label(frame, text="Tracking Beacons:")
labelTrackingTitle.place(x=menuFrameWidth / 2, y=height - 300, anchor="center")
labelTrackingCount = Label(frame, textvariable=beaconCount)
labelTrackingCount.place(x=menuFrameWidth / 2, y=height - 260, anchor="center")

quitApp = Button(frame, command=shutdownTime, text="Quit")
quitApp.place(x=menuFrameWidth / 2,
class NewSliderWindow(Toplevel):
    def __init__(self, master=None):
        super().__init__(master=master)
        self.set_basic()

        self.bind('<Configure>', lambda e: self.place_buttons())

    def set_basic(self):
        self.overrideredirect(1)
        self.set_geometry()
        self.set_scale()
        self.set_checkButton()
        self.set_save_closeButtons()

    def set_geometry(self):
        self.width = 60
        parentX = self.master.winfo_rootx()
        parentY = self.master.winfo_rooty()
        parentHeight = self.master.winfo_height()
        parentWidth = self.master.winfo_width()
        self.geometry(
            '%dx%d+%d+%d' %
            (self.width, parentHeight, parentX + parentWidth + 2, parentY))

    def set_save_closeButtons(self):
        self.saveButton = Button(self,
                                 image=saveIcon,
                                 command=self.update_image)
        self.cancelButton = Button(self, image=closeIcon, command=self.cancel)

        self.saveButton.place(relx=0.1, rely=0.8, relwidth=0.4)
        self.cancelButton.place(relx=0.55, rely=0.8, relwidth=0.4)

        self.saveButton.place(
            relx=0.1,
            rely=1 - ((0.4 * self.width) / self.master.winfo_height()),
            relwidth=0.4)
        self.cancelButton.place(
            relx=0.55,
            rely=1 - ((0.4 * self.width) / self.master.winfo_height()),
            relwidth=0.4)

    def place_buttons(self):
        self.saveButton.place(
            relx=0.03,
            rely=1 - ((0.45 * self.width) / self.master.winfo_height()),
            relwidth=0.45)
        self.cancelButton.place(
            relx=0.52,
            rely=1 - ((0.45 * self.width) / self.master.winfo_height()),
            relwidth=0.45)

    def set_scale(self):
        self.var = IntVar()
        self.scale = Scale(self,
                           length=256,
                           from_=0,
                           to=255,
                           orient=VERTICAL,
                           command=lambda e: self.update_preview(
                               int(self.var.get()), self.cbVal.get()),
                           variable=self.var,
                           digits=1,
                           resolution=1)
        self.scale.place(relx=0, rely=0.1, relwidth=0.9, relheight=0.7)
        self.scale.set(0)

    def set_checkButton(self):
        self.cbVal = IntVar()
        self.cb = Checkbutton(self,
                              width=0,
                              variable=self.cbVal,
                              command=lambda: self.update_preview(
                                  int(self.var.get()), self.cbVal.get()))
        self.cb.place(relx=0.4, rely=0.78)
        self.cb.invoke()

    #UPDATE IMAGE ON SLIDER CHANGE
    def update_preview(self, thresholdVal, checkBoxVal):
        self.master.image.threshold(thresholdVal, checkBoxVal)
        self.master.update_visible_image()

    #UPDATE IMAGE ON "SAVE" AND UPDATE HISTOGRAM
    def update_image(self):
        self.master.update_visible_image()
        self.master.image.copy = copy.deepcopy(self.master.image.cv2Image)
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.thresholdScaleWindow = None
        self.master.manager.new_state(self.master.image.cv2Image)
        self.destroy()

    #GO BACK TO ORIGINAL ON "CANCEL"
    def cancel(self):
        self.master.image.cv2Image = copy.deepcopy(self.master.image.copy)
        self.master.update_visible_image()
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.thresholdScaleWindow = None
        self.destroy()
Exemple #24
0
class Root(Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title('PEAUCELLIER LINKAGE')
        self.geometry('1280x720')
        self.resizable(0, 0)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.measure_state = False
        self.protocol("WM_DELETE_WINDOW", self.salirfichero)
        self.a_value = DoubleVar()
        self.a_value.set(2)
        self.b_value = DoubleVar()
        self.b_value.set(5)
        self.c_value = DoubleVar()
        self.c_value.set(2)
        self.a0_value = DoubleVar()
        self.a0_value.set(0)
        self.b0_value = DoubleVar()
        self.b0_value.set(22.3316)
        self.c0_value = DoubleVar()
        self.c0_value.set(0)
        self.r_value = DoubleVar()
        self.r_xtr = [1.01, 5]
        self.r_value.set(2)
        self.scale_factor = DoubleVar()
        self.scale_factor.set(1)
        self.j = 0
        self.xs = []
        self.ys = []
        self.alpha = []
        self.beta = []
        self.theta = []
        self.time = []
        self.ratio = 60
        self.theta_max = DoubleVar()
        self.theta_max.set(round(math.degrees(1.4455), 4))
        self.x_max = DoubleVar()
        self.x_max.set(5.25)
        self.y_max = DoubleVar()
        self.y_max.set(4.6301)
        self.t_max = 1.4455
        self.widgets()

    def points_pos(self):
        a = self.a_value.get()
        b = self.b_value.get()
        c = self.c_value.get()
        r = self.r_value.get()
        t0 = self.c0_value.get()
        t_max = math.acos(
            (b**2 + c**2 - r**2 - a**2 - 2 * b * c) / (2 * r * a))
        ymax = (b + c) * (a * sen(t_max)) / (b - c)
        xmax = ((b + c)**2 - ymax**2)**0.5
        self.x_max.set(round(xmax, 4))
        self.y_max.set(round(ymax, 4))
        self.t_max = t_max
        if abs(t0) > t_max:
            sgn = t0 / abs(t0)
            t0 = t_max * sgn * 1
        A = [0, 0]
        B = [r, 0]
        C = [r + a * cos(t0), a * sen(t0)]
        AC = norm(C)
        alpha = math.atan(C[1] / C[0])
        beta = math.acos((b**2 + AC**2 - c**2) / (2 * b * AC))
        D = [b * cos(alpha + beta), b * sen(alpha + beta)]
        E = [b * cos(alpha - beta), b * sen(alpha - beta)]
        AF = (b**2 - c**2) / AC
        F = [AF * cos(alpha), AF * sen(alpha)]

        r_min = max([a - b + c, b - c - a, c - b - a, a - b - c])
        r_max = b + c - a
        self.r_xtr = [r_min + 0.01, r_max - 0.01]
        self.points = np.around(np.array([A, B, C, D, E, F]), 4)
        self.a0_value.set(round(math.degrees(alpha), 4))
        self.b0_value.set(round(math.degrees(beta), 4))
        self.c0_value.set(round(math.degrees(t0), 4))
        self.theta_max.set(round(math.degrees(t_max), 4))
        self.alpha.append(alpha)
        self.beta.append(beta)
        self.theta.append(t0)
        self.alpha = self.alpha[-self.ratio:]
        self.beta = self.beta[-self.ratio:]
        self.theta = self.theta[-self.ratio:]

    def salirfichero(self):
        valor = messagebox.askquestion('Salir', '¿Desea cerrar la aplicacion?')
        if valor == 'yes':
            self.destroy()

    def animate(self, i):
        self.i = i
        try:
            a = self.a_value.get()
            b = self.b_value.get()
            c = self.c_value.get()
        except:
            a = 0
            b = 0
            c = 0

        p1 = np.linspace(-self.t_max, self.t_max, num=50)
        p_inv = np.flipud(p1)
        p2 = p_inv[1:-1]
        angle_list = np.concatenate((p1, p2), axis=0)
        if self.measure_state and a != 0 and b != 0 and c != 0:
            cont = self.i % 98
            if self.selected.get() == 2:
                angle = math.sin(self.i / 20) * (self.t_max) * 0.9
            elif self.selected.get() == 3:
                if cont == 0:
                    self.j = self.j + 1
                angle = angle_list[cont * (-1)**self.j]
            else:
                angle = math.sin(self.i / 20) * (self.t_max) * 0.9

            self.c0_value.set(angle)
            state = False
            try:
                self.points_pos()
                state = True
            except:
                state = False
            if state:

                self.r_scale.config(from_=self.r_xtr[0], to=self.r_xtr[1])
                self.ax.clear()
                self.ax2.clear()

                n = 1.1
                y = self.y_max.get() * n
                x = self.x_max.get() * n
                if 1.2 * x < 2 * y:
                    self.ax.set_ylim(-y, y)
                    self.ax.set_xlim(-y * 0.2, y * 1.8)
                else:
                    self.ax.set_ylim(-0.6 * x, 0.6 * x)
                    self.ax.set_xlim(-x * 0.2, x)

                point = np.transpose(self.points)
                x_data = point[0, :]
                y_data = point[1, :]
                self.ax.plot(x_data, y_data, 'o')

                text = ['A', 'B', 'C', 'D', 'E', 'F']
                for i in range(len(text)):
                    self.ax.text(x_data[i] + 0.3, y_data[i] + 0.3, text[i])

                angle_plot = ['α', 'β', 'θ']
                alpha = self.alpha[-1]
                alpha_array = np.linspace(0, alpha, num=20)
                beta = self.beta[-1]
                beta_array = np.linspace(alpha, alpha + beta, num=20)
                theta = self.theta[-1]
                theta_array = np.linspace(0, theta, num=20)
                AD = norm([x_data[3], y_data[3]])
                BC = norm([x_data[2] - x_data[1], y_data[2] - y_data[1]])
                self.ax.text(AD * 0.3 * math.cos(alpha * 0.5),
                             AD * 0.3 * math.sin(alpha * 0.5), angle_plot[0])
                self.ax.plot(AD * 0.3 * np.cos(alpha_array),
                             AD * 0.3 * np.sin(alpha_array), 'b')
                self.ax.text(AD * 0.5 * math.cos(alpha + beta * 0.5),
                             AD * 0.5 * math.sin(alpha + beta * 0.5),
                             angle_plot[1])
                self.ax.plot(AD * 0.5 * np.cos(beta_array),
                             AD * 0.5 * np.sin(beta_array), 'r')
                self.ax.text(
                    BC * 0.5 * math.cos(theta * 0.5) + x_data[1] * 1.1,
                    BC * 0.5 * math.sin(theta * 0.5), angle_plot[2])
                self.ax.plot(BC * 0.5 * np.cos(theta_array) + x_data[1],
                             BC * 0.5 * np.sin(theta_array), 'g')

                data_lines = [[0, 1, 'k'], [0, 3, 'r'], [0, 4,
                                                         'r'], [1, 2, 'b'],
                              [2, 3, 'g'], [2, 4, 'g'], [3, 5, 'g'],
                              [4, 5, 'g'], [0, 5, '--']]
                for i, j, k in data_lines:
                    self.ax.plot([x_data[i], x_data[j]],
                                 [y_data[i], y_data[j]], k)

                self.time.append(self.i / 20)
                self.xs.append(x_data[5])
                self.ys.append(y_data[5])
                self.xs = self.xs[-self.ratio:]
                self.ys = self.ys[-self.ratio:]
                self.time = self.time[-self.ratio:]
                xs2 = np.array(self.xs)
                ys2 = np.array(self.ys)
                time = np.array(self.time)
                xs = np.array(self.xs[-15:])
                ys = np.array(self.ys[-15:])
                self.ax.plot(xs, ys, 'c.', alpha=0.5)
                alpha = np.array(self.alpha)
                beta = np.array(self.beta)
                theta = np.array(self.theta)
                try:
                    scale = self.scale_factor.get()
                except:
                    scale = 1
                if scale == 0:
                    scale = 1
                if len(self.xs) > 3:
                    w_a = np.gradient(alpha)
                    a_a = np.gradient(w_a)
                    w_b = np.gradient(beta)
                    a_b = np.gradient(w_b)
                    w_t = np.gradient(theta)
                    a_t = np.gradient(w_t)
                    dx = np.gradient(xs2)
                    dy = np.gradient(ys2)
                    d2x = np.gradient(dx)
                    d2y = np.gradient(dy)
                    vF = norm([dx, dy])
                    aF = norm([d2x, d2y])
                    v = [xs[-1] - xs[-2], ys[-1] - ys[-2]]
                    self.ax.quiver(xs[-1],
                                   ys[-1],
                                   v[0],
                                   v[1],
                                   angles='xy',
                                   scale_units='xy',
                                   scale=0.08,
                                   color='blue')
                    a = [
                        xs[-1] + xs[-3] - xs[-2] * 2,
                        ys[-1] + ys[-3] - ys[-2] * 2
                    ]
                    self.ax.quiver(xs[-1],
                                   ys[-1],
                                   a[0],
                                   a[1],
                                   angles='xy',
                                   scale_units='xy',
                                   scale=0.008,
                                   color='red')
                    coef = list(map(lambda x: x.get(), self.var_data))
                    values = [
                        alpha, beta, theta, w_a, a_a, w_b, a_b, w_t, a_t, vF,
                        aF
                    ]
                    cn = colors.Normalize(0, 11)
                    for i in range(11):
                        if coef[i] == 1:
                            if self.selected.get() == 1:
                                lim = self.t_max
                                self.ax2.set_ylim(-lim * 0.5 / scale,
                                                  lim * 0.5 / scale)
                                self.ax2.set_xlim(-lim, lim)
                                self.ax2.plot(self.theta,
                                              values[i],
                                              color=plt.cm.jet(cn(i)))
                            elif self.selected.get() == 2 or self.selected.get(
                            ) == 3:
                                lim = self.t_max
                                self.ax2.set_ylim(-self.t_max / scale,
                                                  self.t_max / scale)
                                self.ax2.set_xlim(time.min(), time.max())
                                self.ax2.plot(time,
                                              values[i] * scale,
                                              color=plt.cm.jet(cn(i)))

                self.ax.grid(True)
                self.ax2.grid(True)
                self.i = self.i + 1

    def state(self):
        if (self.measure_button['text'] == 'START'):
            self.measure_button['text'] = 'STOP'
            self.measure_state = True
        else:
            self.measure_button['text'] = 'START'
            self.measure_state = False

    def widgets(self):

        title = Label(self, text='PEAUCELLIER LINKAGE ANALISYS')
        title.place(x=300, y=10)
        title.config(justify='center', font=("Courier", 30))

        data_label = Label(self,
                           text='Input data: ',
                           font=("Times", 15, "italic"))
        data_label.place(x=75, y=75)
        a_label = Label(self, text='a: ', font=("Times", 15, "italic"))
        a_label.place(x=75, y=115)
        a_entry = Entry(self, textvariable=self.a_value)
        a_entry.place(x=100, y=120)
        a_color = Label(self, bg='blue', width=2)
        a_color.place(x=230, y=120)
        b_label = Label(self, text='b: ', font=("Times", 15, "italic"))
        b_label.place(x=75, y=145)
        b_entry = Entry(self, textvariable=self.b_value)
        b_entry.place(x=100, y=150)
        b_color = Label(self, bg='red', width=2)
        b_color.place(x=230, y=150)
        c_label = Label(self, text='c: ', font=("Times", 15, "italic"))
        c_label.place(x=75, y=175)
        c_entry = Entry(self, textvariable=self.c_value)
        c_entry.place(x=100, y=180)
        c_color = Label(self, bg='green', width=2)
        c_color.place(x=230, y=180)

        r_label = Label(self, text='r: ', font=("Times", 15, "italic"))
        r_label.place(x=270, y=135)
        self.r_scale = Scale(self,
                             variable=self.r_value,
                             from_=self.r_xtr[0],
                             to=self.r_xtr[1],
                             orient=HORIZONTAL,
                             length=200,
                             resolution=0.01)
        self.r_scale.place(x=315, y=125)

        data_label = Label(self,
                           text='Output data: ',
                           font=("Times", 15, "italic"))
        data_label.place(x=775, y=75)
        a0_label = Label(self, text='α: ', font=("Times", 15, "italic"))
        a0_label.place(x=775, y=115)
        a1_label = Label(self,
                         textvariable=self.a0_value,
                         font=("Times", 15, "italic"))
        a1_label.place(x=800, y=115)
        b0_label = Label(self, text='β: ', font=("Times", 15, "italic"))
        b0_label.place(x=775, y=145)
        b1_label = Label(self,
                         textvariable=self.b0_value,
                         font=("Times", 15, "italic"))
        b1_label.place(x=800, y=145)
        c0_label = Label(self, text='θ: ', font=("Times", 15, "italic"))
        c0_label.place(x=775, y=175)
        b1_label = Label(self,
                         textvariable=self.c0_value,
                         font=("Times", 15, "italic"))
        b1_label.place(x=800, y=175)
        m0_label = Label(self, text='θ_max: ', font=("Times", 15, "italic"))
        m0_label.place(x=975, y=115)
        m1_label = Label(self,
                         textvariable=self.theta_max,
                         font=("Times", 15, "italic"))
        m1_label.place(x=1050, y=115)
        y0_label = Label(self, text='y_max: ', font=("Times", 15, "italic"))
        y0_label.place(x=975, y=145)
        y1_label = Label(self,
                         textvariable=self.y_max,
                         font=("Times", 15, "italic"))
        y1_label.place(x=1050, y=145)
        x0_label = Label(self, text='x_max: ', font=("Times", 15, "italic"))
        x0_label.place(x=975, y=175)
        x1_label = Label(self,
                         textvariable=self.x_max,
                         font=("Times", 15, "italic"))
        x1_label.place(x=1050, y=175)
        scale_label = Label(self,
                            text='scale factor:',
                            font=("Times", 15, "italic"))
        scale_label.place(x=800, y=220)
        scale_entry = Entry(self, textvariable=self.scale_factor)
        scale_entry.place(x=920, y=225)

        self.measure_button = Button(self, text='START', command=self.state)
        self.measure_button.place(x=50, y=250)

        self.var_data = []
        self.var_text = [
            'α', 'β', 'θ', 'w_α', 'α_α', 'w_β', 'α_β', 'w_θ', 'α_θ', 'v', 'a'
        ]
        for i in range(len(self.var_text)):
            self.var_data.append(IntVar())
            Checkbutton(self,
                        text=self.var_text[i],
                        variable=self.var_data[-1]).place(x=570, y=80 + i * 20)

        self.selected = IntVar()
        Radiobutton(self, text='θ', value=1,
                    variable=self.selected).place(x=650, y=80)
        Radiobutton(self, text='t ∿', value=2,
                    variable=self.selected).place(x=650, y=100)
        Radiobutton(self, text='t ʌ', value=3,
                    variable=self.selected).place(x=650, y=120)

        self.fig = Figure(figsize=(14, 4), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.get_tk_widget().place(x=-100, y=300)
        gs = self.fig.add_gridspec(1, 3)
        self.ax = self.fig.add_subplot(gs[0, 0])
        self.ax2 = self.fig.add_subplot(gs[0, 1:])
        self.measure_state = True
        self.animate(0)
        self.measure_state = False
Exemple #25
0
class Gui(Frame):
    counter = 0

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

        self.pack()
        global buienradarAPI

        #define master variables (geometry and background)
        master.geometry('{}x{}'.format(1600, 900))
        master.resizable(width=False, height=False)

        master.filename = PhotoImage(file="achtergrond.png")
        master.background_label = Label(master, image=master.filename)
        master.background_label.place(x=0, y=0, relwidth=1, relheight=1)

        #define variables needed to get information from checkboxes in the gui
        self.IntVarWaterHeight = IntVar()
        self.IntVarRainLevel = IntVar()
        self.IntVarWindDirection = IntVar()
        self.IntVarWindSpeed = IntVar()

        #define graph dimensions
        self.graphHeight = 178
        self.graphWidth = 698
        self.startYvar = self.graphHeight + 2
        self.startYvar = self.graphHeight + 2
        self.waterLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.rainLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.windDirectionCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.windSpeedCoords = [0, 0, 0, 0, 0, 0, 0, 0]
        self.keringStatus = 'OPEN'

        #define frame for gui
        box = Frame(master, relief=SUNKEN, borderwidth=2).pack()
        #define gui elements (graphs, buttons, checkboxes, sliders)
        self.waterLevelGraph = Canvas(box,
                                      height=self.graphHeight,
                                      width=self.graphWidth,
                                      relief=SUNKEN,
                                      borderwidth=1)
        self.waterLevelGraph.place(x=10, y=30)

        self.rainLevelGraph = Canvas(box,
                                     height=self.graphHeight,
                                     width=self.graphWidth,
                                     relief=SUNKEN,
                                     borderwidth=1)
        self.rainLevelGraph.place(x=10, y=250)

        self.windDirectionGraph = Canvas(box,
                                         height=self.graphHeight,
                                         width=self.graphWidth,
                                         relief=SUNKEN,
                                         borderwidth=1)
        self.windDirectionGraph.place(x=10, y=470)

        self.windSpeedGraph = Canvas(box,
                                     height=self.graphHeight,
                                     width=self.graphWidth,
                                     relief=SUNKEN,
                                     borderwidth=1)
        self.windSpeedGraph.place(x=10, y=690)

        self.statusLabel = Label(box,
                                 text=self.keringStatus,
                                 font=('Helvetica', 16),
                                 relief=SUNKEN,
                                 borderwidth=5)
        self.statusLabel.place(x=890, y=50, width=700, height=100)

        self.exitButton = Button(box,
                                 text='Afsluiten',
                                 font=('Helvetica', 16),
                                 command=exit,
                                 borderwidth=2)
        self.exitButton.place(x=1245, y=800, height=90, width=345)

        self.historyButton = Button(box,
                                    text='Historie',
                                    font=('Helvetica', 16),
                                    borderwidth=2,
                                    command=lambda: self.showHistoryWindow())
        self.historyButton.place(x=890, y=800, height=40, width=345)

        self.historyStartEntry = Entry(box, borderwidth=2)
        self.historyStartEntry.insert(0, 'jjjj-mm-dd uu:mm')
        self.historyStartEntry.place(x=890, y=850, height=40, width=170)

        self.historyEndEntry = Entry(box, borderwidth=2)
        self.historyEndEntry.insert(0, 'jjjj-mm-dd uu:mm')
        self.historyEndEntry.place(x=1065, y=850, height=40, width=170)

        self.waterLevelSlider = Scale(box,
                                      from_=0,
                                      to=75,
                                      resolution=25,
                                      relief=RAISED)
        self.waterLevelSlider.place(x=910, y=230, height=265)
        self.waterLevelCheck = Checkbutton(box,
                                           variable=self.IntVarWaterHeight)
        self.waterLevelCheck.place(x=1120, y=350)

        self.rainLevelSlider = Scale(box,
                                     from_=0,
                                     to=250,
                                     resolution=10,
                                     relief=RAISED)
        self.rainLevelSlider.place(x=910, y=505, height=265)
        self.rainLevelCheck = Checkbutton(box, variable=self.IntVarRainLevel)
        self.rainLevelCheck.place(x=1140, y=626)

        self.windDirectionSlider = Scale(box,
                                         from_=0,
                                         to=350,
                                         resolution=10,
                                         relief=RAISED)
        self.windDirectionSlider.place(x=1245, y=230, height=265)

        self.windSpeedSlider = Scale(box, from_=0, to=35, relief=RAISED)
        self.windSpeedSlider.place(x=1245, y=505, height=265)
        self.windSpeedCheck = Checkbutton(box, variable=self.IntVarWindSpeed)
        self.windSpeedCheck.place(x=1505, y=485)

        self.applyConfigButton = Button(box,
                                        text='toepassen',
                                        font=('Helvetica', 16),
                                        command=self.updateConfig)
        self.applyConfigButton.place(x=1462, y=180, height=30, width=117)

    #function used to test checkboxes
    def getConfig(self):
        waterHeightConfigCheck = self.IntVarWaterHeight.get()
        rainLevelConfigCheck = self.IntVarRainLevel.get()
        windDirectionConfigCheck = self.IntVarWindDirection.get()
        windSpeedConfigCheck = self.IntVarWindSpeed.get()
        checksList = []
        checksList.append(waterHeightConfigCheck)
        checksList.append(rainLevelConfigCheck)
        checksList.append(windDirectionConfigCheck)
        checksList.append(windSpeedConfigCheck)
        return checksList

    def create_window(self, title, text):
        t = Toplevel(self)
        t.wm_title(title)
        i = Text(t, relief="flat", height=50, width=70)
        i.insert(1.0, text)
        i.config(state='disabled')
        print(text)
        i.pack()

    def showHistoryWindow(self):
        string = self.getHistoryString()
        self.create_window('Historie', string)

    def getHistoryString(self):
        self.startEntryString = self.historyStartEntry.get()
        self.endEntryString = self.historyEndEntry.get()
        returnValue = 'beginwaarde'

        if validDateString(self.startEntryString) == True:
            if validDateString(self.endEntryString) == True:
                if time.mktime(
                        time.strptime(self.startEntryString,
                                      '%Y-%m-%d %H:%M')) <= time.mktime(
                                          time.strptime(
                                              self.endEntryString,
                                              '%Y-%m-%d %H:%M')):
                    returnValue = (self.startEntryString, self.endEntryString)
        else:
            returnValue = 'allemaal problemen'
        print('functie doorlopen')
        print(returnValue)
        return returnValue

    #function used to read config from the GUI and write to file
    def updateConfig(self):
        print('config updated')
        if self.IntVarWaterHeight.get() == 0:
            waterheightParameter = '-'
        else:
            waterheightParameter = self.waterLevelSlider.get()

        if self.IntVarWindSpeed.get() == 0:
            windSpeedParameter = '-'
        else:
            windSpeedParameter = self.windSpeedSlider.get()

        if self.IntVarRainLevel.get() == 0:
            rainLevelParameter = '-'
        else:
            rainLevelParameter = self.rainLevelSlider.get()

        windDirectionParameter = self.windDirectionSlider.get()

        writeParameters('params.json', windDirectionParameter,
                        windSpeedParameter, waterheightParameter,
                        rainLevelParameter)

    #function used to
    def updateYCoordList(self, list, type):
        if type == 'rainLevel':
            list.append(self.getRainLevelYCoord())
            list.remove(list[0])

        elif type == 'waterLevel':
            list.append(self.getWaterLevelYCoord())
            list.remove(list[0])

        elif type == 'windDirection':
            list.append(self.getWindDirectionYCoord())
            list.remove(list[0])

        elif type == 'windSpeed':
            list.append(self.getWindSpeedYCoord())
            list.remove(list[0])

        else:
            list.append(36)
            list.remove(list[0])
        return list

    def drawGraph(self, list, canvas):
        canvas.delete('all')
        startX = 0
        for index in range(len(list) - 1):
            startY = self.startYvar - list[index]
            try:
                endY = self.startYvar - list[index + 1]
            except:
                print('error')
                pass
            endX = startX + 100
            canvas.create_line(startX, startY, endX, endY)
            startX += 100

    def updateGraph(self, list, canvas, type, miliseconds):
        self.drawGraph(self.updateYCoordList(list, type), canvas)
        canvas.after(miliseconds, self.updateGraph, list, canvas, type,
                     miliseconds)

    def updateStatusLabel(self, label):
        label.configure(text=random.randint(0, 9))
        label.after(100, self.updateStatusLabel, label)

    def getRainLevelYCoord(self):
        rainLevel = buienradarAPI['regenMMPU']
        if rainLevel == '-':
            rainLevel = 0
        rainLevelY = int(float(rainLevel) * 1.388888888888889)
        return rainLevelY

    def getWindSpeedYCoord(self):
        windSpeed = buienradarAPI['windsnelheidMS']
        windSpeedY = int(float(windSpeed) * 5)
        return windSpeedY

    def getWindDirectionYCoord(self):
        windDirection = buienradarAPI['windrichtingGR']
        windDirectionY = int(float(windDirection) * 0.4)
        return windDirectionY

    def getWaterLevelYCoord(self):
        return 50
Exemple #26
0
    class vedoGUI(Frame):
        def __init__(self, parent):
            Frame.__init__(self, parent, bg="white")
            self.parent = parent
            self.filenames = []
            self.noshare = BooleanVar()
            self.flat = BooleanVar()
            self.xspacing = StringVar()
            self.yspacing = StringVar()
            self.zspacing = StringVar()
            self.background_grad = BooleanVar()
            self.initUI()

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

            ############import
            Button(self,
                   text="Import Files",
                   command=self._importCMD,
                   width=15).place(x=115, y=17)

            ############meshes
            Frame(root, height=1, width=398, bg="grey").place(x=1, y=60)
            Label(self,
                  text="Meshes",
                  fg="white",
                  bg="green",
                  font=("Courier 11 bold")).place(x=20, y=65)

            # color
            Label(self, text="Color:", bg="white").place(x=30, y=98)
            colvalues = ('by scalar', 'gold', 'red', 'green', 'blue', 'coral',
                         'plum', 'tomato')
            self.colorCB = Combobox(self,
                                    state="readonly",
                                    values=colvalues,
                                    width=10)
            self.colorCB.current(0)
            self.colorCB.place(x=100, y=98)

            # mode
            modvalues = ('surface', 'surf. & edges', 'wireframe',
                         'point cloud')
            self.surfmodeCB = Combobox(self,
                                       state="readonly",
                                       values=modvalues,
                                       width=14)
            self.surfmodeCB.current(0)
            self.surfmodeCB.place(x=205, y=98)

            # alpha
            Label(self, text="Alpha:", bg="white").place(x=30, y=145)
            self.alphaCB = Scale(
                self,
                from_=0,
                to=1,
                resolution=0.02,
                bg="white",
                length=220,
                orient="horizontal",
            )
            self.alphaCB.set(1.0)
            self.alphaCB.place(x=100, y=125)

            # lighting
            Label(self, text="Lighting:", bg="white").place(x=30, y=180)
            lightvalues = ('default', 'metallic', 'plastic', 'shiny', 'glossy')
            self.lightCB = Combobox(self,
                                    state="readonly",
                                    values=lightvalues,
                                    width=10)
            self.lightCB.current(0)
            self.lightCB.place(x=100, y=180)
            # shading phong or flat
            self.flatCB = Checkbutton(self,
                                      text="flat shading",
                                      var=self.flat,
                                      bg="white")
            #self.flatCB.select()
            self.flatCB.place(x=210, y=180)

            # rendering arrangement
            Label(self, text="Arrange as:", bg="white").place(x=30, y=220)
            schemevalues = ('superpose (default)', 'mesh browser',
                            'n sync-ed renderers')
            self.schememodeCB = Combobox(self,
                                         state="readonly",
                                         values=schemevalues,
                                         width=20)
            self.schememodeCB.current(0)
            self.schememodeCB.place(x=160, y=220)

            # share cam
            self.noshareCB = Checkbutton(self,
                                         text="independent cameras",
                                         variable=self.noshare,
                                         bg="white")
            self.noshareCB.place(x=160, y=245)

            ############volumes
            Frame(root, height=1, width=398, bg="grey").place(x=1, y=275)
            Label(self,
                  text="Volumes",
                  fg="white",
                  bg="blue",
                  font=("Courier 11 bold")).place(x=20, y=280)

            # mode
            Label(self, text="Rendering mode:", bg="white").place(x=30, y=310)
            modevalues = (
                "isosurface (default)",
                "composite",
                "maximum proj",
                "lego",
                "slicer",
                "slicer2d",
            )
            self.modeCB = Combobox(self,
                                   state="readonly",
                                   values=modevalues,
                                   width=20)
            self.modeCB.current(0)
            self.modeCB.place(x=160, y=310)

            Label(self, text="Spacing factors:", bg="white").place(x=30, y=335)
            self.xspacingCB = Entry(self, textvariable=self.xspacing, width=3)
            self.xspacing.set('1.0')
            self.xspacingCB.place(x=160, y=335)
            self.yspacingCB = Entry(self, textvariable=self.yspacing, width=3)
            self.yspacing.set('1.0')
            self.yspacingCB.place(x=210, y=335)
            self.zspacingCB = Entry(self, textvariable=self.zspacing, width=3)
            self.zspacing.set('1.0')
            self.zspacingCB.place(x=260, y=335)

            ############## options
            Frame(root, height=1, width=398, bg="grey").place(x=1, y=370)
            Label(self,
                  text="Options",
                  fg='white',
                  bg="brown",
                  font=("Courier 11 bold")).place(x=20, y=375)

            # backgr color
            Label(self, text="Background color:", bg="white").place(x=30,
                                                                    y=405)
            bgcolvalues = ("white", "lightyellow", "azure", "blackboard",
                           "black")
            self.bgcolorCB = Combobox(self,
                                      state="readonly",
                                      values=bgcolvalues,
                                      width=9)
            self.bgcolorCB.current(3)
            self.bgcolorCB.place(x=160, y=405)
            # backgr color gradient
            self.backgroundGradCB = Checkbutton(self,
                                                text="gradient",
                                                variable=self.background_grad,
                                                bg="white")
            self.backgroundGradCB.place(x=255, y=405)

            ################ render button
            Frame(root, height=1, width=398, bg="grey").place(x=1, y=437)
            Button(self, text="Render", command=self._run,
                   width=15).place(x=115, y=454)

        def _importCMD(self):
            ftypes = [
                ("All files", "*"),
                ("VTK files", "*.vtk"),
                ("VTK files", "*.vtp"),
                ("VTK files", "*.vts"),
                ("VTK files", "*.vtu"),
                ("Surface Mesh", "*.ply"),
                ("Surface Mesh", "*.obj"),
                ("Surface Mesh", "*.stl"),
                ("Surface Mesh", "*.off"),
                ("Surface Mesh", "*.facet"),
                ("Volume files", "*.tif"),
                ("Volume files", "*.slc"),
                ("Volume files", "*.vti"),
                ("Volume files", "*.mhd"),
                ("Volume files", "*.nrrd"),
                ("Volume files", "*.nii"),
                ("Volume files", "*.dem"),
                ("Picture files", "*.png"),
                ("Picture files", "*.jpg"),
                ("Picture files", "*.bmp"),
                ("Picture files", "*.gif"),
                ("Picture files", "*.jpeg"),
                ("Geojson files", "*.geojson"),
                ("DOLFIN files", "*.xml.gz"),
                ("DOLFIN files", "*.xml"),
                ("DOLFIN files", "*.xdmf"),
                ("Neutral mesh", "*.neu*"),
                ("GMESH", "*.gmsh"),
                ("Point Cloud", "*.pcd"),
                ("3DS", "*.3ds"),
                ("Numpy scene file", "*.npy"),
                ("Numpy scene file", "*.npz"),
            ]
            self.filenames = tkFileDialog.askopenfilenames(parent=root,
                                                           filetypes=ftypes)
            args.files = list(self.filenames)

        def _run(self):

            tips()

            args.files = list(self.filenames)
            if self.colorCB.get() == "by scalar":
                args.color = None
            else:
                if self.colorCB.get() == 'red':
                    args.color = 'crimson'
                elif self.colorCB.get() == 'green':
                    args.color = 'limegreen'
                elif self.colorCB.get() == 'blue':
                    args.color = 'darkcyan'
                else:
                    args.color = self.colorCB.get()

            args.alpha = self.alphaCB.get()

            args.wireframe = False
            args.showedges = False
            args.point_size = 0
            if self.surfmodeCB.get() == 'point cloud':
                args.point_size = 2
            elif self.surfmodeCB.get() == 'wireframe':
                args.wireframe = True
            elif self.surfmodeCB.get() == 'surf. & edges':
                args.showedges = True
            else:
                pass  # normal surface mode

            args.lighting = self.lightCB.get()
            args.flat = self.flat.get()

            args.no_camera_share = self.noshare.get()
            args.background = self.bgcolorCB.get()

            args.background_grad = None
            if self.background_grad.get():
                b = getColor(args.background)
                args.background_grad = (b[0] / 1.8, b[1] / 1.8, b[2] / 1.8)

            args.multirenderer_mode = False
            args.scrolling_mode = False
            if self.schememodeCB.get() == "n sync-ed renderers":
                args.multirenderer_mode = True
            elif self.schememodeCB.get() == "mesh browser":
                args.scrolling_mode = True

            args.ray_cast_mode = False
            args.lego = False
            args.slicer = False
            args.slicer2d = False
            args.lego = False
            args.mode = 0
            if self.modeCB.get() == "composite":
                args.ray_cast_mode = True
                args.mode = 0
            elif self.modeCB.get() == "maximum proj":
                args.ray_cast_mode = True
                args.mode = 1
            elif self.modeCB.get() == "slicer":
                args.slicer = True
            elif self.modeCB.get() == "slicer2d":
                args.slicer2d = True
            elif self.modeCB.get() == "lego":
                args.lego = True

            args.x_spacing = 1
            args.y_spacing = 1
            args.z_spacing = 1
            if self.xspacing.get() != '1.0':
                args.x_spacing = float(self.xspacing.get())
            if self.yspacing.get() != '1.0':
                args.y_spacing = float(self.yspacing.get())
            if self.zspacing.get() != '1.0':
                args.z_spacing = float(self.zspacing.get())

            draw_scene(args)
            if os.name == "nt":
                exit()
            if settings.plotter_instance:
                settings.plotter_instance.close()
Exemple #27
0
    Image.open(
        "C:/Users/Kaito Yamada/Documents/GitHub/nanigasi/library/GUI/Tkinter/imagefile/image2.png"
    ))
glabel = Label(root, image=image)
glabel.place(x=5, y=50, width=100, height=100)

entry = Entry(root)
entry.place(x=5, y=160, width=100, height=30)
entry.insert(tkinter.END, "entry")
print("entry=" + entry.get())

bv = tkinter.BooleanVar()
bv.set(True)
checkbtn = Checkbutton(root, text="checkbutton", variable=bv)
checkbtn.place(x=5, y=205, width=100, height=30)

print("checkbtn=" + str(bv.get()))

scale = Scale(root, orient="horizontal")
scale.place(x=205, y=5, width=100, height=50)
scale.set(30)
print(scale.get())

scrolledtext = ScrolledText(root, state="normal")
scrolledtext.place(x=205, y=75, width=200, height=100)

scrolledtext.insert(tkinter.END, "scrolled text")
print(scrolledtext.get("1.0", "1.2"))

root.mainloop()
Exemple #28
0
class PianoGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, bg="white")
        self.parent = parent
        self.filename = 'test_timetravel.xml'
        self.Rcb = BooleanVar()
        self.Lcb = BooleanVar()
        self.RightHandBeam = 0
        self.LeftHandBeam = 1
        self.initUI()

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

        importButton = Button(self,
                              text="Import Score",
                              command=self.importCMD)
        importButton.place(x=115, y=15)

        hlab = Label(self, text="Hand Size:", bg="white")
        hlab.place(x=40, y=67)
        hvalues = ('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL')
        self.handsize = Combobox(self,
                                 state="readonly",
                                 values=hvalues,
                                 width=4)
        self.handsize.current(2)
        self.handsize.place(x=115, y=65)

        Rcb = Checkbutton(self, text="R", variable=self.Rcb, bg="white")
        Rcb.select()
        Rcb.place(x=220, y=65)

        Lcb = Checkbutton(self, text="L", variable=self.Lcb, bg="white")
        Lcb.select()
        Lcb.place(x=180, y=65)

        genButton = Button(self, text="GENERATE", command=self.generateCMD)
        genButton.place(x=300, y=20)

        museButton = Button(self, text="Musescore", command=self.musescoreCMD)
        museButton.place(x=300, y=70)

        vpButton = Button(self, text="3D Player", command=self.vpCMD)
        vpButton.place(x=300, y=120)

        closeButton = Button(self, text="Close", command=self.quit)
        closeButton.place(x=300, y=170)

        self.meas = Scale(self,
                          from_=5,
                          to=200,
                          bg='white',
                          length=120,
                          orient='horizontal')
        self.meas.set(100)
        self.meas.place(x=130, y=110)
        melab = Label(self, text='#max meas:', bg="white")
        melab.place(x=40, y=130)

        self.rate = Scale(self,
                          from_=10,
                          to=100,
                          bg='white',
                          length=120,
                          orient='horizontal')
        self.rate.set(100)
        self.rate.place(x=130, y=150)
        slab = Label(self, text='3D speed:', bg="white")
        slab.place(x=40, y=170)

    def importCMD(self):
        ftypes = [('XML Music files', '*.xml'), ('Midi Music files', '*.mid'),
                  ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        self.filename = dlg.show()
        print('Input File is ', self.filename)

    def generateCMD(self):
        sf = converter.parse(self.filename)

        if self.Rcb.get():
            self.rh = Hand("right", self.handsize.get())
            self.rh.noteseq = scorereader.reader(sf, beam=self.RightHandBeam)
            self.rh.generateFingering(nmeasures=self.meas.get())

        if self.Lcb.get():
            self.lh = Hand("left", self.handsize.get())
            self.lh.noteseq = scorereader.reader(sf, beam=self.LeftHandBeam)
            self.lh.generateFingering(nmeasures=self.meas.get())

        print("Saving score to output.xml")
        sf.write('xml', fp='output.xml')
        print("\nTo visualize score type:\n musescore output.xml\n")

    def vpCMD(self):
        print('try import vkeyboard')
        import vkeyboard
        vk = vkeyboard.VirtualKeyboard()
        if self.Rcb.get(): vk.build_RH(self.rh)
        if self.Lcb.get(): vk.build_LH(self.lh)
        vk.rate = self.rate.get()
        vk.playsounds = 1
        vk.playKeyboard()

    def musescoreCMD(self):
        print('try opening musescore')
        os.system('musescore output.xml')
Exemple #29
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)
Exemple #30
0
                                                                         y=225)

    # 使用说明
    Button(top, text="使用说明", command=create, width=10,
           bg="sky blue").place(x=20, y=360)

    # 音量
    w1 = Scale(top,
               from_=0,
               to=100,
               orient="horizontal",
               length=75,
               variable=v,
               command=printScale,
               label="音量")
    w1.place(x=240, y=145)

    #进度条
    c1 = Scale(top,
               from_=0,
               to=100,
               orient="horizontal",
               length=200,
               repeatinterval=1000,
               variable=v1,
               command=jdScale,
               label="进度")
    c1.place(x=110, y=275)
    # tt = threading.Thread(target=gdScale())
    # tt.start()
    # while True: