from tkinter import * def main(): color = None root = Tk() root.title("Traffic Lights") root.geometry("640x480") # drawArea = Canvas(root, bg="white") drawArea = Canvas(root, bg="#cffbffaff") drawArea.pack(side=LEFT, fill=BOTH, expand=True, padx=8, pady=8) panel = Frame(root) panel.pack(side=RIGHT, fill=Y, expand=False, padx=8, pady=8) redButton = Button(panel, text="Red") redButton.pack(side=TOP, fill=X) yellowButton = Button(panel, text="Yellow") yellowButton.pack(side=TOP, fill=X) greenButton = Button(panel, text="Green") greenButton.pack(side=TOP, fill=X) blinkingButton = Button(panel, text="Blinking") blinkingButton.pack(side=TOP, fill=X) blinkDt = 500 # 500 milliseconds = 0.5 s blinking = False def onRed(): nonlocal color, blinking blinking = False color = 0 drawLights() def onYellow(): nonlocal color, blinking blinking = False color = 1 drawLights() def onGreen(): nonlocal color, blinking blinking = False color = 2 drawLights() def onBlinking(): nonlocal color, blinking blinking = True color = 1 drawLights() drawArea.after(blinkDt, switchYellow) def switchYellow(): nonlocal color, blinking if not blinking: return if color == 1: color = (-1) else: color = 1 drawLights() drawArea.after(blinkDt, switchYellow) def drawLights(): w = drawArea.winfo_width() h = drawArea.winfo_height() drawArea.delete("all") x = w/2 r = 20 for y in (h/3, h/2, h*2/3): drawArea.create_oval( x - r, y - r, x + r, y + r, fill=None, outline="black") if color == 0: y = h/3 drawArea.create_oval(x - r, y - r, x + r, y + r, fill="red") elif color == 1: y = h/2 drawArea.create_oval(x - r, y - r, x + r, y + r, fill="yellow") elif color == 2: y = h*2/3 drawArea.create_oval(x - r, y - r, x + r, y + r, fill="green") redButton.configure(command=onRed) yellowButton.configure(command=onYellow) greenButton.configure(command=onGreen) blinkingButton.configure(command=onBlinking) drawLights() drawArea.bind("", lambda e: drawLights()) root.mainloop() if __name__ == "__main__": main()