dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

GUI in Python

Wed Aug 20, 2014 11:25 am

Hi!

I've been working in a project with my RPi. I've created a radio wifi that permits you to select between different countries playlist and you can control it with buttons and see it in a lcd. All is programmed in python and the python script is started when the RPi switches on.

I would like to create a easy gui that allows you to choose in a simple graphical user interface which country playlist you prefer while you can do it with the buttons too. Therefore the only thing that the gui has to do is to choose which function of the python script loads, because when I choose one playlist my programme loads its function and the music starts. My RPi is running Raspbian. I've seen that Tkinter can be a great option.

Please, anyone can help me with any tutorial or example? Because I have no idea how to do it.

Sorry for my English because I'm Spanish.

Thanks.

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: GUI

Wed Aug 20, 2014 11:39 am

Have you looked at https://wiki.python.org/moin/TkInter yet :?:

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Wed Aug 20, 2014 11:44 am

AndrewS wrote:Have you looked at https://wiki.python.org/moin/TkInter yet :?:
Thanks. I'll see it. One more question, is possible to do what I want with Tkinter?

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: GUI

Wed Aug 20, 2014 11:56 am

dan11 wrote:One more question, is possible to do what I want with Tkinter?
I can't see any reason why it wouldn't - it's just a generic GUI library used by hundreds of other Python projects...

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Mon Aug 25, 2014 8:41 pm

I need some help please.

Finally I've decided to do it like a pygame. My project uses the script of python of Sheldon:

http://usualpanic.com/2013/05/raspberry ... net-radio/

Now I want to control it at the same time with the lcd or with the gui. I've created a code that shows a photo of the lcd and depending of which button you clik in the photo it will do one thing or another. But I dont know how to do that in the code after of each condition:

Code: Select all

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# Módulos
import sys, pygame
from pygame.locals import *
from WifiRadioV4 import *
# Constantes
WIDTH = 493
HEIGHT = 300
  
# Funciones
# ---------------------------------------------------------------------
def load_image(filename, transparent=False):
        try: image = pygame.image.load(filename)
        except pygame.error, message:
                raise SystemExit, message
        image = image.convert()
        if transparent:
                color = image.get_at((0,0))
                image.set_colorkey(color, RLEACCEL)
        return image
# ---------------------------------------------------------------------

def main():
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Raspberry Pi Radio Wifi")
 
    background_image = load_image('fondo.jpg')
 
    while True:
        for eventos in pygame.event.get():
            if eventos.type == QUIT:
                sys.exit(0)
            elif eventos.type == pygame.MOUSEBUTTONDOWN:
	              x, y = eventos.pos

                if 283<=x<=307  and 238<=y<=264:
                        print "Select "
                       ¿Function?
		            elif 338<=x<=363  and 239<=y<=265:
                        print "Left"
                        ¿Function?
		            elif 391<=x<=416  and 223<=y<=247:
                         print "Up "
                        ¿Function?
		            elif 392<=x<=418  and 260<=y<=287:
                        print "Down "
                       ¿Function?
		            elif 445<=x<=468  and 242<=y<=268:
                        print "Right"
                        ¿Function?
			
        screen.blit(background_image, (0, 0))
        pygame.display.flip()
    return 0
 
if __name__ == '__main__':
    pygame.init()
    main()
Any help please?

Another issue is that when I run the pygame with the other script running in the RPi is too busy and the lcd shows nothing although I can change the radios and the volume with the buttons but I dont see anything in the lcd.

Thanks

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: GUI

Mon Aug 25, 2014 10:04 pm

dan11 wrote:I need some help please.

Finally I've decided to do it like a pygame. My project uses the script of python of Sheldon:

http://usualpanic.com/2013/05/raspberry ... net-radio/

Now I want to control it at the same time with the lcd or with the gui. I've created a code that shows a photo of the lcd and depending of which button you clik in the photo it will do one thing or another. But I dont know how to do that in the code after of each condition.
Shouldn't you just put the function calls in the places marked with "¿Function?"? So, write the functionality that you want in function definitions (after the load_image funtion), and then call them from the main loop. The "¿Function?" placeholders shows where to place the calls.
dan11 wrote: Another issue is that when I run the pygame with the other script running in the RPi is too busy and the lcd shows nothing although I can change the radios and the volume with the buttons but I dont see anything in the lcd.
The script will run as fast as it can, taking all cpu resources that the operating system gives it. The program consists of a loop that runs again and again, checking if it gets some input and updating the screen. You have to make it pause for a few milliseconds during every round. The usual way in Python is to use the sleep() function from the module time but pygame has a similar function included that is probaly preferable to use. With pygame.time.Clock() you can create a clock object:

