Как сделать так, чтобы круг следовал за указателем мыши? - PullRequest
0 голосов
/ 25 декабря 2018

Я пытаюсь сделать 2D-шутер с Python tkinter.
Вот мой прогресс:

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 make circle1 иcircle2 следуйте за указателем мыши.Как то так c.goto(circle1, x, y).

1 Ответ

0 голосов
/ 25 декабря 2018

Вы можете сделать это, изменив координаты двух "кругов" в функции обработчика событий move_circle().Чтобы сделать так, чтобы центры этих двух объектов располагались на «кончике» указателя мыши, выполняется простой расчет (см. Изображение ниже).

Обратите внимание, я также изменил ваш код, чтобы более точно следовать PEP 8 - Руководству по стилю для Python Code Руководствам по кодированию.

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:

screenshot of GUI app running

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...