ImportError:无法从“ __main__”导入名称“设置”

时间:2019-02-23 23:42:56

标签: python pygame python-import

我正在使用Python 3.7。我有一个简单的2文件程序。它们都在同一目录下。

~/myapp/
   settings.py
   button.py

settings.py具有基本常量变量:

# Define color (R, G, B) tuples
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

button.py具有以下内容:

import pygame as pg

from . import settings

class Button:
    def __init__(self, rect, command):
        self.rect = pg.Rect(rect)
        self.image = pg.Surface(self.rect.size).convert()
        self.image.fill((255,0,0))
        self.function = command

    def get_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
            self.on_click(event)

    def on_click(self, event):
        if self.rect.collidepoint(event.pos):
            self.function()

    def draw(self, surf):
        surf.blit(self.image, self.rect)

def button_was_pressed():
    print('button_was_pressed')

screen = pg.display.set_mode((800,600))
done = False
btn = Button(rect=(50,50,105,25), command=button_was_pressed)

if __name__ == '__main__':
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            btn.get_event(event)
        btn.draw(screen)
        pg.display.update()

每当我运行该程序时,都会出现以下错误:

Traceback (most recent call last):
  File "c:/Users/s2000coder/Desktop/myapp/button.py", line 7, in <module>
    from . import settings
ImportError: cannot import name 'settings' from '__main__' (c:/Users/s2000coder/Desktop/myapp/button.py)

但是,当我将其更改为import settings时,它可以工作。

我很好奇为什么在这种情况下使用from .相对导入无效?

0 个答案:

没有答案