Full Python Code:

import tkinter as tk

import time

class TrafficLight:

    def __init__(self, root):

        self.root = root

        self.root.title(“Traffic Light”)

        self.canvas = tk.Canvas(root, width=200, height=400, bg=”white”)



        self.colors = [“red”, “orange”, “green”]

        self.current_color_index = 0


    def draw_traffic_light(self):

        #Draw the traffic light background

        self.canvas.create_rectangle(50, 50, 150, 350, outline=”black”, fill=”gray”)

        #Draw the red light

        self.canvas.create_oval(75, 75, 125, 125, outline=”black”, fill=”gray”, tags=”red”)

        #Draw the orange light

        self.canvas.create_oval(75, 150, 125, 200, outline=”black”, fill=”gray”, tags=”orange”)

        #Draw the green light

        self.canvas.create_oval(75, 225, 125, 275, outline=”black”, fill=”gray”, tags=”green”)

    def update_traffic_light(self):

        current_color = self.colors[self.current_color_index]

        #Turn off all lights

        self.canvas.itemconfig(“red”, fill=”gray”)

        self.canvas.itemconfig(“orange”, fill=”gray”)

        self.canvas.itemconfig(“green”, fill=”gray”)

        #Turn on the current color

        self.canvas.itemconfig(current_color, fill=current_color)

        #Update the color index for the next iteration

        self.current_color_index = (self.current_color_index + 1) % len(self.colors)

        #Schedule the next update after 10 seconds

        self.root.after(10000, self.update_traffic_light)

if _name_ == “__main__”:

    root = tk.Tk()

    traffic_light = TrafficLight(root)



Leave a Reply

Your email address will not be published. Required fields are marked *