Code: Select all

clock = pygame.time.Clock()
Do that before entering the loop. Then at the very end of the loop, under the line pygame.display.flip(), call the clock objects method tick():

Code: Select all

clock.tick(30)
The number is the framerate that you want. Smaller numbers conserve cpu cycles but also increase the latency of input.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Tue Aug 26, 2014 7:39 am

Thanks for your reply Sleep.

I know where I have to put the calls of the functions what I don't know exactly is what I've to write inside each function to achieve that clicking in the image will be the same that pushing the button on the lcd. Any help please? Because the function used only reads the state of the buttons but I don't know how I can set this state manually.

I will try all later, thanks very much.

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: GUI

Tue Aug 26, 2014 10:57 am

dan11 wrote:Because the function used only reads the state of the buttons but I don't know how I can set this state manually.
You don't "manually set the button state". Instead you need to separate out the code that actually "does something" from your button-press-detecting function, and put that in a separate function. And then in both your "button press" and "mouse click" detection functions, simply call your "action function"...
Last edited by AndrewS on Tue Aug 26, 2014 12:13 pm, edited 1 time in total.

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: GUI

Tue Aug 26, 2014 12:10 pm

dan11 wrote:Thanks for your reply Sleep.

I know where I have to put the calls of the functions what I don't know exactly is what I've to write inside each function to achieve that clicking in the image will be the same that pushing the button on the lcd. Any help please? Because the function used only reads the state of the buttons but I don't know how I can set this state manually.

I will try all later, thanks very much.
The structure of Sheldon Hartling's program and the structure of the Pygame GUI program are the same, so it should be quite straightforward to combine them into one program.

Both have a main function that first sets up things and then goes into an event loop that reads the user input and does actions accordingly. Hartling's code reads the button press with "press = read_buttons()" and then according to the input it executes an action - e.g. changes the value of a variable and then calls a function. The Pygame GUI reads the mouse coordinates when the mouse is clicked and according to them can change the value of a variable or call a function. Your program's main loop should have both event loops combined into one loop

If you want the same action from a mouse click in the GUI as from a button press, just copy the code from one place to another. If you want new functionality, you have to write new functions that does what you want to do, and then call them from the event loop.

Hartling's code already has an "delay_milliseconds(99)" to slow down the loop in the same way the clock.tick() call does in Pygame. The tick() is better if consistency of the frame rate is important.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Wed Aug 27, 2014 8:48 am

Thanks for your answers, the gui is working.

The clock object solved the issue and I've attached the gui code into the radio code and now all is running.

Thanks very much.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Thu Sep 04, 2014 10:23 am

Hi guys! I need some help again.

If I run my program since terminal I dont have any problem all is working perfectly.

But now I want to start automatically my script when I turn on my RPi, I have done it. But when I do it the pygame starts and I see the image of my LCD but RPi is very busy and the mouse moves very slow however if I run it since termial all is ok.

I've followed this tutorial to start my RPi with a script:

http://www.raspberrypi-spanish.es/foro/ ... f=5&t=7338

What can I do?

Thanks

BMS Doug
Posts: 3823
Joined: Thu Mar 27, 2014 2:42 pm
Location: London, UK

Re: GUI

Fri Sep 05, 2014 10:34 am

Hi Dan,

I think you will need to post a link to your script before anyone can diagnose the issue for you.
Doug.
Building Management Systems Engineer.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Sat Sep 06, 2014 10:56 am

I solved the issue. I did this:

• Create the folder home/pi/.config/lxsession/LXDE

• In this folder put a file named autostart containing one line specifying the full path of the file to be executed:

e.g. python /home/pi/pipresents/pipresents.py <options>

• Make the autostart file executable by using the properties menu in the File Manager to alter the permissions on the file.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Mon Sep 08, 2014 10:05 am

Hi guys! I want to improve my gui.

I would like to show the same messages that are shown in my LCD in my gui.

How I could do it? Any idea?

Thanks

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: GUI

