将类导入为通配符Python时出现全局名称错误

时间:2014-07-22 03:13:06

标签: python tkinter nameerror attributeerror

我正在尝试使用tkinter制作多个“页面”GUI,但实际上找不到一个好的方法。我使用grid_forget并在方法中分离“页面”,它就像一个魅力。但是我试图将这些方法分成一个单独的文件,以使一切变得更清晰,但是当我尝试使用我的主文件/类中的所有小部件运行其中一个方法时,我一直收到全局名称错误。

    Traceback (most recent call last):
  File "C:/Users/Derek/PycharmProjects/whites/Main.py", line 3, in <module>
    from screens import *
  File "C:\Users\Derek\PycharmProjects\whites\screens.py", line 4, in <module>
    import Main
  File "C:\Users\Derek\PycharmProjects\whites\Main.py", line 54, in <module>
    app = Application(master=main, w=main.winfo_width(), h=main.winfo_height())
  File "C:\Users\Derek\PycharmProjects\whites\Main.py", line 20, in __init__
    home_screen(self,True)
NameError: global name 'home_screen' is not defined

我也尝试导入import screens,并试图运行screens.home_screen(self,True)并且那个

AttributeError: 'module' object has no attribute 'home_screen'

即使它确实

Example Main.py

from screens import *
import globals


class Application(tk.Frame):

    globals.init()


    def __init__(self, w, h, master=None):

        tk.Frame.__init__(self, master)
        self.grid()

        self.window_width = w
        self.window_height = h

        home_screen(self,True)
        query_screen(False)
        res_screen(False)
        settings_screen(False)

screens.py

import tkinter as tk
import globals
import Main


def home_screen(self, state):
     *define widgets for this "screen"

[编辑] 以下是完整文件的副本。screensMainglobals

[编辑:2] 所以我改变了代码来尝试不同的解决方案,它基本上是相同的错误。如果我尝试将screens.py转换为类并将其初始化为对象但没有任何内容,则模块对象没有属性。所以我猜这意味着它根本就不是python而且我的项目设置已经更糟糕了

2 个答案:

答案 0 :(得分:0)

您定义:

def home_screen(self, state):

但它不属于任何一类!

从功能签名中删除self,仅使用state变量调用

编辑:

如果您创建main.py:

from screens import *

class Application():

    def __init__(self):
        home_screen(True)


# then later on
a = Application() # this will print 'True'

并在文件screens.py中:

def home_screen(state):
    print state

它会起作用(假设两者都在同一目录中)。

答案 1 :(得分:0)

解决方案是运行screens.py而不是main.py.为什么这是我不知道,但它仍然最终符合我的目标。如果有人想要权衡它。

<强> [编辑]

最终解决方案,改变程序启动的方式。现在运行得很好。

if __name__ == "__main__":
    main = tk.Tk()
    main.wm_title("White's Canoe Livery")
    main.state("zoomed")
    main.update()
    # print(main.winfo_width())
    app = Application(master=main, w=main.winfo_width(), h=main.winfo_height())
    app.mainloop()