Home > OS >  Is there a way to pull data from a json and add it into a grid in tkinter?
Is there a way to pull data from a json and add it into a grid in tkinter?

Time:12-23

I am trying to make a desktop application that can track network that have been added to the app. I'm saving these networks in a json file. I want to be able to grab those networks from the sheet and add them into a grid. Does anyone know if there is a way to do this?

user.json file:

{
  "networks": [
    {
      "network name": "mynet",
      "Network IP": "192.168.0.0",
      "Subnet": "255.255.255.240",
      "Intermediary Devices": "2",
      "Hosts": "8"
    },
    {
      "network name": "NewNet",
      "Network IP": "10.0.0.100",
      "Subnet": "255.255.255.240",
      "Intermediary Devices": "1",
      "Hosts": "12"
    },
    {
      "network name": "pop",
      "Network IP": "192.168.2.10",
      "Subnet": "255.255.255.248",
      "Intermediary Devices": "1",
      "Hosts": "2"
    }
  ]
}

My code below:


import json
import ctypes
from tkinter import *
from PIL import Image, ImageTk

ctypes.windll.shcore.SetProcessDpiAwareness(1)

class NetAppHomePG:

   

    def __init__(self):

        self.win = Tk()
        self.win.geometry("3800x2000")
        self.win.title("NetApp")

        self.NavBarFrame = Frame(self.win, background="grey")
        self.TabsFrame = Frame(self.win)

        self.Networks = {}

        self.UsedIPs = []

        

        #NavBar
        self.Logo = Label(self.NavBarFrame, text="NetApp", font=("Roboto", 36), foreground="white", background="grey").grid(row=0, column=0, padx=10, pady=10, sticky=W)
        self.ProfileImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/user.png"))
        self.Logo = Button(self.NavBarFrame, image=self.ProfileImg, background="grey", border=0).grid(row=0, column=1, padx=3200, pady=10, sticky=E)

        self.NavBar1 = Canvas(self.win, width=3840, height=10, background="grey")
        self.NavBar1.create_line(0, 10, 3840, 10, width=7, fill="grey")
        self.NavBar1.place(x=0,y=151)
        
        #Tabs
        self.TabBtn1 = Button(self.TabsFrame, text="My IPv4 Networks", font=("Roboto", 18), border=0, background="lightblue")
        self.TabBtn1.grid(row=0, column=0, padx=50, pady=300, ipadx=50, sticky=W E)

        self.TabBtn2 = Button(self.TabsFrame, text="My IPv6 Networks", font=("Roboto", 18), border=0, background="lightblue")
        self.TabBtn2.grid(row=1, column=0, padx=50, pady=100, ipadx=50, sticky=W E)

        self.TabBtn3 = Button(self.TabsFrame, text="Settings", font=("Roboto", 18), border=0, background="lightblue")
        self.TabBtn3.grid(row=2, column=0, padx=50, pady=300, ipadx=50, sticky=W E)

        self.TabLine1 = Canvas(self.win, width=10, height=1862, background="grey")
        self.TabLine1.create_line(10, 0, 10, 1862, width=6, fill="grey")
        self.TabLine1.place(x=700,y=163)

        #ManageMyNets
        self.NetName = 1
        self.xcor = int(0)
        self.ycor = int(1)
        self.OnlineDotImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/green-dot.png"))
        self.AddImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/plus.png"))
        self.NetRouterImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/router.png"))
        self.NetPCImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/computer-set.png"))
        self.NetSwitchImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/hub.png"))
        self.NetServerImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/server.png"))
        self.AddButton = Button(self.TabsFrame, image=self.AddImg, command=self.Add_Network)
        self.AddButton.grid(row=self.xcor, column=self.ycor, padx=250, pady=0)
        self.NavBarFrame.grid(sticky=W)
        self.TabsFrame.grid(sticky=W)

        with open("user.json") as json_file:
            self.data = json.load(json_file)
            self.temp = self.data['networks']
            
        
        for network in self.temp:
            self.NetworkBg= Canvas(self.TabsFrame, width=600, height=600, background="white")
            self.NetworkName = Label(self.NetworkBg, text=(self.temp[0]['network name']), font=("Roboto", 18), foreground="black", background="white")
            self.NetworkIP = Label(self.NetworkBg, text=(self.temp[0]['Network IP']), font=("Roboto", 12), foreground="black", background="white")
            self.NetworkSubnet = Label(self.NetworkBg, text=("Subnet: " self.temp[0]['Subnet']), font=("Roboto", 12), foreground="black", background="white")
            self.NetworkState = Label(self.NetworkBg, text=("Status: "), font=("Roboto", 12), foreground="black", background="white")
            self.Dot = Label(self.NetworkBg, image=self.OnlineDotImg, foreground="black", background="white")
            self.NetworkInter = Label(self.NetworkBg, text=("Intermediary Devices: " self.temp[0]['Intermediary Devices']), font=("Roboto", 12), foreground="black", background="white")
            self.InspectNet = Button(self.NetworkBg, text=("Inspect Network"), border=0, font=("Roboto", 12, "underline"), foreground="black", background="white", command=self.Inspect)
            self.NetworkHosts = Label(self.NetworkBg, text=("Hosts: " self.temp[0]['Hosts']), font=("Roboto", 12), foreground="black", background="white")
            self.NetworkBg.grid(row=self.xcor, column=self.ycor, padx=150, pady=0)
            self.NetworkName.grid(row=0, column=0, sticky=W)
            self.NetworkIP.grid(row=1, column=0, pady=10,sticky=W)
            self.NetworkSubnet.grid(row=2, column=0, sticky=W)
            self.NetworkState.grid(row=3, column=0, pady=20, sticky=W)
            self.Dot.grid(row=3, column=0, padx=110, sticky=W)
            self.NetworkInter.grid(row=4, column=0, pady=0, sticky=W)
            self.NetworkHosts.grid(row=5, column=0, pady=0, sticky=W)
            self.InspectNet.grid(row=6, column=1, pady=0, sticky=E)
            self.AddButton.grid(row=self.xcor, column=self.ycor 1, padx=150, pady=0)
            
        self.win.mainloop()

    def write_json(self, filename="user.json"):
        with open(filename, "w") as f:
            self.y = {"network name": self.NetName, "Network IP": self.IP, "Subnet" : self.Subnet, "Intermediary Devices" : self.InterDevice, "Hosts" : self.Hosts}
            self.temp.append(self.y)
            json.dump(self.data, f, indent=2)
    


    def NetInfo(self):
        self.NetName = self.NetEntry.get()
        self.InterDevice = self.NumInterDeviceEntry.get()
        self.Hosts = self.NumHostsEntry.get()
        self.IP = (self.NetIPEntry1.get() "." self.NetIPEntry2.get() "." self.NetIPEntry3.get() "." self.NetIPEntry4.get())
        self.IP_Assignment()
        self.write_json()
        self.ycor  = int(1)
        if self.ycor == 6:
            self.xcor  = int(1)
            self.ycor = int(1)
            self.AddButton.grid(row=self.xcor, column=self.ycor 1, padx=150, pady=0)
            self.NetworkSetup = Tk()

            

    def IP_Assignment(self):
        self.TotalInterDevs = int(self.NumInterDeviceEntry.get())
        self.TotalHosts= int(self.NumHostsEntry.get())
        self.TotalDevs = (self.TotalInterDevs self.TotalHosts)
        self.Subnet = ""
        if self.TotalDevs <= 254  and self.TotalDevs >= 127:
            self.Subnet = "255.255.255.0"
        if self.TotalDevs <= 126 and self.TotalDevs >= 63:
            self.Subnet = "255.255.255.128"
        if self.TotalDevs <= 62 and self.TotalDevs >= 31:
            self.Subnet = "255.255.255.192"
        if self.TotalDevs <= 30 and self.TotalDevs >= 15:
            self.Subnet = "255.255.255.224"
        if self.TotalDevs <= 14 and self.TotalDevs >= 7:
            self.Subnet = "255.255.255.240"
        if self.TotalDevs <= 6 and self.TotalDevs >= 3:
            self.Subnet = "255.255.255.248"
        if self.TotalDevs <= 2:
            self.Subnet = "255.255.255.252"
        self.Octet1 = int(self.NetIPEntry1.get())
        self.Octet2 = int(self.NetIPEntry2.get())
        self.Octet3 = int(self.NetIPEntry3.get())
        self.Octet4 = int(self.NetIPEntry4.get())
        
        print(self.UsedIPs)  

    def Add_Network(self):

        self.NetworkSetup = Tk()
        self.NetworkSetup.geometry("1500x1000")
        self.NetworkSetup.title("Network Setup")

        self.Net = Label(self.NetworkSetup, text="Network Name: ", font=("Roboto", 10))
        self.NetEntry = Entry(self.NetworkSetup, font=("Roboto", 10), width=10)

        self.NetIP = Label(self.NetworkSetup, text="Network IP: ", font=("Roboto", 10))
        self.NetIPEntry1 = Entry(self.NetworkSetup, width=10, font=("Roboto", 10))
        self.NetIPEntry2 = Entry(self.NetworkSetup, width=10, font=("Roboto", 10))
        self.NetIPEntry3 = Entry(self.NetworkSetup, width=10, font=("Roboto", 10))
        self.NetIPEntry4 = Entry(self.NetworkSetup, width=10, font=("Roboto", 10))

        self.NumInterDevice = Label(self.NetworkSetup, text="Number of intermediary devices: ", font=("Roboto", 10))
        self.NumInterDeviceEntry = Entry(self.NetworkSetup, font=("Roboto", 10), width=10)

        self.NumHosts = Label(self.NetworkSetup, text="Number of hosts: ", font=("Roboto", 10))
        self.NumHostsEntry = Entry(self.NetworkSetup, font=("Roboto", 10), width=10)

        self.AddNetBtn = Button(self.NetworkSetup, text="Add Network", font=("Roboto", 10), bg="lightblue", fg="white", command=self.NetInfo)
        

        self.Net.grid(row=0, column=0, pady=50, padx=20)
        self.NetEntry.grid(row=0, column=1)
        self.NetIP.grid(row=1, column=0, pady=50, padx=20)
        self.NetIPEntry1.grid(row=1, column=1, padx=20, pady=30, sticky=W)
        self.NetIPEntry2.grid(row=1, column=2, padx=20, pady=30,sticky=W)
        self.NetIPEntry3.grid(row=1, column=3, padx=20, pady=30,sticky=W)
        self.NetIPEntry4.grid(row=1, column=4, padx=20, pady=30,sticky=W)
        self.NumInterDevice.grid(row=2, column=0, pady=50, padx=20)
        self.NumInterDeviceEntry.grid(row=2, column=1)
        self.NumHosts.grid(row=3, column=0, pady=100, padx=20)
        self.NumHostsEntry.grid(row=3, column=1)
        self.AddNetBtn.grid(row=4, column=1)

        self.NetworkSetup.mainloop()
    
    def Inspect(self):
        self.InspectNet = Tk()
        self.InspectNet.geometry("1500x1000")
        self.InspectNet.title("Network Setup")


        self.InspectNumInter = int(self.InterDevice)
        self.InspectNumHost = int(self.Hosts)

        self.InspectTabsFrame = Frame(self.InspectNet)

        self.InspectNetTab = Button(self.InspectTabsFrame, width=20, text="Network", font=("Roboto", 10), bg="lightblue", fg="white")
        self.LogicalTopology= Button(self.InspectTabsFrame, width=20, text="Logical Topology", font=("Roboto", 10), bg="lightblue", fg="white", command=self.Topology)
        self.Border = Canvas(self.InspectTabsFrame, width=1490, height=936, bg="lightgrey", borderwidth=3, relief="solid")

        self.InspectName = Label(self.Border, text=(self.NetName), font=("Roboto", 18), background="lightgrey")
        self.InspectIP = Label(self.Border, text=(self.IP), font=("Roboto", 12), background="lightgrey")
        self.InspectDevices = Listbox(self.Border, bg="white", font=("Roboto", 12))
        for i in range(self.TotalInterDevs):
            self.Octet4  = 1
            if self.Octet4 > 255:
                self.Octet3  = 1
                self.Octet4  = -255
            self.UsedIPs.append(str(self.Octet1)   "."   str(self.Octet2)   "."   str(self.Octet3)   "."   str(self.Octet4))  
        for i in range(self.TotalHosts):
            self.Octet4  = 1
            if self.Octet4 > 255:
                self.Octet3  = 1
                self.Octet4  = -255
            self.UsedIPs.append(str(self.Octet1)   "."   str(self.Octet2)   "."   str(self.Octet3)   "."   str(self.Octet4))

        self.InspectNetTab.grid(row=0, column=0)
        self.LogicalTopology.grid(row=0, column=1)
        self.Border.grid(row=1, column=0, columnspan=2)
        self.InspectName.grid(row=0, column=0, padx=10, pady=10, sticky=W)
        self.InspectIP.grid(row=1, column=0, padx=10, pady=10, sticky=W)
        self.InspectDevices.grid(row=2, column=0, pady=50, padx=100)

        self.InspectTabsFrame.grid(sticky=N)

        self.InspectNet.mainloop()
    
NetAppHomePG()

I've tried assigning user.json['networks'] to a for loop then putting all the label, buttons, and grid in that loop. I hoped this would've just looped through all of the networks under user.json['networks'].

CodePudding user response:

You stated you tried iterating over the values inside of user.json['networks'] but what I see in your code is for network in self.temp:. This is not the same thing.

To iterate over your data you should do something more like this:

import tkinter as tk


json_file = {"networks": [
    {"network name": "mynet", "Network IP": "192.168.0.0", "Subnet": "255.255.255.240", "Intermediary Devices": "2", "Hosts": "8"},
    {"network name": "NewNet", "Network IP": "10.0.0.100", "Subnet": "255.255.255.240", "Intermediary Devices": "1", "Hosts": "12"},
    {"network name": "pop", "Network IP": "192.168.2.10", "Subnet": "255.255.255.248", "Intermediary Devices": "1", "Hosts": "2"}]}


root = tk.Tk()
root.geometry("400x400")

for data in json_file['networks']:
    frame = tk.Frame(root)
    frame.pack()
    for key, value in data.items():
        tk.Label(frame, text=f'{key}: {value}', anchor="w").pack(fill='x')


root.mainloop()

Results:

enter image description here

  • Related