0

我是一个tk新手,在导入类和让它们继承框架时遇到了麻烦。如果我将所有代码堆叠在一个文件中,它就可以工作。类似的东西(我在 Github 上找到了这个,抱歉没有注明出处),

imports...

class Clock(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, bg='black')
        code....
class FullscreenWindow:
    def __init__(self):
        self.tk = Tk()
        self.tk.configure(background='black')
        self.topFrame = Frame(self.tk, background = 'black')
        self.bottomFrame = Frame(self.tk, background = 'black')
        self.topFrame.pack(side = TOP, fill=BOTH, expand = YES)
        self.bottomFrame.pack(side = BOTTOM, fill=BOTH, expand = YES)
        self.state = False
        self.tk.bind("<Return>", self.toggle_fullscreen)
        self.tk.bind("<Escape>", self.end_fullscreen)
        # clock
        self.clock = Clock(self.topFrame)

w = FullscreenWindow()
w.tk.mainloop()

但是,如果我尝试分解代码以便可以在目录和子目录中导入模块,则会出现错误,因为我不明白如何传递帧。例如,如果我将 Clock 类放在一个文件中modules/clock/Clock.py(是​​的,我包含__init__.py在所有目录中)并将代码更改为

from modules.clock import Clock

class FullscreenWindow:
        def __init__(self):
            self.tk = Tk()
            self.tk.configure(background='black')
            self.topFrame = Frame(self.tk, background = 'black')
            self.bottomFrame = Frame(self.tk, background = 'black')
            self.topFrame.pack(side = TOP, fill=BOTH, expand = YES)
            self.bottomFrame.pack(side = BOTTOM, fill=BOTH, expand = YES)
            self.state = False
            self.tk.bind("<Return>", self.toggle_fullscreen)
            self.tk.bind("<Escape>", self.end_fullscreen)
            # clock
            self.clock = Clock(self.topFrame)

w = FullscreenWindow()
w.tk.mainloop()

我得到错误

  File "modules\clock\Clock.py", line 8, in <module>
    class Clock(Frame):

NameError: name 'Frame' is not defined

如何设置代码以便将代码分解为模块并传递 tk.Frame?

4

0 回答 0