Search code examples
pythonuser-interfacetkintertextsave

Saving GUI entries to a text file


This is the first time I've used tkinter and GUI in Python, so I'm pretty much a novice.

I have a big GUI form that I made with tkinter. It uses all the classic tkinter widgets: text entry boxes, spinboxes, option menus, radio buttons, and check buttons. What I want to do is let a user enter data into the GUI form and then press the Save button to save everything to a text file. Unfortunately, I can't find many examples of saving data like this to a text file. Here is a generic sample of my code.

import tkinter as tk
from tkinter import ttk

variables = dict()

root = tk.Tk()
root.title('Generic Form')
root.columnconfigure(0, weight=1)

ttk.Label(root, text='Generic Form', font=("TkDefaultFont", 16)).grid()

drf = ttk.Frame(root)
drf.grid(padx=10, sticky=(tk.N + tk.S))
drf.columnconfigure(0, weight=1)

g_info = ttk.LabelFrame(drf, text='Generic Data')
g_info.grid(row=0, column=0, sticky=(tk.W + tk.E))

variables['Scenario ID'] = tk.StringVar()
ttk.Label(g_info, text='Scenario ID').grid(row=0, column=0)
ttk.Entry(g_info, textvariable=variables['Scenario ID']).grid(row=1, column=0, sticky=(tk.W + tk.E))

variables['Integer Value'] = tk.IntVar()
ttk.Label(g_info, text='Integer Value').grid(row=2, column=0)
ttk.Spinbox(g_info, textvariable=variables['Integer Value'], from_=0, to=100, increment = 1).grid(row=3, column=0, sticky=(tk.W + tk.E))

variables['OPTIONS'] = tk.StringVar()
option_var = tk.StringVar(value='Choose')
choices = ('This', 'That', 'The Other Thing')
ttk.Label(g_info, text='OPTIONS').grid(row=4, column=0, sticky=(tk.W + tk.E))
ttk.OptionMenu(g_info, option_var, *choices).grid(row=5, column=0, sticky=(tk.W + tk.E))

choice_default = tk.StringVar(value=F)
variables['CHOICE'] = tk.StringVar()
choice_frame = ttk.Frame(g_info)
ttk.Label(g_info, text='CHOICE').grid(row=6, column=0, sticky=(tk.W + tk.E))
choice_frame.grid(row=7, column=0, sticky=(tk.W + tk.E))
for choice in ('T', 'F'):
    ttk.Radiobutton(choice_frame, value=choice, test=choice, variable=choice_default.pack()

buttons = tk.Frame(drf)
buttons.grid(column=1, pady=20, sticky=(tk.W + tk.E))
save_button = ttk.Button(buttons, test='Save')
save_button.pack(side=tk.RIGHT)

def on_save():
   filename = f'C:/test.txt'
   data = dict()
   with open(filename, 'w', newline='' as fh:
      fh.write("\n")

save_button.configure(command=on_save)
root.mainloop()

Here is the output text I'm trying to get.

Generic Data
  Scenario ID = Scenario 1
  Integer Value = 51
  Options = The Other Thing
  Choice = T

Most of what I know with tkinter is from the book Python GUI Programming with Tkinter by Alan D. Moore. Unfortuantely, this book only describes how to save data into a CSV file. For the project I'm working on, I need it saved in a text file. I know there's a way to do this, but I can't find any examples except for the Entry widget.


Solution

  • After some trial and error, I have finally found a solution and can post an answer. Let me be clear though: this answer is due in no part to anyone who replied to this post. I stated upfront that I am new to tkinter, but everyone that replied (acw1668, Rory, Brian Oakley, and especially Tim Roberts) treated me as if I was a buffoon. You all talked past the issue, would only give me the vaguest hints about what I was doing wrong, and offered me no solutions. Thanks for nothing everyone. You have my deepest condescension, because that is all you gave me.

    import tkinter as tk
    from tkinter import ttk
    
    variables = dict()
    
    root = tk.Tk()
    root.title('Generic Form')
    root.columnconfigure(0, weight=1)
    
    ttk.Label(root, text='Generic Form', font=("TkDefaultFont", 16)).grid()
    
    drf = ttk.Frame(root)
    drf.grid(padx=10, sticky=(tk.N + tk.S))
    drf.columnconfigure(0, weight=1)
    
    frame_info = ttk.LabelFrame(drf, text='Generic Data')
    frame_info.grid(row=0, column=0, sticky=(tk.W + tk.E))
    
    variables['Scenario ID'] = tk.StringVar()
    ttk.Label(frame_info, text='Scenario ID').grid(row=0, column=0)
    ttk.Entry(frame_info, textvariable=variables['Scenario ID']).grid(row=1, column=0, sticky=(tk.W + tk.E))
    
    variables['Integer Value'] = tk.IntVar()
    ttk.Label(frame_info, text='Integer Value').grid(row=2, column=0)
    ttk.Spinbox(frame_info, textvariable=variables['Integer Value'], from_=0, to=100, increment = 1).grid(row=3, column=0, sticky=(tk.W + tk.E))
    
    variables['OPTIONS'] = tk.StringVar()
    option_var = tk.StringVar(value='Choose')
    choices = ('Choose', 'This', 'That', 'The Other Thing')
    ttk.Label(frame_info, text='OPTIONS').grid(row=4, column=0, sticky=(tk.W + tk.E))
    ttk.OptionMenu(g_info, variables['OPTIONS'], *choices).grid(row=5, column=0, sticky=(tk.W + tk.E))
    
    choice_default = tk.StringVar(value='F')
    variables['CHOICE'] = tk.StringVar()
    choice_frame = ttk.Frame(frame_info)
    ttk.Label(frame_info, text='CHOICE').grid(row=6, column=0, sticky=(tk.W + tk.E))
    choice_frame.grid(row=7, column=0, sticky=(tk.W + tk.E))
    for choice in ('T', 'F'):
        ttk.Radiobutton(choice_frame, value=choice, variable=variables['CHOICE']).pack()
    
    def on_save():
        
        
        inc = variables['Scenario ID'].get()
        number = variables['Integer Value'].get()
        menu = variables['OPTIONS'].get()
        boolean = variables['CHOICE'].get()
        
        with open('GUI.txt', 'w') as x:
            x.write( 'Generic Data' ), x.write('\n')
            x.write( f'  Scenario ID = {inc}' ), x.write('\n')
            x.write( f'  Integer Value = {number}' ), x.write('\n')
            x.write( f'  Options = {menu}' ), x.write('\n')
            x.write( f'  Choice = {boolean}' ), x.write('\n')
    
    tk.Button(frame_info, text='Save', command=on_save).grid(row=8, column=0, sticky=(tk.W + tk.E))
    
    root.mainloop()