我正在尝试使tkinter窗口像Pong中的球一样在屏幕上反弹,但是它将在每个方向上仅移动1个像素,然后再次返回。我做错了什么?
main.py:
import tkinter
from time import sleep
window = tkinter.Tk()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
window.title('VIRUS.EXE')
width, height = 300, 150
x, y, = 0, 0
x_vel = 1
y_vel = 1
while True:
sleep(0.1)
if x + width >= screen_width or x <= 0:
x_vel = -x_vel
if y + width >= screen_height or y <= 0:
y_vel = -y_vel
x += x_vel
y += y_vel
window_string = str(width) + 'x' + str(height) + '+' + str(x) + '+' + str(y)
window.geometry(window_string)
window.update()
window.mainloop()
答案 0 :(得分:0)
尝试使用+
而不是-
if x + width >= screen_width or x <= 0:
x_vel = +x_vel
if y + width >= screen_height or y <= 0:
y_vel = +y_vel
编辑:这可能会为您指明正确的方向:
if x <= screen_width or x <= 0:
x_vel = +x_vel
x += x_vel
if y <= (screen_height -200)or y <= 0:
y_vel = +y_vel
y += y_vel