Graphics.py Keyboard Input

#! /usr/bin/python3
# ===================================================================
# draw rectangle and monitor keyboard
# Note: This program uses window coordinates
#
# (Use keyboard input to modify the rectangle?)
# ===================================================================

from graphics import *
import time

rx1        = 100
ry1        = 100
rx2        = 200
ry2        = 200
win_height = 801
win_width  = 801

# -------------------------------------------------------------------
# ---- draw a rectangle
# -------------------------------------------------------------------

def draw_rectangle(win,x1,y1,x2,y2):

   r = Rectangle(Point(x1,y1), Point(x2,y2))
   r.setFill("red")
   r.setOutline("black")
   r.setWidth(4)
   r.draw(win)

   return r.getCenter()

# -------------------------------------------------------------------
# ---- draw text string
# ---- x,y are the center of the text graphicas object
# -------------------------------------------------------------------

def draw_text_string(win,txt,x,y):

    t = Text(Point(x,y),txt)
    t.draw(win)

# -------------------------------------------------------------------
# ---- draw axes at center point of window
# -------------------------------------------------------------------

def draw_axies(win):

    xl = Line(Point(0,win_height/2),Point(win_width-1,win_height/2))
    xl.setWidth(1)
    xl.setFill("black")
    xl.draw(win)

    yl = Line(Point(win_width/2,0),Point(win_width/2,win_height-1))
    yl.setWidth(1)
    yl.setFill("black")
    yl.draw(win)

# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

win = GraphWin("Draw Rectangle", win_width, win_height)
win.setBackground("white")

draw_axies(win)

cp = draw_rectangle(win,rx1,ry1,rx2,ry2)

txt ='This window must have the focus for keyboard input'
draw_text_string(win,txt,win_width/2,win_height*5/8)

txt = f'rectangle center is x={cp.getX()} y={cp.getY()}'
draw_text_string(win,txt,win_width/2,win_height*7/8)

# ---- keyboard input

while True:

    key = win.getKey()

    print(f'key="{key}"  len={len(key)}')

    if key == 'q' or key == 'Q':
        break

win.close()                    # close window
print()