Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prompt user to open a file with python3?

I'm making a game and I want the user to be able to click a button which opens the file manager and asks them to open a game save file. Is there a module / how could I put this in my game? If there's no good gui way how would I make a text input thing (without using the terminal)? Thanks!

like image 200
FluffyFlounder Avatar asked Oct 19 '25 22:10

FluffyFlounder


1 Answers

Pygame is a low-level library, so it doesn't have the kind of built-in dialogs you're after. You can create such, but it will be quicker to use the tkinter module which is distributed with Python and provides an interface to the TK GUI libraries. I'd recommend reading the documentation, but here's a function that will pop up a file selection dialog and then return the path selected:

def prompt_file():
    """Create a Tk file dialog and cleanup when finished"""
    top = tkinter.Tk()
    top.withdraw()  # hide window
    file_name = tkinter.filedialog.askopenfilename(parent=top)
    top.destroy()
    return file_name

Here's a small example incorporating this function, pressing Spacebar will popup the dialog:

import tkinter
import tkinter.filedialog
import pygame

WIDTH = 640
HEIGHT = 480
FPS = 30

def prompt_file():
    """Create a Tk file dialog and cleanup when finished"""
    top = tkinter.Tk()
    top.withdraw()  # hide window
    file_name = tkinter.filedialog.askopenfilename(parent=top)
    top.destroy()
    return file_name

pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

f = "<No File Selected>"
frames = 0
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                f = prompt_file()

    # draw surface - fill background
    window.fill(pygame.color.Color("grey"))
    ## update title to show filename
    pygame.display.set_caption(f"Frames: {frames:10}, File: {f}")
    # show surface
    pygame.display.update()
    # limit frames
    clock.tick(FPS)
    frames += 1
pygame.quit()

Notes: This will pause your game loop, as indicated by the frame counter but as events are being handled by the window manager, this shouldn't be an issue. I'm not sure why I needed the explicit import tkinter.filedialog, but I get an AttributeError if I don't.

As for string entry in pygame, you might want to do this natively, in which case you'd be handling KEYUP events for letter keys to build the string and perhaps finishing when the user presses Enter or your own drawn button. You could continue down the tk path, in which case you'll want to use something like tkinter.simpledialog.askstring(…)

like image 147
import random Avatar answered Oct 21 '25 12:10

import random