Skip to main content
 首页 » 编程设计

python之如何在 Python 中的多个 while 语句之间切换

2025年05月04日11落叶

我正在编写一个程序,我需要在不同的循环中切换。 当我尝试切换回我崩溃的前一个循环时,这是可行的想法。

有什么建议吗?

附言以下是例子

例如函数 = 主页

(改变循环)

函数 = txtbox

(改变循环)

Function = Home(此处崩溃)

import pygame, sys, time, random 
from pygame.locals import * 
import math 
import sys 
import os 
# set up pygame 
pygame.init() 
 
 
 
 
# set up the window 
WINDOWWIDTH = 1200 
WINDOWHEIGHT = 650 
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 1, 32) 
pygame.display.set_caption("Mango") 
 
 
Function = "Home" 
 
font = pygame.font.SysFont("Fonts", 30) 
 
#colors 
TEXTCOLOR = (255, 255, 255) 
TEXTCOLORS = (255, 0, 0) 
 
 
# run the game loop 
while Function == "Home": 
    # check for the QUIT event 
    events = pygame.event.get() 
    for event in events: 
        if event.type == QUIT: 
            pygame.quit() 
            sys.exit() 
        elif event.type == pygame.MOUSEBUTTONUP: 
            Function = "txtbox" 
            break 
 
 
    pygame.display.flip() 
 
 
 
while Function == "txtbox": 
 
    events = pygame.event.get() 
    # process other events 
    for event in events: 
 
          if event.type == pygame.MOUSEBUTTONUP: 
            Function = "Home" 
            break 
 
    pygame.display.flip() 

请您参考如下方法:

它不会崩溃。当 Function 在最后一个循环中设置为“Home”时,它就完成了执行。那个循环就结束了。

尝试将这两个 while 循环包含在另一个永远运行的 while 循环中。

while True: 
    while Function == "Home": 
        # check for the QUIT event 
        events = pygame.event.get() 
        for event in events: 
            if event.type == QUIT: 
                pygame.quit() 
                sys.exit() 
            elif event.type == pygame.MOUSEBUTTONUP: 
                Function = "txtbox" 
                break 
 
 
        pygame.display.flip() 
 
 
 
    while Function == "txtbox": 
 
        events = pygame.event.get() 
        # process other events 
        for event in events: 
 
              if event.type == pygame.MOUSEBUTTONUP: 
                Function = "Home" 
                break 
 
        pygame.display.flip()