Python Forum
[PyGame] Can't get button class to work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Can't get button class to work
#4
(Nov-26-2018, 04:45 PM)mzmingle Wrote: I thought it had to be in the loop to ensure it would let you close the program without crashing?
The callback function gets executed the second you press the button. Im not sure what you mean by new screen, but any result will occur after the callback is executed. You can use a flag such as your clicked value to determine if something needs to occur persistently based on the button being clicked or not, but not the button logic itself.

Here is an example using your code:
screen = pygame.display.set_mode((800,600))
done = False
def teacherChoice():
    print('executing techerChoice')
    
def letterButton():
    print('executing letterButton')

teacherLogin = Button((100, 250, 400, 100), teacherChoice, text = 'Teacher')
studentLogin = Button((100, 100, 400, 100), letterButton, text = 'Student', color = pg.Color('blue'))

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        teacherLogin.getEvent(event)
        studentLogin.getEvent(event)
 
    screen.fill(pg.Color('white'))
    teacherLogin.draw(screen)
    studentLogin.draw(screen)
    pygame.display.update()
 
pygame.quit()
The difference between ours is
  • the initialization of the buttons are before the main loop
  • the buttons' event method is ran in the event loop
  • there are callback functions for the buttons

The callback function are only ran once after being pressed. They themselves can call a flag variable to do something persistently. A "new screen" to me sounds like a state machine. If you want this to occur with a button press, then you can use this example and replace the event of mouse button down event to your button press event instead. In this example the buttons callback function would just have to set the states done value to True to get the next screen.

I made this example for this thread, but would be better suited in the tutorials section for future users..
https://python-forum.io/Thread-PyGame-Cr...4#pid64464
Recommended Tutorials:
Reply


Messages In This Thread
Can't get button class to work - by mzmingle - Nov-21-2018, 10:39 AM
RE: Can't get button class to work - by metulburr - Nov-21-2018, 02:30 PM
RE: Can't get button class to work - by mzmingle - Nov-26-2018, 04:45 PM
RE: Can't get button class to work - by metulburr - Nov-26-2018, 10:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Button class still not working? mzmingle 3 3,110 Jan-16-2019, 04:43 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020