对象跟随鼠标位置Tkinter的X Coords

时间:2018-05-22 17:14:40

标签: python tkinter python-2.x

我想制作乒乓球,我希望我的球拍跟随鼠标的x位置。我只是将鼠标的x位置分配给一个变量,每当我移动鼠标然后离开屏幕时它就会自动添加。我现在改变了一点,但我无法让它工作

错误:

from Tkinter import *
import time

HEIGHT = 500
WIDTH = 800
COLOR = 'blue'
SIZE = 50

root = Tk()

canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg=COLOR)
canvas.pack()


class Ball:

   def __init__(self, canvas):
      self.ball = canvas.create_oval(0, 0, SIZE, SIZE, fill='black')
      self.speedx = 6
      self.speedy = 6
      self.active = True
      self.move_active()

   def ball_update(self):
      canvas.move(self.ball, self.speedx, self.speedy)
      pos = canvas.coords(self.ball)
      if pos[2] >= WIDTH or pos[0] <= 0:
            self.speedx *= -1
      if pos[3] >= HEIGHT or pos[1] <= 0:
            self.speedy *= -1

   def move_active(self):
      if self.active:
         self.ball_update()
         root.after(1, self.move_active)



class Paddle:


   def __init__(self, canvas):
      self.paddle = canvas.create_rectangle(0,0,100,10, fill='red')
      canvas.bind('<Motion>', self.motion)
      self.active = True
      self.move_active


   def motion(self, event):
      self.x = event.x
      self.diff = self.x - canvas.coords(self.paddle)
      print('the diff is:' ,self.diff)
      print('the click is at: {}'.format(self.x))


   def move_active(self):
      if self.active:
         self.motion()
         root.after(1, self.move_active)





run = Ball(canvas)
run2 = Paddle(canvas)
root.mainloop()

CODE:

interface SomeType {

}

export interface IEvents {
  method(): boolean;
  on(name: "eventName1", listener: (obj: SomeType) => void): 13;
  on(name: "eventName2", listener: (obj: SomeType) => void): void;
  on(name: "eventName3", listener: (obj: SomeType) => void): undefined;
  on(name: "eventName4", listener: (obj: SomeType) => void): 14;
  on(name: "eventName5", listener: (obj: SomeType) => void): 10;
  on(name: "eventName6", listener: () => void): "hola";
  on(name: "eventName8", listener: (obj: SomeType) => void): 200;
  on(name: "eventName7", listener: (obj: SomeType) => void): void;
}

const x: ReturnType<IEvents["on"]> = 200;

1 个答案:

答案 0 :(得分:0)

没有理由读取当前坐标。您可以使用event.x计算新坐标,而无需知道当前坐标是什么。

def motion(self, event):
    '''update paddle coordinates using current mouse position'''
    canvas.coords(self.paddle, event.x-50, 0, event.x+50, 10)

这将简单地覆盖您在__init__方法中设置的坐标0,0,100,10,其中新坐标基于鼠标位置。