如何在一个表面上为 pygame 提供多个输入框并将这些输入存储在变量中? [复制]

Posted

技术标签:

【中文标题】如何在一个表面上为 pygame 提供多个输入框并将这些输入存储在变量中? [复制]【英文标题】:How to have multiple input boxes on one surface for pygame and store those inputs in variables? [duplicate] 【发布时间】:2019-04-04 23:45:51 【问题描述】:
import pygame
pygame.init()

display_width = 1024
display_height = 600
display = pygame.display.set_mode((display_width,display_height))

blue = (0,0,200)
light_blue = (0,0,255)
black = (0,0,0)
red = (200,0,0,255)
light_red = (255,0,0)
white = (255,255,255)
light_purple = (139,0,139,255)
purple = (128,0,128,255)

smallfont = pygame.font.SysFont("comicsansms", 50)
medfont = pygame.font.SysFont("Algerian", 50)
largefont = pygame.font.SysFont("Algerian", 85)


altSmall = pygame.font.SysFont("Algerian",20)
altMed = pygame.font.SysFont("Algerian",30)
altLarge = pygame.font.SysFont("Algerian",75)
extrasmall = pygame.font.SysFont("comicsansms",15)


clock = pygame.time.Clock()

def text_objects(text, color,size = "small"):

    textSurface = smallfont.render(text, True, black)

    if size == "small":
        textSurface = smallfont.render(text, True, color)
    if size == "medium":
        textSurface = medfont.render(text, True, color)
    if size == "large":
        textSurface = largefont.render(text, True, color)

    if size == "altMed":
        textSurface = altMed.render(text,True,color)

    if size == "altSmall":
        textSurface = altSmall.render(text,True,color)

    if size == "medFont":
        textSurface = medfont.render(text,True,color)

    if size == "smallFont":
        textSurface = smallfont.render(text,True,color)

    if size == "extraSmall":
        textSurface = extrasmall.render(text,True,color)

    return textSurface, textSurface.get_rect()

def alt_med_pos_message_to_screen(msg,color,x,y,size = "smallfont"):
    screen_text = smallfont.render(msg,True,color)
    display.blit(screen_text,[x,y])

class Button():

    text = str()
    x = int()
    y = int()
    width = int()
    height = int()
    inactive_color = None
    active_color = None
    action = str()
    active = bool()

    def __init__(self,text,x,y,width,height,inactive_color,active_color,action,text_color,text_size,active):
        self.text = text
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.inactive_color = inactive_color
        self.active_color = active_color
        self.action = action
        self.text_color = text_color
        self.text_size = text_size
        self.active = active

    def nothing():
        pass

    def handle_event(self,event):

        if self.is_hovered() and event.type == pygame.MOUSEBUTTONDOWN:
            self.action()

    def text_to_button(self,surface):
        textSurf, textRect = text_objects(self.text,self.text_color,self.text_size)
        textRect.center = ((self.x+(self.width/2)), self.y+(self.height/2))
        surface.blit(textSurf, textRect)


    def is_hovered(self):
        cur = pygame.mouse.get_pos()
        return self.x + self.width > cur[0] > self.x and self.y + self.height > cur[1] > self.y

    def drawButton(self, surface):

        if self.active:
            pygame.draw.rect(surface,self.inactive_color,[self.x,self.y,self.width,self.height])

        if self.is_hovered() and self.active:
            pygame.draw.rect(surface, self.active_color,[self.x,self.y,self.width,self.height])

        self.text_to_button(surface)

def home_screen():

    backgroundImg = 'C:/Users/student/Desktop/Geometry Calc/Images/programbackground.png'
    statisticsImg = 'C:/Users/student/Desktop/Geometry Calc/Images/statistics.png'
    algebraImg = 'C:/Users/student/Desktop/Geometry Calc/Images/algebra-math.png'
    geometryImg = 'C:/Users/student/Desktop/Geometry Calc/Images/geometry.png'

    background = pygame.image.load(backgroundImg)
    statistics = pygame.image.load(statisticsImg)
    algebra = pygame.image.load(algebraImg)
    geometry = pygame.image.load(geometryImg)

    homeScreen = True
    StatisticsButton = Button("Statistics",100,250,250,85,purple,light_purple,statistics_formulas,black,"smallfont",True)
    GeometryButton = Button("Geometry",100,315,250,85,purple,light_purple,geometry_formulas,black,"smallfont",True)
    AlgebraButton = Button("Algebra",100,390,250,75,purple,light_purple,algebra_formulas,black,"smallfont",True)
    while homeScreen:
        for evt in pygame.event.get():
            StatisticsButton.handle_event(evt)
            GeometryButton.handle_event(evt)
            AlgebraButton.handle_event(evt)
            if evt.type == pygame.QUIT:
                homeScreen = False
                pygame.quit()
                quit()

        display.blit(background,[0,0])
        alt_med_pos_message_to_screen("Formula Hack",red,display_width/2-150,100,size = "smallfont")
        StatisticsButton.drawButton(display)
        GeometryButton.drawButton(display)
        AlgebraButton.drawButton(display)

        display.blit(statistics,[350,250])
        display.blit(geometry,[350,325])
        display.blit(algebra,[350,400])

        pygame.display.update()

def statistics_formulas():

    inStatistics = True
    backgroundImg ='C:/Users/student/Desktop/Geometry Calc/Images/StatisticsBackground.png'

    Zscore = Button("1. Z-score",900,25,75,35,purple,light_purple,zscore,black,"extraSmall",True)


    statsBackground = pygame.image.load(backgroundImg)
    while inStatistics:
        for evt in pygame.event.get():
            Zscore.handle_event(evt)
            if evt.type == pygame.QUIT:
                inStatistics = False
                pygame.quit()
                quit()

        display.blit(statsBackground,[0,0])

        Zscore.drawButton(display)
        pygame.display.update()

def geometry_formulas():
    print("geometry")

def algebra_formulas():
    print("algebra")

def zscore():
    screen = pygame.display.set_mode((display_width, display_height))
    font = pygame.font.Font(None, 32)
    clock = pygame.time.Clock()
    input_box = pygame.Rect(100, 100, 140, 32)
    color_inactive = pygame.Color('lightskyblue3')
    color_active = pygame.Color('dodgerblue2')
    color = color_inactive
    active = False
    text = "0"
    done = False
    input1 = int(text)

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                # If the user clicked on the input_box rect.
                if input_box.collidepoint(event.pos):
                    # Toggle the active variable.
                    active = not active
                else:
                    active = False
                # Change the current color of the input box.
                color = color_active if active else color_inactive
            if event.type == pygame.KEYDOWN:
                if active:
                    if event.key == pygame.K_RETURN:
                        text = ""
                    elif event.key == pygame.K_BACKSPACE:
                        text = text[:-1]
                    else:
                        text += event.unicode

        screen.fill((30, 30, 30))
        # Render the current text.
        txt_surface = font.render(text, True, color)
        # Resize the box if the text is too long.
        width = max(200, txt_surface.get_width()+10)
        input_box.w = width
        # Blit the text.
        screen.blit(txt_surface, (input_box.x+5, input_box.y+5))

        # Blit the input_box rect.
        pygame.draw.rect(screen, color, input_box, 2)

        pygame.display.flip()
        clock.tick(30)

home_screen()

如果知道有帮助,我只需要存储整数、值,谢谢! 问题所在代码的主要部分位于函数“zScore”下方的底部附近,但它确实使用了在整个代码中创建的一些类。任何帮助表示赞赏。

我最初尝试将变量文本存储在另一个变量中并使用此输入变量进行基本操作,但输入框当然只接受字符串。然后我尝试使用 int() 函数尝试将输入到输入框中的字符串转换为整数,但这也不起作用。我也无法在同一屏幕上使用多个输入框。

【问题讨论】:

我知道您正在使用我的示例,但您的问题中有很多代码,我们必须对其进行分析才能给出答案。如果您将其减少到 minimal, runnable example 将会很有帮助。 我的原始示例的链接:***.com/a/46390412/6220679 【参考方案1】:

您只需在用户按下回车键时将text 变量转换为int。这应该有效:

if event.key == pygame.K_RETURN:
    try:
        input1 = int(text)
    except ValueError:
        print('Invalid input')
    text = ""

【讨论】:

我不确定你想用 input1 做什么。如果你想在其他功能之一中使用它,你必须return它。 嗨,对不起,我刚刚看到你的评论。是的,这是你的算法,如果我应该先问的话,我很抱歉,你的帖子对我很有帮助。感谢您再次回复我的 pygame 问题,您非常有帮助!

以上是关于如何在一个表面上为 pygame 提供多个输入框并将这些输入存储在变量中? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在 pygame 表面打洞? [复制]

如何在pygame中制作具有透明背景的表面

pygame:屏蔽非图像类型的表面

如何在 Pygame 中将具有一定透明度的 PNG 粘贴到表面上? [复制]

在pygame中的透明表面上渲染抗锯齿文本

Pygame:保存对象/类/表面的列表