Search code examples
pythonfunctionmethodsmodulepython-module

Calling variables from one method to another in Python


SO this is the the first project I've taken up outside of the beginners tutorials. I've made two modules so far, one that creates a URL from user input. It concatenates a bunch of things together and uses user input to save things like dates and times to form the whole URL, I've tested this and it's working fine.

I've also created a small GUI that takes two pieces of input and displays them inside a textbox, this is also working fine.

I have a function in my GUI that records the text from the text entry boxes. What i would like is for the entered text to be used as my user input inside the other module. Do i need to to return each text entry as a separate call? Or can i keep the two boxes but access the variables saved as each function call happens?

def click():
    entered_text = textEntry.get()
    entered_text2 = textEntry2.get()
    output.delete(0.0,END)
    output.insert(END, entered_text +'\n'+ entered_text2)
    # This is the end of this function with no return

and here is the part i would like to be used to form part of the URL

def create_MY_URL():
    startDate = input("Enter intraday start date dd/mm/yyyy: ")
    startTime = input("Enter start time hh:mm: ")
    finishDate = input("Enter intraday finish date dd/mm/yyyy: ")
    finishTime = input("Enter finish time hh:mm: ")
    #there is plenty more of this function, it is returned at the end

So would i need two calls to click() for each piece of information in order to use it as a "startDate" and "FinishDate"?


Solution

  • This is where importing will help you, assuming you have two .py files named gui.py and create_url.py you would import the functionality from your create_url.py into your gui.py

    create_url.py

    def create_MY_URL(start_date, end_date):  # accept the variables as input
        startDate = start_date  # assign the variables rather than accept an input
        startTime = input("Enter start time hh:mm: ")
        finishDate = end_date
        finishTime = input("Enter finish time hh:mm: ")
        #there is plenty more of this function, it is returned at the end
    

    With gui.py you would import create_url and you can then call functions which you have built into create_url.py

    import create_url  # name of .py file
    
    def click():
        entered_text = textEntry.get()
        entered_text2 = textEntry2.get()
        output.delete(0.0,END)
        output.insert(END, entered_text +'\n'+ entered_text2)
    
        create_MY_URL(entered_text, entered_text2)  # call your function and pass your two inputs
        # create_MY_URL will do stuff here
    

    In this example both .py files exist in the same directory