3

I am using Python 3.7. I have a simple 2-files program. They are both under the same directory.

~/myapp/
   settings.py
   button.py

settings.py has basic constant variables:

# 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 has the following:

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()

Whenever I run the program, I would get the error below:

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)

However, when I change it to import settings, it works.

I am curious as to why the usage from . relative import doesn't work in this case?

s2000coder
  • 913
  • 2
  • 15
  • 23
  • Have you tried just "import settings"? doesn't directly answer the question. – Kenny Ostrom Feb 24 '19 at 00:07
  • 3
    This indicates that you cannot use relative dot notation in a command line execution (__main__) https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time You can only use relative within a package. It's a SO answer, and I don't have the actual python doc confirmation. Looks convincing though. – Kenny Ostrom Feb 24 '19 at 00:09
  • Normally this form of usage is `from import `, e.g.: `from settings import *`. – Kingsley Feb 24 '19 at 23:39

0 Answers0