函数值检索:如何在函数外部访问变量的值。以及如何在另一个函数中使用该值?

时间:2019-03-25 05:51:34

标签: python tkinter

我已经写了一个代码来打印与给定的mac地址相对应的IP地址。问题是IP处于retrieve_input函数内部。我怎样才能获取IP地址的外部值? 这是我的代码。

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()

2 个答案:

答案 0 :(得分:2)

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()

如果您不想使用全局变量,则可以使用return IP,该函数可以返回您要使用的IP adres。

但是,如果您了解Python类和属性,还有另一种方法。

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)

答案 1 :(得分:0)

您可以像这样将ip设置为全局变量:

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

在您的代码中,它看起来像这样:

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)