Creating a JSON file with Tkinter Python (with example)

by Apr 10, 2020Python Tkinter Examples

Introduction:

In this article, we will learn “How to interface JSON(JavaScript Object Notation) with Tkinter”. If you are new to Python’s JSON package, I recommend you to go through this first similarly if you are new to Tkinter go through this.

Here we will design a GUI with an application format with user input textbox and save it as a JSON file in the computer as “IOTEDU.json” in default.

So I have decided the look of the GUI as below

Imagination of GUI widgets which will be implemented later.
– GUI of Application Format

We will have 3 inputs from the user. To get the inputs we will be using the Entry box and a button to trigger action. We can do this with simple knowledge in Tkinter.  What about JSON?, We will learn it in this article. Here is the code for the following.

from tkinter import *
import JSON
from tkinter.filedialog import asksaveasfile

window = Tk()
window.geometry('640x300')
window.title('IoT4Begineers')

name = Label(window, text="Name:")
Name = Entry(window)
age = Label(window, text="Age:")
Age = Entry(window)
role = Label(window, text="Role:")
Role = Entry(window)
submit = Button(window,text='Submit',command = check).grid(row=3, column=1)


test = 1
def writeToJSONFile(path, fileName, data):
        json.dump(data, path)

path = './'


def check():
    a = Name.get()
    b = test * int(Age.get())
    c = Role.get()
    print(a)
    print(b)
    print(c)
    data = {}
    data['Name'] = a
    data['Age'] = b
    data['Role'] = c
    files = [('JSON File', '*.json')]
    fileName='IOTEDU'
    filepos = asksaveasfile(filetypes = files,defaultextension = json,initialfile='IOTEDU')
    writeToJSONFile(filepos, fileName, data)


name.grid(row=0, column=0)
age.grid(row=1,column=0)
role.grid(row=2,column=0)
Name.grid(row=0, column=1)
Age.grid(row=1, column=1)
Role.grid(row=2, column=1)


mainloop()

Steps with Explanation:

1. Importing the packages

from tkinter import *
import json
from tkinter.filedialog import asksaveasfile

We’ve imported three packages, first of all for Tkinter, one for the JSON and finally for the saveas function which helps you do operation on files i.e saving a file and opening a file from the system.

2. Creating a window for the GUI

window = Tk()
window.geometry('640x300')
window.title('IoT4Begineers')

3. Adding widgets to the GUI

name = Label(window, text="Name:")
Name = Entry(window)
age = Label(window, text="Age:")
Age = Entry(window)
role = Label(window, text="Role:")
Role = Entry(window)
submit = Button(window,text='Submit',command = check).grid(row=3, column=1)

Here I had added 3 labels likewise 3 Entry boxes to get input from the user and also a button to trigger the function check()

4. Defining a function (check) to save the input data.

def check():
    a = Name.get()
    b = test * int(Age.get())
    c = Role.get()
    print(a)
    print(b)
    print(c)
    data = {}
    data['Name'] = a
    data['Age'] = b
    data['Role'] = c
    files = [('JSON File', '*.json')]
    filepos = asksaveasfile(filetypes = files,defaultextension = json,initialfile='IOTEDU')
    writeToJSONFile(filepos, fileName, data)

  • First of all, I will get the data from the Entry box using the function get() and save it into the variables a,b,c
  • Then I create an empty dictionary named data and set the index values of (‘Name’ to a, ‘Age’ to b and ‘Role’ to c).
  • Here I use the operation of saveas to save the file to the system and put it into a variable named filepos, Here I selected filetypes as files as we are saving it as file type and default extension as JSON, as our format is to be saved in JSON format and initial file indicates the default name to be saved in, so I set it to “IOTEDU”
  • I called a function writeTOJSONFile() to write the data into the JSON file.

5. Defining a function(writeTOJSONFile) to convert data in JSON format.

path = './'

def writeToJSONFile(path, fileName, data):
        json.dump(data, path)

  • Initially I set the Path to home.
  • In this function I used the json.dump method to convert the python objects into JSON format.

6. Layout the widgets in position

name.grid(row=0, column=0)
age.grid(row=1,column=0)
role.grid(row=2,column=0)
Name.grid(row=0, column=1)
Age.grid(row=1, column=1)
Role.grid(row=2, column=1)

Finally I used grid function to layout the widgets in a appropriate positions.

Here is the output of the following code.

Output:

Well, that’s about it. Now go create something more fun, and I hope my tutorial has helped you out somewhat.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Tkinter based GUI- Application form

Tkinter based GUI- Application form

Hello everyone! Today we are going to make a Tkinter based GUI that will be an Application Form . We will ask some details by the user and then will be saving that with a default extension of .yaml, which can be changed at the time of saving the file. Let's go ahead!...

Look and Feel Customization on Python Tkinter

In this tutorial, you will learn about how to customize the look and feel of a python GUI created using tkinter. This is third part of tkinter tutorial course. To begin with, we will look at how to create message boxes. Contents: Creating MessageboxesCreate...

Layout Management using Python Tkinter

Layout Management using Python Tkinter

In this tutorial, you will be learning “How to layout your GUI using Python”. The following are the topics that will be covered in this article. Python Tkinter Label FramesTkinter Geometry MatrixCreating menu barsCreating tabbed widgets 1. Python Tkinter Label Frames:...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....