Mon Sep 08, 2014 11:30 am

Here is a small sample program of writing text to the display:

Code: Select all

import pygame, sys

WINDOWWIDTH = 620 
WINDOWHEIGHT = 480
FONT_SIZE = 50
FONT_COLOR = (255,255,255)
BG_COLOR = (0,0,0)
POSITION =  (int(WINDOWWIDTH/2.0), int(WINDOWHEIGHT/2.0))

pygame.init()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
fontObject = pygame.font.SysFont('dejavusans', FONT_SIZE)
frame_number = 0
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_ESCAPE:
				pygame.quit()
				sys.exit()
	frame_number = frame_number + 1
	textSurfaceObj = fontObject.render(str(frame_number), True, FONT_COLOR)
	textRectObj = textSurfaceObj.get_rect()
	textRectObj.center = POSITION
	pygame.draw.rect(screen, BG_COLOR, textRectObj)
	screen.blit(textSurfaceObj, textRectObj)
	pygame.display.update([textRectObj])

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Mon Sep 08, 2014 11:35 am

Sleep Mode zZ wrote:Here is a small sample program of writing text to the display:

Code: Select all

import pygame, sys

WINDOWWIDTH = 620 
WINDOWHEIGHT = 480
FONT_SIZE = 50
FONT_COLOR = (255,255,255)
BG_COLOR = (0,0,0)
POSITION =  (int(WINDOWWIDTH/2.0), int(WINDOWHEIGHT/2.0))

pygame.init()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
fontObject = pygame.font.SysFont('dejavusans', FONT_SIZE)
frame_number = 0
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_ESCAPE:
				pygame.quit()
				sys.exit()
	frame_number = frame_number + 1
	textSurfaceObj = fontObject.render(str(frame_number), True, FONT_COLOR)
	textRectObj = textSurfaceObj.get_rect()
	textRectObj.center = POSITION
	pygame.draw.rect(screen, BG_COLOR, textRectObj)
	screen.blit(textSurfaceObj, textRectObj)
	pygame.display.update([textRectObj])
Thanks.

But is there any way to catch the content of the queue of my python script and then show it or I have to write each part of text manually?

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: GUI

Mon Sep 08, 2014 11:54 am

I'm not quite sure what you are asking. You can render any string to a surface and then blit it into the screen. In the example program it is a int typed variable (frame_number) that is changed to a string and then rendered. If you have the content of your queue in strings (or something that can be transformed to strings), you can display it on the pygame screen. For more spesific instructions I would have to see your program and understand what content you want to display on the screen.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Mon Sep 08, 2014 11:59 am

Here is my code:

Code: Select all

# -*- encoding: utf-8 -*-
#!/usr/bin/python


# IMPORTAMOS MÓDULOS
from Adafruit_I2C          import Adafruit_I2C
from Adafruit_MCP230xx     import Adafruit_MCP230XX
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from datetime              import datetime
from subprocess            import *
from time                  import sleep, strftime
from Queue                 import Queue
from threading             import Thread

import os
import glob
import sys, pygame
from pygame.locals import *

# CONSTANTES IMAGEN
WIDTH = 493
HEIGHT = 300

# INICIALIZAMOS PLACA LCD
LCD = Adafruit_CharLCDPlate()

# DEFINIMOS VARIABLES GLOBALES
PLAYLIST_MSG   = []
STATION        = 1
NUM_STATIONS   = 0

# BOTONES
NONE           = 0x00
SELECT         = 0x01
RIGHT          = 0x02
DOWN           = 0x04
UP             = 0x08
LEFT           = 0x10
UP_AND_DOWN    = 0x0C
LEFT_AND_RIGHT = 0x12

# QUEUE
LCD_QUEUE = Queue()

#FUNCION IMAGEN
def load_image(filename, transparent=False):
        try: image = pygame.image.load(filename)
        except pygame.error, message:
                raise SystemExit, message
        image = image.convert()
        if transparent:
                color = image.get_at((0,0))
                image.set_colorkey(color, RLEACCEL)
        return image



# WORKER THREAD

def update_lcd(q):
   
   while True:
      msg = q.get()
      while not q.empty():
         q.task_done()
         msg = q.get()
      LCD.setCursor(0,0)
      LCD.message(msg)
      q.task_done()
   return


# MAIN 

