简体   繁体   中英

How can I use pygame imports in a way that doesn't give me an error?

I am new to python so I apologize for the likely stupidity behind this question.

I have two files that I am using - File1 and File2

Within File1 I have variable X defined, this file alters the value of X throughout my game and imports specific objects from File2

Within File2 I have the line from File1 import X without using the variable at all within that File.

Hitting run comes up with an error stating that it cannot import a function from File2:

ImportError: cannot import name 'draw_panel' from partially initialized module 'File2' (most likely due to a circular import)

If instead of importing specific objects including that one from File1 like i was previously doing, I was to simply type from File2 import * then my game would run for a short while until producing the following error:

NameError: name 'draw_panel' is not defined

I apologize for the vague structure of this question, I am open to any alternative suggestions on importing. I simply need to be able to use the variable that is also altered within the first File.

Instead of importing x from File1 directly, you can pass a variable to a function from File2 the variable x .

To accomplish this, you would need to execute the code from File2 within File1 , which would be most easily accomplished by setting up a class in File2 which contains all your functions and variables needed.

For a very basic example:

class TestClass:
    def __init__(self):
        self.test_variable = 2

    def multiply_test_variable(self, x):
        self.test_variable *= x

Then, import this class in File1 and run the code from there:

from File2 import TestClass

x = 3

test_object = TestClass()

print(test_object.test_variable)
test_object.multiply_test_variable(x)
print(test_object.test_variable)

It's hard to explain or give examples without your actual code but I hope this helps make it somewhat clear what I mean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM