pygame-将更新的鼠标坐标显示在屏幕上

时间:2020-10-20 23:50:16

标签: text pygame coordinates mouse

谁能帮助我找出如何在屏幕的右上角放置不断更新的ouse坐标?我认为将其仅用于开发目的将对您有很大帮助,但我无法弄清楚。到目前为止,这是我的代码:

'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 20:26:57 2020

@author: wohlsr
"""

import pygame
from pygame.locals import *
from sys import exit

background_image_filename = ('menu-start.jpg')
mouse_image_filename = ('mouse-pointer.png')
icon = pygame.image.load('go-stop-icon.png')

pygame.init()
screen = pygame.display.set_mode((1024, 768), 0, 32)
pygame.display.set_caption("Gostop")
pygame.display.set_icon(icon)
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()



while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    pygame.mouse.set_visible(0)
    screen.blit(background, (0,0))
    x, y = pygame.mouse.get_pos()
    x-= mouse_cursor.get_width() / 2
    y-= mouse_cursor.get_height() / 2
    screen.blit(mouse_cursor, (x, y))

    

    pygame.display.update()
'''

Visual of what I have so far

1 个答案:

答案 0 :(得分:1)

此代码将鼠标位置放置在屏幕的右上角。

import pygame
from pygame.locals import *
from sys import exit

background_image_filename = ('menu-start.jpg')
mouse_image_filename = ('mouse-pointer.png')
icon = pygame.image.load('go-stop-icon.png')

pygame.init()
screen = pygame.display.set_mode((1024, 768), 0, 32)
pygame.display.set_caption("Gostop")
pygame.display.set_icon(icon)
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()

font=pygame.font.SysFont('arial',20,True,False)  # font for mouse position
def showcoords(screen,x,y):
    q1Text= font.render("{}  {}".format(int(x),int(y)).center(20),1,(0,0,0))  # surface with coord text
    bg = q1Text.copy()  # copy surface for background
    bg.fill((0,100,100))  # background
    textRect = q1Text.get_rect()   
    textRect.topright = ((1024,0))  # put in top\right corner
    screen.blit(bg,textRect)  # draw background
    screen.blit(q1Text,textRect)  # draw coords



while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    pygame.mouse.set_visible(0)
    screen.blit(background, (0,0))
    x, y = pygame.mouse.get_pos()
    x-= mouse_cursor.get_width() / 2
    y-= mouse_cursor.get_height() / 2
    screen.blit(mouse_cursor, (x, y))

    showcoords(screen,x,y)  # show mouse coords

    pygame.display.update()

如果您想使用全局x,y值而不传递参数,请进行以下更改:

def showcoords(screen):
    global x,y  # use existing x,y values
    .......

showcoords(screen)  # show mouse coords

输出

Mouse