def main():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Paramos reproductor
   output = run_cmd("mpc stop" )

   # Configuración AdaFruit LCD Plate
   LCD.begin(16,2)
   LCD.clear()
   LCD.backlight(LCD.ON)

   # Creamos el worker thread y lo hacemos una herramienta
   worker = Thread(target=update_lcd, args=(LCD_QUEUE,))
   worker.setDaemon(True)
   worker.start()
   
   # Mensaje inicial
   LCD_QUEUE.put('Bienvenido a\nRPi Radio Wifi', True)

   # Cargamos la playlist
   load_playlist_spain()
   sleep(2)
   LCD.clear()

   screen = pygame.display.set_mode((WIDTH, HEIGHT))
   pygame.display.set_caption("Raspberry Pi Radio Wifi")

   clock = pygame.time.Clock()
    
   background_image = load_image('fondo.jpg')
   
# INICIAMOS LA MÚSICA

   # Iniciamos el reproductor
   LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
   run_cmd("mpc volume +100")
   mpc_play(STATION)
   countdown_to_play = 0
      
   
   while True:
      press = read_buttons()
      for eventos in pygame.event.get():
            if eventos.type == QUIT:
                sys.exit(0)
            elif eventos.type == pygame.MOUSEBUTTONDOWN:
	        x, y = eventos.pos

                if 283<=x<=307  and 238<=y<=264:
                        press=SELECT
		elif 338<=x<=363  and 239<=y<=265:
                        press = LEFT
	        elif 391<=x<=416  and 223<=y<=247:
                        press=UP
	        elif 392<=x<=418  and 260<=y<=287:
                        press=DOWN
	        elif 445<=x<=468  and 242<=y<=268:
                        press = RIGHT 


      # Pulsamos botón izquierdo
      if(press == LEFT):
         STATION -= 1
         if(STATION < 1):
            STATION = NUM_STATIONS
         LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
         countdown_to_play = 3

      # Pulsamos botón derecho
      if(press == RIGHT):
         STATION += 1
         if(STATION > NUM_STATIONS):
            STATION = 1
         LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
         countdown_to_play = 3

      # Pulsamos botón de arriba
      if(press == UP):
         output = run_cmd("mpc volume +2")

      # Pulsamos botón de abajo
      if(press == DOWN):
         output = run_cmd("mpc volume -2")

      # Pulsamos botón select
      if(press == SELECT):
         menu_pressed()

      if(countdown_to_play > 0):
         countdown_to_play -= 1
         if(countdown_to_play == 0):
            mpc_play(STATION)

      screen.blit(background_image, (0, 0))
      pygame.display.flip()
      clock.tick(3)
   update_lcd.join()
   return 0
   
# LECTURA BOTONES PULSADOS

def read_buttons():

   buttons = LCD.buttons()
   if(buttons != 0):
      while(LCD.buttons() != 0):
         delay_milliseconds(1)
   return buttons

# TIEMPO DE DELAY EN MILISEGUNDOS

def delay_milliseconds(milliseconds):
   seconds = milliseconds / float(1000)	
   sleep(seconds)


# CARGAMOS DIFERENTES PLAYLIST

def load_playlist_spain():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Añadimos todas las emisoras a la playlist
   output = run_cmd("mpc clear")
   output = run_cmd("/home/pi/Python-WiFi-Radio/spain.sh")

   # Cargamos playlist en PLAYLIST_MSG
   PLAYLIST_MSG = []
   with open ("/home/pi/Python-WiFi-Radio/spain.sh", "r") as playlist:
      # Salta primera línea de la playlist 
      for line in playlist:
         if line[0:1] != '#!':  
               break
      # Carga las siguientes líneas
      for line in playlist:
         if line[0] == "#" :
            PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + "                ")
   playlist.close()
   NUM_STATIONS = len(PLAYLIST_MSG)

def load_playlist_france():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Añadimos todas las emisoras a la playlist
   output = run_cmd("mpc clear")
   output = run_cmd("/home/pi/Python-WiFi-Radio/france.sh")

   # Cargamos playlist en PLAYLIST_MSG
   PLAYLIST_MSG = []
   with open ("/home/pi/Python-WiFi-Radio/france.sh", "r") as playlist:
      # Salta primera línea de la playlist 
      for line in playlist:
         if line[0:1] != '#!':  
               break
      # Carga las siguientes líneas
      for line in playlist:
         if line[0] == "#" :
            PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + "                ")
   playlist.close()
   NUM_STATIONS = len(PLAYLIST_MSG)

