如何使圆形跟随鼠标指针?

时间:2018-12-25 09:31:56

标签: python tkinter

我正在尝试使用Python tkinter做2D射击游戏。
这是我的进度:

from tkinter import *

root = Tk()

c = Canvas(root, height=500, width=500, bg='blue')
c.pack()

circle1x = 250
circle1y = 250
circle2x = 250
circle2y = 250

circle1 = c.create_oval(circle1x, circle1y, circle1x + 10, circle1y + 10, outline='white')
circle2 = c.create_rectangle(circle2x, circle2y,circle2x + 10, circle2y + 10)

pos1 = c.coords(circle1)
pos2 = c.coords(circle2)

c.move(circle1, 250 - pos1[0], 250 - pos1[2])
c.move(circle2, 250 - pos1[0], 250 - pos1[2])

beginWall = c.create_rectangle(0, 200, 500, 210, outline='white')

def move_circle(event):
   pass

c.bind('<Motion>', move_circle)

root.mainloop()

但是我试图使名为move_circle的函数使circle1circle2跟随鼠标指针。像这样的c.goto(circle1, x, y)

1 个答案:

答案 0 :(得分:1)

您可以通过在move_circle()事件处理函数中修改两个“圆”的坐标来实现。通过简单的计算就可以使这两个对象的中心位于鼠标指针的“尖端”(请参见下图)。

请注意,我还修改了您的代码,以更严格地遵循ES docs编码准则。

import tkinter as tk

# Constants
CIRCLE1_X = 250
CIRCLE1_Y = 250
CIRCLE2_X = 250
CIRCLE2_Y = 250
SIZE = 10  # Height and width of the two "circle" Canvas objects.
EXTENT = SIZE // 2  # Their height and width as measured from center.

root = tk.Tk()

c = tk.Canvas(root, height=500, width=500, bg='blue')
c.pack()

circle1 = c.create_oval(CIRCLE1_X, CIRCLE1_Y,
                        CIRCLE1_X + SIZE, CIRCLE1_Y + SIZE,
                        outline='white')
circle2 = c.create_rectangle(CIRCLE2_X, CIRCLE2_Y,
                             CIRCLE2_X + SIZE, CIRCLE2_Y + SIZE)

pos1 = c.coords(circle1)
pos2 = c.coords(circle2)

c.move(circle1, 250-pos1[0], 250-pos1[2])
c.move(circle2, 250-pos1[0], 250-pos1[2])

begin_wall = c.create_rectangle(0, 200, 500, 210, outline='white')

def move_circles(event):
    # Move two "circle" widgets so they're centered at event.x, event.y.
    x0, y0 = event.x - EXTENT, event.y - EXTENT
    x1, y1 = event.x + EXTENT, event.y + EXTENT
    c.coords(circle1, x0, y0, x1, y1)
    c.coords(circle2, x0, y0, x1, y1)

c.bind('<Motion>', move_circles)

root.mainloop()

以下是在Windows计算机上运行的屏幕截图:

PEP 8 - Style Guide for Python Code