I have a 2 vertical lines on a canvas with a gap in the middle (generated randomly every time). This line starts on the right side of the canvas. When I click the "l" key it runs a function that moves the line left by 5, and you can keep clicking "l" until it reaches the left side. I want to know how to set it up so I only have to press the "l" key once and the line will slowly move across the screen until it reaches the left side. Any help would be appreciated
import random
import time
from tkinter import *
window = Tk()
window.geometry("300x300")
window.title("GUI")
window.resizable(FALSE, FALSE)
label1 = Label(window, text="My First GUI", font=("arial", 16, "bold"))
label1.pack()
canvas = Canvas()
canvas.config(bg="gray")
canvas.place(width=300, height=150, x=0, y=150)
def key_pressed(event):
if event.char == "l":
move_line()
def create_gap():
gap_ycoords = []
# random number between 10 and 95 in increments of 5
first_line_end = random.randrange(10, 96, 5)
gap_ycoords.append(first_line_end)
second_line_start = first_line_end + 50
gap_ycoords.append(second_line_start)
return gap_ycoords
def draw_line_obstacle(canvas_ref):
y_coord = create_gap()
top_line = canvas_ref.create_line(295, 5, 295, y_coord[0], tags="top_line")
bottom_line = canvas_ref.create_line(295, y_coord[1], 295, 145, tags="bottom_line")
draw_line_obstacle(canvas)
def move_line():
if canvas.coords("top_line")[0] > 5:
tcoords = canvas.coords("top_line")
bcoords = canvas.coords("bottom_line")
canvas.coords("top_line", tcoords[0] - 5, tcoords[1], tcoords[2] - 5, tcoords[3])
canvas.coords("bottom_line", bcoords[0] - 5, bcoords[1], bcoords[2] - 5, bcoords[3])
window.bind("<Key>", key_pressed)
window.mainloop()