leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

python with gui buttons

Mon Nov 24, 2014 8:22 am

hey guys,

i am trying my hardest to make a gui using python and pygame. So far i can only get one screen up and viewable called screen3 in my sript, but when i put screen2 below the code of screen3 it overwrites the first screen. what im after is press a png image (what to be a clickable button) then goes to another screen with other icons on it.

please see by the last coding that works that this is just one screen. how do i add other screens and make the icons turn into clickable buttons (like under the image)

if some one could help me with the code side like an example or unless someone is bored and could write abit of code added on and i can then see the patterns i will need to use.

Code: Select all

#! /usr/bin/env python
import pygame, sys
from pygame.locals import *

pygame.init()

screen3 = pygame.display.set_mode((320,240)) #screen size

white = 255,255,255 #colour of screen

override = pygame.image.load("icons/override.png")# button images
users = pygame.image.load("icons/users.png")
changepin = pygame.image.load("icons/changepin.png")
settings = pygame.image.load("icons/settings.png")

screen3.fill(white)
screen3.blit(override,(5,10))# button position
screen3.blit(users,(165,10))
screen3.blit(changepin,(5,120))
screen3.blit(settings,(165,120))

pygame.display.flip()

while True : #main loop
	for event in pygame.event.get() :
		if event.type == QUIT :
			pygame.quit()
			sys.exit()
	pygame.display.update()


User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: python with gui buttons

Mon Nov 24, 2014 9:10 am

I think you only have one screen/surface to use in pygame. What you can then do is have a variable to set which is the active screen in your code and then just draw this to the surface.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Mon Nov 24, 2014 10:04 am

yes this is what im after but havent got a clue how to write it out in code. please could someone help me achieve this goal,

main underlay screen

then screen1 = 4 images, blit location and 4 buttons
screen 2 = 2 images, blit location and 1 button
screen3 = etc etc.

im not to sure where to put this detail as i tried outside the loop and it just overwrites to the last screen

i would be very grateful if someone could take the their time :)

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Mon Nov 24, 2014 11:02 am

Have a look at LapsePiTouch at https://github.com/climberhunt/LapsePiTouch

Gr.
Dirk.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Mon Nov 24, 2014 11:14 am

that is the code that i have been trying to figure out but i can not understand it fully.

i can see on that he has icons and buttons outside the mainloop but its setting up the main under screen im confused about.

i have tried to run his script but doesnt work as i havent got the motors, so tried cutting them out but i still fail :(

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Mon Nov 24, 2014 12:19 pm

i have tried to run his script but doesnt work as i havent got the motors, so tried cutting them out but i still fail
I can run the script with just the PiTFT screen connected, no motors connected.

https://github.com/adafruit/adafruit-pi-cam uses the same method, but it depends on the picamera module.

What I would do is log in using SSH, and add some diagnostic print statements in areas you have a problem understanding.
Start the script from the command line and you should see the print output on the SSH terminal (there is already some diagnostic output anyway)
The graphical output will go to the physical screen as usual.

Gr.
Dirk.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Mon Nov 24, 2014 12:46 pm

i havent got a tft screen, i have the usb touchscreen. but still thought i would be able to view it as a working program in the lx terminal and another window pops up. like my code does

isnt a button function all the same ? in thats guys code its between line 60 and 111 but still cant get it to work as i want.

why is it so hard to make a button ?

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Mon Nov 24, 2014 1:07 pm

leejohnson wrote:i havent got a tft screen, i have the usb touchscreen. but still thought i would be able to view it as a working program in the lx terminal and another window pops up. like my code does
The 2 example scripts I gave are set up to write to a specific framebuffer device and not to a window on the desktop (check out the 'os.putenv' calls).
That's why these scripts don't work for you.
Maybe it works if you comment out the 4 os.putenv calls.
isnt a button function all the same ? in thats guys code its between line 60 and 111 but still cant get it to work as i want.
So have you copied the Buttons class and set up the button definitions (line 295).
Then in the main loop you catch a mouse down event, use the Button class to see which button is hit and act on that.
This should work almost unaltered from the example code...

Gr.
Dirk.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Mon Nov 24, 2014 1:19 pm

i will try and take out the os.4 and run again tonight.

yes i included the line 295 aswell first to copy what has been done before.

as for the mouse button doewn coooment, that part is in the main loop line 425, but does say #process touchscreen input, will thing still work doesnt look anything special to the touch screen just mouse position and click

thank you for your help, no doubt ill be back on again tonight as i dont think ill be hopeful but want to learn

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Mon Nov 24, 2014 1:30 pm

leejohnson wrote:as for the mouse button doewn coooment, that part is in the main loop line 425, but does say #process touchscreen input, will thing still work doesnt look anything special to the touch screen just mouse position and click
With something like this I would create a skeleton program, with some debug output (can be print statements) to see what happens.
Apart from some screen setup code it would look something like this:

Code: Select all

  while True:
    for event in pygame.event.get():
      if(event.type is MOUSEBUTTONDOWN):
        pos = pygame.mouse.get_pos()
        print pos   # not 100% sure if this is correct
Gr.
Dirk.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Tue Nov 25, 2014 11:14 am

tried striping the code and running again no luck :(

dirk if you have time you have more knowledge than me are you able to pin up the code you have succussfully done to achieve a screen gui on the computer then i can see where im going wrong.

all i need is a button function under the image to click on to the next screen with icons on it? sorry to be a pain but really struggling

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Tue Nov 25, 2014 2:09 pm

leejohnson wrote: dirk if you have time you have more knowledge than me are you able to pin up the code you have succussfully done to achieve a screen gui on the computer then i can see where im going wrong.
Don't know about more knowledge ;)
Trying to get to grips with pygame myself to get some stuff working for my PiTFT screen. I'll see if I can whip up something.

Gr.
Dirk.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: python with gui buttons

Tue Nov 25, 2014 4:20 pm

I did it a slightly different way for one of my projects. I made a modular system where different screens could just be added or removed by adding folders to the project, rather than hard-wiring the code. This runs with a PiTFT screen. Touching the screen changes the display to the next plugin. However, this feels like overkill for your needs.

A while ago I helped someone pull together a multi-screen script for remote controlling XBMC. It used some existing classes to create menus (although Google has so far failed me on this). The layout is slightly rigid but it is flexible in that you can add more screens as necessary.

I'll see if I've still got the code lying around later tonight.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

DirkS
Posts: 10362
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: python with gui buttons

Tue Nov 25, 2014 6:56 pm

A bit of a botch job, but it does show one way of displaying different screens.
I'm sure that 'elP' can come up with something better :)

I think I prefer to use classes (not a new concept for me). For my piTFT programs I will probably use a modified version of the LapsePiTouch script.

Code: Select all

#! /usr/bin/env python
import pygame, sys
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((320,240)) #screen size

white = 255,255,255 #colour of screen

iconleft = pygame.image.load("left.png")
iconright = pygame.image.load("right.png")
iconstop = pygame.image.load("stop.png")

buttons = [
  ({'id':'right', 'rect':(255,180,60, 60), 'icon':iconright},
   {'id':'stop', 'rect':(100,180, 120, 60), 'icon':iconstop}),

  ({'id':'left', 'rect':(5, 180, 60, 60), 'icon':iconleft},
   {'id':'stop', 'rect':(100,180, 120, 60), 'icon':iconstop}),
]

def selected(rect, pos):
  # print 'now in selected'
  x1 = rect[0]
  y1 = rect[1]
  x2 = x1 + rect[2] - 1
  y2 = y1 + rect[3] - 1
  if ((pos[0] >= x1) and (pos[0] <= x2) and
      (pos[1] >= y1) and (pos[1] <= y2)):
    return True
  return False

def drawbuttons(sm):
    for b in buttons[sm]:
        screen.blit(b['icon'], (b['rect'][0], b['rect'][1]))

screenModePrior = -1
screenMode = 0

while True : #main loop

    screen.fill(0)
    drawbuttons(screenMode)
             
    if screenMode == 1:
        # print / draw additional stuff
        myfont = pygame.font.SysFont("Arial", 30)
        label = myfont.render("Screen 1" , 1, (255,255,255))
        screen.blit(label, (10, 10))
       
    if screenMode == 0:
        myfont = pygame.font.SysFont("Arial", 30)
        label = myfont.render("Screen 0" , 1, (255,255,255))
        screen.blit(label, (10, 10))
        
    pygame.display.update()
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
              pygame,quit()
            elif(event.type is MOUSEBUTTONDOWN):
              # print 'mouse down'
              pos = pygame.mouse.get_pos()
              for b in buttons[screenMode]:
                if selected(b['rect'], pos):
                    if b['id'] == 'left': screenMode -= 1
                    elif b['id'] == 'right': screenMode +=1
                    elif b['id'] == 'stop':
                        print('Goodbye')
                        pygame.quit()
                        sys.exit()
                    # print screenMode
                    break

        if screenMode >= 0 or screenMode != screenModePrior: break
        
    screenModePrior = screenMode

BTW: I 'borrwed' code (and some icons) from David Hunt's LapsePiTouch script (https://github.com/climberhunt/LapsePiTouch)

Gr.
Dirk.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: python with gui buttons

Tue Nov 25, 2014 8:21 pm

Dirk,

Nothing wrong with a botch job! Always good to look for a simple solution wherever possible.

The menu class I adapted was this one: http://www.pygame.org/project-MenuClass-1260-.html We needed to use this because the number of screens was variable and couldn't be hardcoded.

I'd start with the simplest idea first and see if it can be adapted for your needs. If not, have a look at the menu class and I'll help out if I can.

elP
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

leejohnson
Posts: 43
Joined: Sun Sep 28, 2014 7:01 pm

Re: python with gui buttons

Wed Nov 26, 2014 1:54 pm

thank you guys for your help on this,

last night i used the lapse code to create a screen mode and works :) however i havent created the button functions yet but your code example i can can make alot more sense then the lapse script. so hopefully try a similar approach to this

thank you for your help on this, no doubt it wont be my last question haha!!!

Return to “Python”