NameError: name 'a' is not defined
p1.py
file and
tkinter
p1.py
has a file p2.py
to run via command.
The ultimate goal is to read the file path of a file from the p2.py
file.
First, in p1.py
, create a function fileopen()
that returns the path of the file obtained using tkinter.filelog.askopenfilename
.
def fileopen():
filepath = askopenfilename(parent=window, filetype=(("all files", "*.*")))
In addition, fileopen()
is used to create a variable a
, a
is declared as a global variable with global
, and a function to import p2.py
file. This function functions as a command that runs when you click a button created with tkinter
.
def c_color_rs_l():
global a
a=fileopen()
print(a)
import p2
If you run c_color_rs_l
afterwards, you can see that a
contains the filepath normally.
However, if p2 is imported, import p2
and a
is received, then a of the called p1 is not defined.
I think the reason why this doesn't work is probably because when p1 is imported from p2, a is not defined because it is imported without going through the process of [1]~[2]. How can I fix it? Python masters...I've been thinking about it and fixing it for a while, but I'm not sure.
Another approach I've tried is to import tkinter.filedialog
into p2 and run askopenfilename
to read the file path well.
Is the GUI a thread problem after that? (I don't know exactly what the problem is yet.) I couldn't run asynchronously because it collided with an existing function. askopenfilename
is not executed once, it is executed indefinitely.
I don't know why we need the Globurn variable.
from p1 import fileopen
def myfunction():
path = fileopen()
# I play with the path whether I read the file or not.
Are you saying that you are using import p2
and p2.a
in another file? The root namespace of p2.py
must have a variable named a
.
The global variable is not so good. I have a good habit of coding in a way that does not use global variables.
When you ask a question, please clarify the gist of the question. In many cases, problems will be solved in the process of narrowing down what I don't know. Then, when you ask questions, try to create a minimum code that reproduces the problem. When I don't know what I don't know, it's hard to ask questions and get good answers.
You can approach it with a global variable, but you can also approach it with a static variable.
Do something similar to the static keyword in Java or c#.
class StaticVars:
MyVar = 0 # Used as a kind of static variable. In fact, in Python, variables are managed as dict. This is unique within the vm.
Set StaticVars.myVar = 1 #1
import p1
print(p1.StaticVars.myVar) #1 is output.
© 2024 OneMinuteCode. All rights reserved.