def load_playlist_germany():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Añadimos todas las emisoras a la playlist
   output = run_cmd("mpc clear")
   output = run_cmd("/home/pi/Python-WiFi-Radio/germany.sh")

   # Cargamos playlist en PLAYLIST_MSG
   PLAYLIST_MSG = []
   with open ("/home/pi/Python-WiFi-Radio/germany.sh", "r") as playlist:
      # Salta primera línea de la playlist 
      for line in playlist:
         if line[0:1] != '#!':  
               break
      # Carga las siguientes líneas
      for line in playlist:
         if line[0] == "#" :
            PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + "                ")
   playlist.close()
   NUM_STATIONS = len(PLAYLIST_MSG)

def load_playlist_italy():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Añadimos todas las emisoras a la playlist
   output = run_cmd("mpc clear")
   output = run_cmd("/home/pi/Python-WiFi-Radio/italy.sh")

   # Cargamos playlist en PLAYLIST_MSG
   PLAYLIST_MSG = []
   with open ("/home/pi/Python-WiFi-Radio/italy.sh", "r") as playlist:
      # Salta primera línea de la playlist 
      for line in playlist:
         if line[0:1] != '#!':  
               break
      # Carga las siguientes líneas
      for line in playlist:
         if line[0] == "#" :
            PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + "                ")
   playlist.close()
   NUM_STATIONS = len(PLAYLIST_MSG)

def load_playlist_united_kingdom():
   global STATION, NUM_STATIONS, PLAYLIST_MSG

   # Añadimos todas las emisoras a la playlist
   output = run_cmd("mpc clear")
   output = run_cmd("/home/pi/Python-WiFi-Radio/united_kingdom.sh")

   # Cargamos playlist en PLAYLIST_MSG
   PLAYLIST_MSG = []
   with open ("/home/pi/Python-WiFi-Radio/united_kingdom.sh", "r") as playlist:
      # Salta primera línea de la playlist 
      for line in playlist:
         if line[0:1] != '#!':  
               break
      # Carga las siguientes líneas
      for line in playlist:
         if line[0] == "#" :
            PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + "                ")
   playlist.close()
   NUM_STATIONS = len(PLAYLIST_MSG)
   
# MENÚ DE OPCIONES

