Search code examples
pythonfileuser-interfacedialogtk-toolkit

How To Create a File Dialog Using Python


I started coding 3 days ago! So far it has been fun, but I have encoured my first road block. I'm wanting to create a "FILE" button that performs all the same functions as it would in any other application: Open, Save, and Save as. What I can do so far is click the file button to expose my three options.

from tkinter import *

root = Tk()

def MyFiles():
    my_ListFile = Listbox(root, selectmode="single", bg="light grey", width=18, height=3, font=('Helvetica 10'))
    my_ListFile.place(x=0, y=27)
    # Additing items to list box
    my_ListFile.insert(END, "Open")
    my_ListFile.insert(END, "Save")
    my_ListFile.insert(END, "Save As")

def oneselect(event):
    listB = event.widget
    idx = int(listB.curselection()[0])
    value = w.get(idx)
    # if the value is open, then open the directory and close the listbox
    # if the value is Save, then save the current GUI and close the listbox
    #if the value is Save As, open directory and close list box

File = Button(root, text="File", command=MyFiles, width=15, font=('Helvetica 10')).place(x=1, y=1)

root.mainloop()

How can I click each option in the list to perform a different function? I'm attempting to build a GUI.


Solution

  • I think you might be looking for something like below:

    File Dialog Screenshot

    You may be able to try something like below:

    import tkinter as tk
    from tkinter import ttk
    from tkinter import filedialog as fd
    from tkinter.messagebox import showinfo
    
    # create the root window
    root = tk.Tk()
    root.title('Tkinter Dialog')
    root.resizable(False, False)
    root.geometry('300x150')
    
    # helper function to select a file to open
    def select_file():
        filetypes = (
            ('text files', '*.txt'),
            ('All files', '*.*')
        )
        filename = fd.askopenfilename(
            title='Open a file',
            initialdir='/',
            filetypes=filetypes)
        showinfo(
            title='Selected File',
            message=filename
        )
    
    # helper function to save a file
    def file_save():
        filetypes = (
        ('text files', '*.txt'),
        ('All files', '*.*')
        )
        f = fd.asksaveasfile(
            title='Save a file',
            mode='w', 
            defaultextension=".txt")
        if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
            return
    
    # helper function to save a file
    def file_save_as():
        filetypes = (
        ('text files', '*.txt'),
        ('All files', '*.*')
        )
        f = fd.asksaveasfile(
            title='Save a file',
            mode='w', 
            defaultextension=".txt")
        if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
            return
    
    def Click(e, var):
        def VG(var):
            select_file()
        def G(var):
            file_save()
        def P(var):
            file_save_as()
        e.widget.focus()
        nclst=[(' Open', lambda var = var: VG(var)),
                (' Save', lambda var = var: G(var)),
                (' Save As', lambda var = var: P(var)),]
    
        my_menu = tk.Menu(None, tearoff=0, takefocus=0)
        for (txt, cmd) in nclst:
                my_menu.add_command(label=txt, command=cmd)
        my_menu.tk_popup(e.x_root+40, e.y_root+10,entry="0")
    
    l_var = tk.StringVar()
    lab = tk.Label(root, textvariable = l_var, width = 10)
    l_var.set("File")
    lab.bind('<Button-1>', lambda e, var = l_var: Click(e, var)) 
    lab.pack()
    
    # run the application
    root.mainloop()
    

    Note that you'll want to modify the specific functionality of the file open, save, and save as methods to match your specific needs - But this may help in getting started