python - 按下按钮时文本未输出到 pygame 屏幕
问题描述
我想编写一个非常简单的程序,当我按下按钮时将文本输出到 pygame 屏幕,但由于某种原因,当我按下按钮时它没有输出。有什么帮助吗?谢谢。
import pygame
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
X=800
Y=480
pygame.init()
pygame.font.init()
my_screen = pygame.display.set_mode((800, 480) ,
pygame.RESIZABLE)
my_font = pygame.font.Font('freesansbold.ttf' , 36)
text = my_font.render("Please wait, loading...",True,green)
textRect=text.get_rect()
textRect.center = (X // 2, Y //2)
pressed=False
boxThick=[0,10,10,10,10,10]
still_looping =True
while still_looping:
for event in pygame.event.get():
if event.type==pygame.QUIT:
still_looping=False
pygame.draw.rect(my_screen,(0,255,0),(0,0,200,200),boxThick[0])
pygame.draw.rect(my_screen,(50,50,50),(200,200,100,50),0)
a,b,c = pygame.mouse.get_pressed()
if a:
pressed = True
else:
if pressed == True:
x,y = pygame.mouse.get_pos()
if x> 200 and x<300 and y>200 and y<200:
my_screen.blit(text,textRect)
pressed = False
pygame.display.update()
解决方案
不显示文本,因为条件y>200 and y<200
总是用 求值False
。由于矩形区域的高度为 50,因此条件必须为y>200 and y<250
:
if x> 200 and x<300 and y>200 and y<200:
if x> 200 and x<300 and y>200 and y<250:
# [...]
由于比较运算符可以在 Python 中链接,因此可以简化代码:
if 200 < x < 300 and 200 < y < 250:
# [...]
但是,如果您想测试鼠标指针是否在矩形区域中,我建议使用pygame.Rect
对象和collidepoint()
:
rect = pygame.Rect(200, 200, 100, 50)
x, y = pygame.mouse.get_pos()
if rect .collidepoint(x, y):
# [...]
推荐阅读
- python - 为什么调试的结果和运行时的结果不一样
- python - 如何对具有不同值的相同 ID 进行正确预测
- node.js - 无法修改已提交的 WriteBatch。(云功能)
- python - 使用 out .get("title") 拉出 Title 属性
- azure - 如何为 Azure ACR 创建 azure logic app?
- outlook - Outlook 加载项 - 附件 ID 在桌面应用程序中无法正常工作,但在 Web 应用程序中工作
- python - 检查数据框中列中的字符串是否存在于不同数据框中的列中
- java - Eureka - 在本地主机上工作,但在不同主机上时出现问题
- python - 选择时值从表中消失
- machine-learning - 将状态批次传递到网络时大小不匹配