如何使一个圆跟随鼠标指针?

2024-04-20 13:47:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python tkinter制作2D shooter。
以下是我的进展:

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_circlemakecircle1circle2跟随鼠标指针。像这样的c.goto(circle1, x, y)。你知道吗


Tags: movetkintercreaterootcoordswhiterectanglepos1
1条回答
网友
1楼 · 发布于 2024-04-20 13:47:50

可以通过修改move_circle()事件处理程序函数中两个“圆”的坐标来实现。一个简单的计算是这样做的,这两个对象的中心定位在鼠标指针的“尖端”(见下图)。你知道吗

注意,我还修改了您的代码,以便更紧密地遵循PEP 8 - Style Guide for 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

相关问题 更多 >