You may have seen in the Maker Hacks Facebook Group the latest iteration of my Raspberry Pi based entertainment center. It’s now got to the point where I need a boot menu, so I thought I would share the code and implementation with you!
Code
See the full code in the Gist.
First we need to add the readchar
module. Use pip3 install readchar
.
This module simplifies interpreting keypresses, otherwise, we would need to look up the escape codes and such ourselves. Not fun.
The other module is the os
module which allows us to clear the screen (os.system('clear')
) and launch programs.
Once you have done this it is a simple case to do an infinite while
loop and look for the specific keys we want the user to choose from.
Remember I said the module helps us? Check out where looking for the Enter key is made much easier:
if(key == readchar.key.ENTER):
We launch the programs using os.system
– you can get more clever with it but this works for our purposes.
import os import readchar # place in your start up file: # sudo nano ./.bashrc def menu(): while True: os.system('clear') print("\t\tChoose from the following options:\n\n") print("\t\tk: Kodi") print("\t\tr: Retro Pi") print("\t\tx: XWindows") print("\n\t\tEnter to quit to terminal\n\n\n") # Read a key key = readchar.readkey() if(key == 'k'): print("Launch Kodi") os.system("kodi") elif(key == 'r'): print("Launch RetroPie") os.system("emulationstation") elif(key == 'x'): print("Launch X Windows") os.system("startx") elif(key == readchar.key.ENTER): print("Exit to terminal") break else: print("Please choose an option from above") if __name__ == "__main__": menu()