def menu_pressed():
   global STATION

   MENU_LIST = [
      '1. Temperatura, \n   fecha y hora ',
      '2. Seleccionar  \n   Playlist     ',
      '3. Silenciar    \n   audio        ',
      '4. Temperatura  \n   Raspberry Pi ',
      '5. Reiniciar    \n   Raspberry Pi ',
      '6. Apagar       \n   Raspberry Pi ',
      '7. Salir del    \n   menu         ' ]
      

   item = 0
   LCD.clear()
   LCD.backlight(LCD.ON)
   LCD_QUEUE.put(MENU_LIST[item], True)

   keep_looping = True
   while (keep_looping):
   
      press = read_buttons()
      for eventos in pygame.event.get():
            if eventos.type == QUIT:
                sys.exit(0)
            elif eventos.type == pygame.MOUSEBUTTONDOWN:
	        x, y = eventos.pos

                if 283<=x<=307  and 238<=y<=264:
                        press=SELECT
		elif 338<=x<=363  and 239<=y<=265:
                        press = LEFT
	        elif 391<=x<=416  and 223<=y<=247:
                        press=UP
	        elif 392<=x<=418  and 260<=y<=287:
                        press=DOWN
	        elif 445<=x<=468  and 242<=y<=268:
                        press = RIGHT 
	  
      # Arriba
      if(press == UP):
         item -= 1
         if(item < 0):
            item = len(MENU_LIST) - 1
         LCD_QUEUE.put(MENU_LIST[item], True)

      # Abajo
      elif(press == DOWN):
         item += 1
         if(item >= len(MENU_LIST)):
            item = 0
         LCD_QUEUE.put(MENU_LIST[item], True)

      # Botón select
      elif(press == SELECT):
         keep_looping = False

         if(item == 0):
            # 1. Mostrar temperatura,fecha y hora
			date_and_time()
         elif(item == 1):
            # 2. Seleccionar playlist
                         LCD_QUEUE.put("Seleccione una  \nplaylist       ", True)
                         sleep(2)
			 MENU_LIST = [
				 '1. France       \n                ',
				 '2. Germany      \n                ',
				 '3. Italy        \n                ',
				 '4. U.Kingdom    \n                ',
                                 '5. Spain        \n                ',
				 '6. Salir menu   \n   playlist     ' ]
      
			 cont = 0
			 LCD.clear()
			 LCD.backlight(LCD.ON)
			 LCD_QUEUE.put(MENU_LIST[cont], True)
			
			 select_country = True
			 while (select_country):
				 press = read_buttons()
				 for eventos in pygame.event.get():
                                    if eventos.type == QUIT:
                                        sys.exit(0)
                                    elif eventos.type == pygame.MOUSEBUTTONDOWN:
                                        x, y = eventos.pos

                                        if 283<=x<=307  and 238<=y<=264:
                                                press=SELECT
                                        elif 338<=x<=363  and 239<=y<=265:
                                                press = LEFT
                                        elif 391<=x<=416  and 223<=y<=247:
                                                press=UP
                                        elif 392<=x<=418  and 260<=y<=287:
                                                press=DOWN
                                        elif 445<=x<=468  and 242<=y<=268:
                                                press = RIGHT 
			         # Izquierda
				 if(press == LEFT):
					 cont -= 1
					 if(cont < 0):
						 cont = len(MENU_LIST) - 1
					 LCD_QUEUE.put(MENU_LIST[cont], True)

				 # Derecha
				 elif(press == RIGHT):
			                 cont += 1
					 if(cont >= len(MENU_LIST)):
						 cont = 0
					 LCD_QUEUE.put(MENU_LIST[cont], True)
				
				 # Select
				 elif(press == SELECT):
					 select_country = False
					
					 if(cont == 0):
						 load_playlist_france()
						 sleep(2)
						 STATION = 1
						 LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
						 mpc_play(STATION)
					 elif(cont ==1):	
						 load_playlist_germany()
						 sleep(2)
						 STATION = 1
						 LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
						 mpc_play(STATION)
					 elif(cont ==2):	
						 load_playlist_italy()
						 sleep(2)
						 STATION = 1
						 LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
						 mpc_play(STATION)
					 elif(cont ==3):	
						 load_playlist_united_kingdom()
						 sleep(2)
						 STATION = 1
						 LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
						 mpc_play(STATION)
				         elif(cont ==4):	
						 load_playlist_spain()
						 sleep(2)
						 STATION = 1
						 LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
						 mpc_play(STATION)
				 else:
					 delay_milliseconds(99)
	 elif(item == 2):
            # 3. Silenciar audio
            output = run_cmd("mpc stop" )
         elif(item == 3):
            # 4. Temperatura Raspberry Pi
            temp_rpi()	   
         elif(item == 4):
            # 5. Reiniciar Raspberry Pi
            LCD_QUEUE.put('Reiniciando     \nRasbperry Pi    ', True)
            sleep(2)
            LCD_QUEUE.join()
            output = run_cmd("mpc clear")
            output = run_cmd("sudo shutdown now -r")
            LCD.clear()
            LCD.backlight(LCD.OFF)
            exit(0)
         elif(item == 5):
            # 6. Apagar Raspberry Pi
            LCD_QUEUE.put('Apagando        \nRasbperry Pi    ', True)
            sleep(2)
            LCD_QUEUE.join()
            output = run_cmd("mpc clear")
            output = run_cmd("sudo shutdown now -h")
            LCD.clear()
            LCD.backlight(LCD.OFF)
            exit(0)
      else:
         delay_milliseconds(99)

   # Restaura la pantalla
   LCD.backlight(LCD.ON)
   LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)


# TEMPERATURA,FECHA Y HORA

#Cargamos los comandos modprobe
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

#Encontramos el archivo desde donde leeremos la información
directorio = '/sys/bus/w1/devices/'
carpeta = glob.glob(directorio + '28*')[0]
archivo = carpeta + '/w1_slave'

#Esta función lee la información que obtenemos del sensonr de temperatura
def read_temp_file():
    f = open(archivo, 'r')
    lines = f.readlines()
    f.close()
    return lines

