APARNA
APARNA

Reputation: 29

Function Value Retrieval: how to access the value of a variable outside a function. and how use that value in another function?

I've written a code to print the IP address corresponding to the mac address given. the thing is the IP is inside the retrieve_input function. how can i get the IP value outside the retrieve_input function? Here is my code.

from tkinter import *
import subprocess

window = Tk()
window.title("Welcome..")
a = str(subprocess.getoutput(["arp", "-a"]))
print(a)
text=a
def retrieve_input():                   #retrive input and fetches the IP
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2]
        print(ip)

window.geometry('900x700')
lbl1=Label(window, text="MAC ADDRESS",width=15,height=2,font=2)
lbl1.grid(column=0, row=0)
txt=Text(window, width=25,height=1)
txt.grid(column=1, row=0)
btn = Button(window, text="CONVERT",fg="black",bg="light 
grey",width=15,font=4,height=2,command=lambda:(retrieve_input())
btn.grid(column=1, row=2)

window.mainloop()

Upvotes: 1

Views: 100

Answers (2)

Meric Ozcan
Meric Ozcan

Reputation: 858

def retrieve_input():                   #retrive input and fetches the IP
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2]
        return ip
    else:
        return False

ip_value = retrieve_input()

You can use return IP if you don't want to use global variables, with that function can return IP adres that you would like to use.

However there is another approach if you you know Python Classes and attributes.

class IpValues:

    def __init__ (self):
        # Initialize and use it as constructor
        self.ip = None
        pass

    def retrieve_input(self):                   
        # retrive input and fetches the IP
        inputValue=txt.get(1.0, "end-1c")
        ext = inputValue
        if (inputValue in a and inputValue != ''):
            nameOnly = text[:text.find(ext) + len(ext)]
            self.ip = nameOnly.split()[-2]


ip_values_object = IpValues()
ip_values_object.retrieve_input()
print(ip_values_object.ip)

Upvotes: 2

glhr
glhr

Reputation: 4547

You can make ip a global variable like this:

def retrieve_input():
  global ip #declare ip as a global variable                   
  ip = "0.0.0.0" #assign a value to ip

retrieve_input()
print(ip) #access the value of ip outside the function

In your code, it would look like this:

def retrieve_input():
    global ip #declare ip as a global variable
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2] #assign a value to ip
        print(ip)

Upvotes: 0

Related Questions