在Pygame中使用其他文件时,如何打开新文件?

所以我做了一个带有按钮的主菜单。一个开始按钮和一个退出按钮。我已经编写了“退出”按钮以退出pygame。现在,我不想将函数放到执行此操作的“开始”按钮中: 打开另一个Python文件,其中发生了主要游戏部分。我制作了一个新的Python文件“ Testo.py”。 然后,我进入“开始”按钮的用途所在的代码部分,并写道:open(file =“ Testo.py”)。但是什么也没发生。我将为您提供两个按钮的代码,但主要部分在“ greenButton”(或“开始”按钮)上。我希望你能理解我的意思。

run = True
greenButton = button((0, 255, 0), 280, 255, 250, 100, "Start")
redButton = button ((255, 0, 0), 280, 380, 250, 100, "Quit")
while run:
    redrawWindow()

    for event in pygame.event.get():
        pos = pygame.mouse.get_pos()

        if event.type == pygame.QUIT:
            run = False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if greenButton.isOver(pos):
                print("clicked the button")
                open(file="Testo.py")
            if redButton.isOver(pos):
                print("clicked the 2button")
                run = False
                pygame.quit()
                quit()

        if event.type == pygame.MOUSEMOTION:
            if greenButton.isOver(pos):
                greenButton.color = (105, 105, 105)
            else:
                greenButton.color = (0, 255, 0)
            if redButton.isOver(pos):
                redButton.color = (105, 105, 105)
            else:
                redButton.color = (255, 0, 0)


评论
  • 长相思守
    长相思守 回复

    Opening a file with open lets you read/write to that file as if it was open in a text editor. I would assume you want to execute the python code written in that file? In that case, you have to import it and call the function you want to execute. For example:

    import Testo
    Testo.main()
    
  • (艮)悲伤
    (艮)悲伤 回复

    There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

    1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
    2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
      • execfile('file.py') in Python 2
      • exec(open('file.py').read()) in Python 3
    3. Spawn a shell process: os.system('python file.py'). Use when desperate.

    From apc

  • 輸給o時咣
    輸給o時咣 回复

    您可以这样做:

    execfile('Testo.py')
    

    但我建议您导入并使用运行它