Python, using tkinter canvas as boundaries


I am currently trying to make the canvas the borders for example something like:

def coords():
     if pos1 <= canvas.height:


if event.keysym == 'w' and tri.hit_left ==False:
        canvas.move(tri, 0, -2)

this would make it so if the triangle collides with the edge of the canvas it would not move past the edge. However I know this does not work because i have tested it out.


from tkinter import *

import random

import time

tk = Tk()


tk.resizable(0, 1)

tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=500)

x3 = 5

y3 = 5

x4 = 5

y4 = 15

x5 = 13

y5 = 10

pos1 = [x3, y3]

pos2 = [x4, y4]

pos3 = [x5, y5]

tri=canvas.create_polygon(x3, y3, x4, y4, x5, y5)



def coords():

def move_tri(event):
    if event.keysym == 'w' and tri.hit_top ==False:
        canvas.move(tri, 0, -2)
    elif event.keysym == 's' and tri.hit_bottom == False:
        canvas.move(tri, 0, 2)
    elif event.keysym == 'a' and tri.hit_left == False:
        canvas.move(tri, -2, 0)
    elif event.keysym == 'd' and tri.hit_right == False:
        canvas.move(tri, 2, 0)


canvas.bind_all('<KeyPress-w>', move_tri)

canvas.bind_all('<KeyPress-a>', move_tri)

canvas.bind_all('<KeyPress-s>', move_tri)

canvas.bind_all('<KeyPress-d>', move_tri)

if you know how to do what i am trying to do please write suggestions, and feel free to ask for clarification.


Haven't dealt with tk before but shouldn't there be a loop to keep the canvas alive instead of immediately exiting? After adding a loop, there are errors about doing operations on ints that ints do not support.

Should probably fix that first right?

And, why did you make the w key follow different logic from the other 3 keys? Are those doing what you want? If so just compare to what you did with them.


it doesn't immediately exit for me, u must be using IDLE