2

I faced a problem connected with import in Python. I've implemented a simple calculator, there is no much code but I'd like to separate my logic from GUI (implemented with Tkinter).

My logic file calc_logic.py:

import enum
from calculator import*
....

My GUI file calculator.py:

from tkinter import *
from calc_logic import *
...

I get an Error:

Traceback (most recent call last):
  File "/Users/vladsokolovskii/Desktop/python/gui_project/calculator.py", line 4, in <module>
    from calc_logic import *
  File "/Users/vladsokolovskii/Desktop/python/gui_project/calc_logic.py", line 2, in <module>
    from calculator import *
  File "/Users/vladsokolovskii/Desktop/python/gui_project/calculator.py", line 25, in <module>
    clear_button = Button(win, text = 'C', padx = 20, pady = 15, command = button_clear)
NameError: name 'button_clear' is not defined

Definition of button_clear() in calc_logic.py:

...
def button_clear():
        display.delete(0, END)
        display.insert(0, '0')
...

The first reference to button_clear() in calculatro.py

...
clear_button = Button(win, text = 'C', padx = 20, pady = 15, command = button_clear)
...

I tried:

clear_button = Button(win, text = 'C', padx = 20, pady = 15, command = lambda: button_clear())

It didn't give me the Error nor worked -_-

I tried to change my code in different ways but never succeed.

Could you please explain to me where the problem is, I'm new to Python and I can't find a similar problem on the Internet, I'm sure that there is a solution but I just don't know how to google it correctly...

Thanks!

Machavity
  • 30,841
  • 27
  • 92
  • 100
Sinking
  • 95
  • 8
  • 1
    When `calculator` is being imported in `calc_logic.py`, `button_clear()` function is not defined yet. Try refactoring your code not importing `calculator` in `calc_logic.py`. – acw1668 Jan 30 '20 at 10:55
  • This is a cyclic import. See https://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python to solve this problem – Demian Wolf Feb 19 '20 at 21:55

0 Answers0