简体   繁体   English

如何以不会给我错误的方式使用 pygame 导入?

[英]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.我是 python 的新手,所以我为这个问题背后可能的愚蠢道歉。

I have two files that I am using - File1 and File2我有两个正在使用的文件 - File1File2

Within File1 I have variable X defined, this file alters the value of X throughout my game and imports specific objects from File2File1中我定义了变量X ,这个文件在我的游戏中改变X的值并从File2导入特定对象

Within File2 I have the line from File1 import X without using the variable at all within that File.File2中,我有from File1 import X的行,而在该文件中根本没有使用变量。

Hitting run comes up with an error stating that it cannot import a function from File2:点击运行会出现一个错误,指出它无法从 File2 导入 function:

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:如果不是像我以前那样从File1导入特定对象,而是简单地输入from File2 import *那么我的游戏将运行一小会儿,直到产生以下错误:

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 .您可以从File2将变量x传递给 function ,而不是直接从File1导入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.为此,您需要在File2中执行File1中的代码,这很容易通过在 File2 中设置File2来完成,其中包含所需的所有函数和变量。

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:然后,在 File1 中导入这个File1并从那里运行代码:

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.如果没有您的实际代码,很难解释或给出示例,但我希望这有助于使我的意思更加清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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