Andrew Andrew - 3 months ago 15
Python Question

Using variable in one script in another to avoid NameError

I am trying to grab user input (

input1
) from main.py and use it in runAnalytics.py.

main.py

import runAnalytics
import tkinter
import os
import centerWindow

global input1

loadApplication = tkinter.Tk()
loadApplication.title("Stock Analytics")
loadApplication.geometry("1080x720")

label1 = tkinter.Label(loadApplication, text = "Ticker")
input1 = tkinter.Entry(loadApplication)

loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run)

centerWindow.center(loadApplication)

loadAnalytics.pack()
label1.pack()
input1.pack()

loadApplication.mainloop()


runAnalytics:

from yahoo_finance import Share
import tkinter
import os
import centerWindow

def run():
ticker = input1

loadAnalytics = tkinter.Tk()
loadAnalytics.title("$" + ticker + " Data")
loadAnalytics.geometry("1080x720")

print ("Price per share: " + ticker.get_price())

ticker.refresh()
print ("Price per share: " + ticker.get_price())

print("The dividend yield is: " + ticker.get_dividend_yield())

print("The 52 week low is: " + ticker.get_year_low())
print("The 52 week high is: " + ticker.get_year_high())
print("The volume is: " + ticker.get_volume())

print("The previous close was: " + ticker.get_prev_close())
print("The previous open was: " + ticker.get_open())

loadAnalytics.mainloop()


The error message that I am seeing reads as follows;

"Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\MyName\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\MyName\Documents\Python Projects\MarketData\runAnalytics.py", line 8, in run
ticker = input1
NameError: name 'input1' is not defined

Answer

The global keyword is not doing what you are expecting it to. It should be used inside a function to say that you will refer to a variable declared outside of the function. To solve your problem you should import the variable (but it is not a good pattern I would say)

from main import input1