#La segunda función se asegura de obtener el mensaje YES de la primera línea
#obtenida del sensor y después devuelve los valores de temperatura leídos en
#grados centígrados
def read_temp():
    lines = read_temp_file()
    detect = 'YES'
    if detect in lines[0]:
        position = lines[1].find('t=')
        if position != -1:
            temp_cad = lines[1][position+2:]
            temp_c = float(temp_cad) / 1000.0
            return temp_c
    else:
        lines = read_temp_file()
      
def date_and_time():
        LCD.clear() 
	LCD.backlight(LCD.ON)
	i = 29
	keep_looping = True
	while (keep_looping):
                  
		#Cada medio segundo actualizar tiempo y temperatura mostrados
		i += 1
		if(i % 5 == 0):
                   date = datetime.now().strftime("%d %b %Y \nHora: %H:%M")
                   LCD_QUEUE.put(date, True)
                   delay_milliseconds(1500)
                   LCD.clear()
                   temp = read_temp()
                   LCD_QUEUE.put("Temperatura: \n"+ str(temp)+" "+ chr(223)+"C", True)
                   delay_milliseconds(1500)
                   LCD.clear()
     
		#Leemos los botones
                press = read_buttons()
                for eventos in pygame.event.get():
                    if eventos.type == QUIT:
                        sys.exit(0)
                    elif eventos.type == pygame.MOUSEBUTTONDOWN:
                        x, y = eventos.pos

                        if 283<=x<=307  and 238<=y<=264:
                                press=SELECT
                                
		if(press == SELECT):
			keep_looping = False
		
		delay_milliseconds(99)
	

# TEMPERATURA RPI
def temp_rpi():
   LCD.clear()
   tempC = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1000
   LCD_QUEUE.put("Temperatura RPi:\n"+ str(tempC)+" "+ chr(223)+"C", True)
   delay_milliseconds(3000)
   LCD.clear()


	
def run_cmd(cmd):
   p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
   output = p.communicate()[0]
   return output



def mpc_play(STATION):
   pid = Popen(["/usr/bin/mpc", "play", '%d' % ( STATION )]).pid



if __name__ == '__main__':
  main()
  pygame.init()

I want to display the content of LCD_QUEUE.put in my gui when is shown in my LCD.

Thanks very much for your reply.

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: GUI

Mon Sep 08, 2014 12:28 pm

Unfortunately I'm not familiar with these libraries at all and cannot test the program. On a quick inspection it seems that LCD_QUEUE is a queue where you put items into it with LCD_QUEUE.put and get items with LCD_QUEUE.get. If you want to display what you put into the queue, probably the best thing is to save the item that you are putting into the LCD_QUEUE at the same time into a variable, and then display the variable in the main loop. If you want to display the item when you are getting the item out of the queue, you would have to save it into a variable at that point.

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Mon Sep 08, 2014 2:17 pm

Sleep Mode zZ wrote:Unfortunately I'm not familiar with these libraries at all and cannot test the program. On a quick inspection it seems that LCD_QUEUE is a queue where you put items into it with LCD_QUEUE.put and get items with LCD_QUEUE.get. If you want to display what you put into the queue, probably the best thing is to save the item that you are putting into the LCD_QUEUE at the same time into a variable, and then display the variable in the main loop. If you want to display the item when you are getting the item out of the queue, you would have to save it into a variable at that point.
Thanks, anyone can help me please?

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: GUI

Wed Sep 10, 2014 6:21 pm

I only had a quick scan through the code, but it looks like the update_lcd() function is the one you want to modify? I guess just underneath the LCD.message(msg) you need to add a function which also displays 'msg' on screen?

dan11
Posts: 32
Joined: Wed Feb 05, 2014 10:01 am

Re: GUI

Thu Sep 11, 2014 5:44 pm

AndrewS wrote:I only had a quick scan through the code, but it looks like the update_lcd() function is the one you want to modify? I guess just underneath the LCD.message(msg) you need to add a function which also displays 'msg' on screen?
It isn't so easy. Because it is necessary to put the part of the function which displays the msg inside the main and it gets an error.

Any idea?

User avatar
AndrewS
Posts: 3625
Joined: Sun Apr 22, 2012 4:50 pm
Location: Cambridge, UK
Contact: Website

Re: GUI in Python

Fri Sep 12, 2014 1:26 pm

Maybe a quick hacky solution would be to use global variables?

Return to “Python”