python - 在pygame中用鼠标移动可缩放矩形

标签 python python-3.x pygame

我正在尝试在 pygame 中移动一个矩形,并使其可缩放。

The scalable rectangle code is something like this然后我尝试添加这样的事件:

from pygame imports *
init()

rect1 = (rect1x, rect1y, 300,300)
rect1x = 0
rect1y = 0

while running: 
    x,y = mouse.get_pos()
        if rect1Pressed == True:
        rect1x = x
        rect1y = y
    for evnt in event.get():
            if evnt.type == QUIT:
                running = False
    if evnt.type == MOUSEBUTTONDOWN:
        if evnt.button == 1:
            if rect1.collidepoint(mouse.get_pos()):
                rect1Pressed == True

我如何合并可缩放矩形并使其能够随鼠标移动?这样窗口就会跟随鼠标移动。所以它有点像笔记本电脑上的一个,您可以在其中缩放窗口并四处移动它。

最佳答案

您可以检查在 elif event.type == pg.MOUSEMOTION: block 中按下了哪个鼠标按钮,例如if event.buttons[0]:,然后根据按钮移动或缩放矩形。要移动矩形,只需将 event.rel 添加到 rect.xrect.y 属性即可。

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect1 = pg.Rect(100, 100, 161, 100)
rect2 = pg.Rect(300, 200, 161, 100)
selected_rect = None

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEBUTTONDOWN:
            for rect in (rect1, rect2):
                if rect.collidepoint(event.pos):
                    selected_rect = rect  # Select the colliding rect.
        elif event.type == pg.MOUSEBUTTONUP:
            selected_rect = None  # De-select the rect.
        elif event.type == pg.MOUSEMOTION:
            if selected_rect is not None:  # If a rect is selected.
                if event.buttons[0]:  # Left mouse button is down.
                    # Move the rect.
                    selected_rect.x += event.rel[0]
                    selected_rect.y += event.rel[1]
                else:  # Right or middle mouse button.
                    # Scale the rect.
                    selected_rect.w += event.rel[0]
                    selected_rect.h += event.rel[1]
                    selected_rect.w = max(selected_rect.w, 10)
                    selected_rect.h = max(selected_rect.h, 10)

    screen.fill((30, 30, 30))
    pg.draw.rect(screen, (0, 100, 250), rect1)
    pg.draw.rect(screen, (0, 200, 120), rect2)
    pg.display.flip()
    clock.tick(30)

关于python - 在pygame中用鼠标移动可缩放矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261024/

相关文章:

python - 只需创建一个包含一个月所有日期的列 - 使用 pandas

python - MYSQL LOAD DATA INFILE 忽略具有非唯一值列的重复行

python - 属性错误: 'Alien' object has no attribute 'image' (I am calling for a Group object)

python - 如何更改 PyGame 中声音或音乐的音量?

python - 简单程序中的错误: TypeError: into object has no attribute '__getitem__'

python - 安装了 Opencv 但是 python 找不到包

python - 如何对多张图像进行傅里叶变换并将输出保存到单个对象中

python-3.x - 如何使用给定的坐标与 python opencv 在图像中绘制一个点?

python-3.x - 按月计算 cumsum() 但如果该月没有数据则重复这些值

python - 使用 bool AND 计算行中字符串的出现次数