Skip to content Skip to sidebar Skip to footer

How To Write Captured Input From A Tkinter Entry Widget To A Json File

Thank you for your time. I reduced the structure of this problem to make it as simple to solve as possible. I am working in python with the GUI developer, tkinter. I want to captur

Solution 1:

If you want to write json, the first step is to create a data structure that can be converted to json. Then, you can use the json.dump function to write the data to a file.

Example:

import json
...
data = {
    "first_name": e1.get(),
    "last_name": e2.get()
}
with open('name.json', 'w') as f:
    json.dump(data, f, indent=4)

When you execute that code, and enter "Foo" for the first name and "Bar" for the last name, the file will have this as its contents:

{"first_name":"Foo","last_name":"Bar"}

Solution 2:

This code works! Using open("file name", "a") and then write, exports the input from the entry label to the file!

from tkinter import *

def show_entry_fields():
   f = open("name.json", "a")
   f.write("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
   e1.delete(0,END)
   e2.delete(0,END)

master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1.config(relief=SUNKEN)
e2.config(relief=SUNKEN)


Button(master, text='Show', command=show_entry_fields).grid(row=3, column=1, sticky=W, pady=4)

mainloop( )

Post a Comment for "How To Write Captured Input From A Tkinter Entry Widget To A Json File"