【问题标题】:Object Following X Coords of Mouse Position Tkinter对象跟随鼠标位置 Tkinter 的 X 坐标
【发布时间】:2018-11-01 13:09:39
【问题描述】:

我正在尝试打乒乓球,我希望我的球拍跟随鼠标的 x 位置。我只是将鼠标的 x 位置分配给一个变量,每次我移动鼠标然后离开屏幕时它都会添加到自身。我现在对其进行了一些更改,但我无法让它工作

错误:

    Traceback (most recent call last):
    File "Tkinter.py", line 1536, in __call__
    return self.func(*args)
    File "animationTest.py", line 51, in motion
    self.diff = self.x - canvas.coords(self.paddle)
    TypeError: unsupported operand type(s) for -: 'int' and 'list'

代码:

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()

【问题讨论】:

  • canvas.coords(self.paddle) 返回一个包含左上角 X 位置和 Y 位置以及右下角 X 位置和 Y 位置的列表。您需要先从列表中提取您想要的位置,然后才能在减法中使用它。
  • @Novel 我将一个变量设置为canvas.coords(self.paddle),但我如何才能获得 X1?
  • 就像任何列表一样使用方括号对其进行索引:x1 = canvas.coords(self.paddle)[0]

标签: python tkinter python-2.x


【解决方案1】:

没有理由读取当前坐标。您可以使用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。

【讨论】:

  • 非常感谢,它解决了我的问题。
  • 您介意解释一下这是如何工作的吗?
  • __init__ 方法中,您将坐标设置为0,0,100,10。这只是更新那些。如果 event.x 为 150,则坐标更新为 100、0、200、10。
  • 如果您在问题正文中添加解释,此答案会更好。
猜你喜欢
  • 2016-07-02
  • 1970-01-01
  • 2022-01-15
  • 2014-06-23
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多