Search code examples
pythontkinterkey-bindingstkinter-canvas

Tkinter - Using multiple key-binds


I've made a program which draws an oval on click (mouse click=start point, mouse release= end point) as shown in code below, and I'd like to add if condition: when the shift key is pressed midst drawing, it would equalize the coordinates and therefore as a result, a circle (or perfect oval if you wish) will be drawn.

from tkinter import *
def draw(event):
    if str(event.type)=='ButtonPress':
        canvas.old_coords=event.x,event.y
    elif str(event.type)=='ButtonRelease':
        x,y=event.x,event.y
        x1,y1=canvas.old_coords
        canvas.create_oval(x,y,x1,y1)
canvas=Canvas()
canvas.pack()
canvas.bind('<B1-Motion>',draw)
canvas.bind('<ButtonPress-1>',draw)
canvas.bind('<ButtonRelease-1>',draw)

How could I possibly take in account pressed shift and then draw a circle?


Solution

  • So, I found a Python module called keyboard and I solved my problem using it, adding this condition:

    if keyboard.is_pressed('shift'):
        if y>y1: y=y1+abs(x-x1)
        else: y=y1-abs(x-x1)
    

    which changes the end coordinates and later draws circle accordingly