Home > database >  How to make a window bounce back when it touches edge of screen (tinker)
How to make a window bounce back when it touches edge of screen (tinker)

Time:12-21

This is my code:

from time import sleep
from tkinter import *


def moveWin(win, velx, vely):
    x = win.winfo_x()
    y = win.winfo_y()
    win.geometry(f" {str(x   velx)} {str(y   vely)}")
    downx, downy = x width, y height
    global sWidth
    global sHeight
    if x <= 0 or downx >= sWidth:
        velx = -velx
    if y <= 0 or downy >= sHeight:
        vely = -vely
    return [x, y, downx, downy]


root = Tk()
width = 300
height = 300
velx = 1
vely = 1
sWidth = root.winfo_screenwidth()  # gives 1366
sHeight = root.winfo_screenheight()  # gives 1080
root.geometry(" 250 250")
while True:
    root.update()
    root.geometry("300x300")
    pos = moveWin(root, velx, vely)
    print(pos)
    sleep(0.01)

I want to bounce back my window when it touches the screen edge but its just going off the screen whats wrong in my code? pls help

CodePudding user response:

If you need to modify global variables, then don't pass them as parameters. Instead, add

def movewin(win):
    global velx
    global vely

at the top of your function.

BIG FOLLOWUP

The more important issue in your app has to do with coordinates. root.winfo_x() and root.winfo_y() do NOT return the upper left corner of your window. Instead, they return the upper left corner of the drawable area, inside the borders and below the title bar. That screws up your drawing, and means you try to position off the bottom of the screen, which Tkinter fixes up.

The solution here is to track the x and y positions yourself, instead of fetching them from Tk.

Tkinter is mostly garbage. You would be better served by looking at pygame for simple games, or at a real GUI system like Qt or wxPython for applications.

from time import sleep
from tkinter import *

class Window(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.width = 300
        self.height = 300
        self.velx = 1
        self.vely = 1
        self.pos = (250,250)
        self.geometry(f"{self.width}x{self.height} {self.pos[0]} {self.pos[1]}")

    def moveWin(self):
        x = self.pos[0]   self.velx
        y = self.pos[1]   self.vely
        downx, downy = x self.width, y self.height
        sWidth = self.winfo_screenwidth()  # gives 1366
        sHeight = self.winfo_screenheight()  # gives 1080
        if x <= 0 or downx >= sWidth:
            self.velx = -self.velx
        if y <= 0 or downy >= sHeight:
            self.vely = -self.vely
        self.pos = (x,y)
        self.geometry(f" {x} {y}")
        return [x, y, downx, downy]

root = Window()
while True:
    root.update()
    pos = root.moveWin()
    print(pos)
    sleep(0.01)
  • Related