Make a functioning traffic light, that switches from green through yellow to red and vice versa.
Create a program that simulates a functional traffic intersection using AI.
Create a new program mouse.py and copy the following code into it. Then run the program.
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
def click(mouse):
print(mouse.x, mouse.y)
canvas.bind('<B1-Motion>', click)
A new command canvas.bind has been added. Thanks to it, the drawing area will now know what to do when you press the left mouse button over it and then move the mouse. Numbers will start appearing in the text window. What do these numbers mean? How must we change the program if we want it to react to pressing the middle or right mouse button?
Instead of the print command in the previous function click, use the command canvas.create_text to draw the character ‘*’. Draw the character at the position where the mouse is. Change the size, font, and color of the printed sign.
Modify the function click in the program mys.py so that it draws a colored circle. Choose the color using a conditional statement so that the program draws red circles to the left of x = 150 and green circles to the right. The radius of the circles will be 5. For example:
Add new lines of code to the previous program:
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
def click(mouse):
…
…
def erase(mouse):
canvas.delete('all')
canvas.bind('<B1-Motion>', click)
canvas.bind('<ButtonPress-3>', erase)
Now we have added functionality to the program that is triggered by clicking the right mouse button. Try it out. We used canvas.delete(‘all’), which clears the drawing area.
Let’s learn how to use a new command canvas.create_line(x1, y1, x2, y2). With this command, we can draw a line segment from point [x1, y1] to point [x2, y2]. Create a new program lines.py and copy the following code into it.
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
def click(mouse):
canvas.create_line(150, 100, mouse.x, mouse.y)
def erase(mouse):
canvas.delete('all')
canvas.bind('<B1-Motion>', click)
canvas.bind('<ButtonPress-3>', erase)
Set the color of the line to red.
First, store the color you want the program to draw with in a variable, for example: color = ‘blue’
We will modify the function click: