所以我做了一个带有按钮的主菜单。一个开始按钮和一个退出按钮。我已经编写了“退出”按钮以退出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:From apc
您可以这样做:
但我建议您导入并使用运行它