DeaD_EyE

gpiozero tkinter

Sep 3rd, 2020
1,068
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from tkinter import Tk, Button, Label
  2.  
  3. # zum Testen
  4. from gpiozero.pins.mock import MockFactory
  5.  
  6. # Button ist schon einmal importiert worden
  7. # deswegen der Import mit einem anderen Namen
  8. from gpiozero import Button as GPIO_Button
  9.  
  10.  
  11. class GUI(Tk):
  12.     def __init__(self, inputs):
  13.         super().__init__()
  14.         self.inputs = inputs
  15.         self.labels = {}
  16.         self.setup()
  17.  
  18.     def setup(self):
  19.         for name, gpio_obj in self.inputs.items():
  20.             gpio_obj.when_pressed = lambda: self.on(name)
  21.             gpio_obj.when_released = lambda: self.off(name)
  22.             if gpio_obj.value:
  23.                 color = "green"
  24.             else:
  25.                 color = "red"
  26.             label = Label(self, text=name, bg=color)
  27.             self.labels[name] = label
  28.             label.pack()
  29.         Button(self, text="Beenden", command=self.destroy).pack()
  30.  
  31.     def on(self, name):
  32.         label = self.labels[name]
  33.         label["bg"] = "green"
  34.  
  35.     def off(self, name):
  36.         label = self.labels[name]
  37.         label["bg"] = "red"
  38.  
  39.  
  40. if __name__ == "__main__":
  41.     factory = MockFactory()
  42.     inputs = {
  43.         "GPIO 17": GPIO_Button(17, pin_factory=factory),
  44.         "GPIO 20": GPIO_Button(20, pin_factory=factory),
  45.     }
  46.     app = GUI(inputs)
  47.     app.mainloop()
  48.  
  49.  
  50.  
RAW Paste Data