从另一个脚本中调用主程序中的类

时间:2019-01-31 14:07:32

标签: python python-3.x tkinter

因为我的python脚本很大,所以将其拆分为多个文件。 然后,我将Needet文件导入到我的主文件中。

然后,我想从已插入文件中打开一个在主文件中定义的类。但是它总是告诉我在主文件中定义的类没有定义。

这是主文件:

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

如您所见,我导入了PageTravel,PageContact和PageDanger。同样在此定义中,我定义了类StartPage。这是在按下按钮时调用的PageContact:

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

现在这是一个完全不同的文件,我可以调用它,因为我已将其导入。然后,我尝试通过再次调用“ StartPage”返回到MainPage。但是这里告诉我起始页面未知。

当我尝试使用

导入起始页时
from mainfile import StartPage

它不起作用。

无行追踪:

  

Tkinter回调Traceback中的异常(最近一次调用最后一次):
  文件   “ C:\ Users \ Odatas \ AppData \ Local \ Continuum \ anaconda3 \ lib \ tkinter__init __。py”,   第1705行,在致电       返回self.func(* args)文件“ C:\ Users \ Odatas \ Documents \ Python Scripts \ contact.py”,第36行,在       command = lambda:master.switch_frame(StartPage))NameError:名称“ StartPage”未定义


  

以下行的跟踪:

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

1 个答案:

答案 0 :(得分:1)

在contact模块中没有import语句,无法知道StartPage的存在。

  

当我尝试导入起始页时

     

from mainfile import StartPage

     

它不起作用。

正在发生的情况是,在第二次导入时,StartPage确实不存在,因为执行尚未到达代码的那一部分。

解决此问题的方法是,在主文件中使用import contactcontact.PageContact,并在联系方式中使用import mainfilemainfile.StartPage

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