1

Because my python script got to big i split it onto multiple files. Then i imported the needet files into my main file.

I then want to open a class that is defined in the main file out of the inculded file. But it always tells me that the class which is defined in the main file is not defined.

Here is the main file:

try:
     import Tkinter as tk
except ImportError:
     import tkinter as tk

try:
     import ttk
     py3 = False
except ImportError:
     import tkinter.ttk as ttk
     py3 = True


# page classes import   
from travel import PageTravel
from contact import PageContact
from dangers import PageDangers



#Main Window wird gestartet.
class PTools(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        #self.geometry("%dx%d"%(self.winfo_screenwidth()-200,self.winfo_screenheight()-200))
        self._frame = None        
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack(anchor='center')    


class StartPage(ttk.Frame):
    def __init__(self, master):      
        s=ttk.Style()
        s.theme_use('winnative')
        ttk.Frame.__init__(self, master)

        #Frames werden geöffnet.
        alles=ttk.Frame(self)
        alles.pack(padx=100)
        version=ttk.Frame(self)
        version.pack(anchor='e')


        self.button1 =ttk.Button(alles, text ="Test1",command=lambda: master.switch_frame(PageTravel),width=50) #command linked
        self.button1.pack()
        self.button2=ttk.Button(alles, text ="Test2",command=lambda: master.switch_frame(PageDangers),width=50)
        self.button2.pack()
        self.button4=ttk.Button(alles, text ="Test3",command=lambda: master.switch_frame(PageContact),width=50)
        self.button4.pack()

if __name__ == "__main__":
    app = PTools()
    app.mainloop()

As you can see i import PageTravel,PageContact and PageDanger. Also in this ffine i define the class StartPage. This is PageContact which is called when pressing the button:

try:
     import Tkinter as tk
except ImportError:
     import tkinter as tk

try:
     import ttk
     py3 = False
except ImportError:
     import tkinter.ttk as ttk
     py3 = True

class PageContact(ttk.Frame):

    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        #label = ttk.Label(self, text="Fragen, Anregungen, Bugs?\n Per Mail bin ich unter ")
        #label.pack(side="top", fill="x", pady=10)

        button = ttk.Button(self, text="Back to Main Menu",
                           command=lambda: master.switch_frame(StartPage))
        button.pack()

Now this is an entirely different file which i can call because i imported it. I then try to go back to the MainPage by calling "StartPage" again. But here it tells me that start page is not known.

When i try to import startpage with

from mainfile import StartPage

It doesnt work.

Traceback without the line:

Exception in Tkinter callback Traceback (most recent call last):
File "C:\Users\Odatas\AppData\Local\Continuum\anaconda3\lib\tkinter__init__.py", line 1705, in call return self.func(*args) File "C:\Users\Odatas\Documents\Python Scripts\contact.py", line 36, in command=lambda: master.switch_frame(StartPage)) NameError: name 'StartPage' is not defined


Traceback with the line:

File "<ipython-input-18-2db7e63f920e>", line 1, in <module>
 runfile('C:/Users/Odatas/Documents/Python Scripts/patrickstools2.py', wdir='C:/Users/Odatas/Documents/Python Scripts') 
File "C:\Users\Odatas\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
 execfile(filename, namespace)
File "C:\Users\Odatas\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
 exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Odatas/Documents/Python Scripts/patrickstools2.py", line 23, in <module>
 from contact import PageContact
File "C:\Users\Odatas\Documents\Python Scripts\contact.py", line 20, in <module>
 from patrickstools2.py import StartPage
File "C:\Users\Odatas\Documents\Python Scripts\patrickstools2.py", line 23, in <module>
 from contact import PageContact
ImportError: cannot import name 'PageContact' from 'contact'
(C:\Users\Odatas\Documents\Python Scripts\contact.py
stovfl
  • 14,998
  • 7
  • 24
  • 51
Odatas
  • 178
  • 2
  • 13
  • The Error is `from contact import PageContact`. It's not clear which part of your code is which file. Please [edit] your Question and add the *.py filename. **Which** ist `patrickstools2.py`. – stovfl Jan 31 '19 at 14:38
  • I cant edit my question anymore it always tells me my code is wrong formated. The first code snippet is patrickstools2.py the second one is contact.py – Odatas Jan 31 '19 at 14:47
  • Possible duplicate of [Python circular importing?](https://stackoverflow.com/questions/22187279/python-circular-importing) – stovfl Jan 31 '19 at 15:00

1 Answers1

2

Without the import statement in the contact module, there is no way of it knowing the existence of StartPage.

When i try to import startpage with

from mainfile import StartPage

It doesnt work.

Whats happening, is that at the time of the second import, StartPage really doesn't exists, since the execution hasn't reached that part of the code.

What you can do to address this issue, is use import contact and contact.PageContact in mainfile, and, import mainfile and mainfile.StartPage in contact, like this.

try:
     import Tkinter as tk
except ImportError:
     import tkinter as tk

try:
     import ttk
     py3 = False
except ImportError:
     import tkinter.ttk as ttk
     py3 = True


# page classes import   
from travel import PageTravel
import contact
from dangers import PageDangers



#Main Window wird gestartet.
class PTools(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        #self.geometry("%dx%d"%(self.winfo_screenwidth()-200,self.winfo_screenheight()-200))
        self._frame = None        
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack(anchor='center')    


class StartPage(ttk.Frame):
    def __init__(self, master):      
        s=ttk.Style()
        s.theme_use('winnative')
        ttk.Frame.__init__(self, master)

        #Frames werden geöffnet.
        alles=ttk.Frame(self)
        alles.pack(padx=100)
        version=ttk.Frame(self)
        version.pack(anchor='e')


        self.button1 =ttk.Button(alles, text ="Test1",command=lambda: master.switch_frame(PageTravel),width=50) #command linked
        self.button1.pack()
        self.button2=ttk.Button(alles, text ="Test2",command=lambda: master.switch_frame(PageDangers),width=50)
        self.button2.pack()
        self.button4=ttk.Button(alles, text ="Test3",command=lambda: master.switch_frame(contact.PageContact),width=50)
        self.button4.pack()

if __name__ == "__main__":
    app = PTools()
    app.mainloop()
try:
     import Tkinter as tk
except ImportError:
     import tkinter as tk

try:
     import ttk
     py3 = False
except ImportError:
     import tkinter.ttk as ttk
     py3 = True

import mainfile

class PageContact(ttk.Frame):

    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        #label = ttk.Label(self, text="Fragen, Anregungen, Bugs?\n Per Mail bin ich unter ")
        #label.pack(side="top", fill="x", pady=10)

        button = ttk.Button(self, text="Back to Main Menu",
                           command=lambda: master.switch_frame(mainfile.StartPage))
        button.pack()
Community
  • 1
  • 1
  • Thanks this right here solved the problem. I knew there was an easy fix i just wasnt able to pin it down. Thank you very much. – Odatas Jan 31 '19 at 14:57