How do I add collision detection to the sides of the window in Tkinter? [Python 3]
<p>I'm making an (admittedly, my first) game in Python, and I've only really made the base of the game (like, moving around), and everything works <em>pretty</em> well, except for the fact that you can move right off the screen.
How would I add collision detection to the sides of the window?
Here's the code:</p>

<pre><code>from tkinter import *
import time
tk = Tk()
tk.title("Squarey")
c = colorchooser.askcolor(title='Choose Squarey\'s Color')
canvas = Canvas(tk, width=700, height=700)
canvas.pack()
class Squarey:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(10, 10, 50, 50, fill=color)
    def draw(self, pos):
        def move(event):
            if event.keysym == 'Up':
                self.canvas.move(self.id, 0, -5)
            elif event.keysym == 'Down':
                self.canvas.move(self.id, 0, 5)
            elif event.keysym == 'Left':
                self.canvas.move(self.id, -5, 0)
            else:
                self.canvas.move(self.id, 5, 0)
        canvas.bind_all('&lt;KeyPress-Up&gt;', move)
        canvas.bind_all('&lt;KeyPress-Down&gt;', move)
        canvas.bind_all('&lt;KeyPress-Left&gt;', move)
        canvas.bind_all('&lt;KeyPress-Right&gt;', move)
class Tele:
    def __init__(self, canvas, pos):
        self.canvas = canvas
        self.id = canvas.create_text(10, 10, text=pos)
    def draw(self, pos):
        canvas.delete(self.id)
        self.id = canvas.create_text(350, 350, text=pos)
squarey = Squarey(canvas, c[1])
pos = squarey.canvas.coords(squarey.id)
tele = Tele(canvas, pos)
while 1:
    pos = squarey.canvas.coords(squarey.id)
    squarey.draw(pos)
    tele.draw(pos)
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)
</code></pre>

<p>Hope everyone can help me out; thanks!</p>

<p>I assume you want to detect the collision of a rectangle with the edges of the screen. I am stranger to tkinter, however I have experience with pygame, let me explain as well as I can.</p>

<p>In pygame, a rectange position are given as left_top corner, a(one side), b(another side). Such as,</p>

<pre><code>(x, y)    b
   ...............
   .             .
   .             .
  a.             .
   .             .
   ...............
</code></pre>

<p>if you want to detect collision, you have to check all sides, using these values.</p>

<p>Let's say screen is <code>(width, height)</code></p>

<pre><code># Top side collision
if y &lt; 0:
    print "Touched top"
# Right side collision
if x + b &gt; width:
    print "Touched right"
# Bottom side collision
if y + a &gt; height:
    print "Touched bottom"
# Left side collision
if x &lt; 0:
    print "Touched left"
</code></pre>

<p>I am pretty sure quite similar logic is needed in tkinter as well.</p>

python tkinter collision-detection python-3.4 tkinter-canvas