0

I am a tk newbie and am having trouble importing classes and having them inherit frames. If I stack all the code in one file it works. Something like (I found this on Github sorry for no attribution),

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

However, if I try to break up the code so I can import modules in directories and subdirectories I get errors because I do not understand how to pass the frames. For example, if I put the Clock class in a file modules/clock/Clock.py (yes I am including __init__.py in all directories) and change the code to

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

I get the error

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

NameError: name 'Frame' is not defined

How can I set up the code so I can break up code into modules and pass the tk.Frame?

superhero
  • 185
  • 3
  • 16
  • Have you put the `from tkinter import Frame` at the top of the Clock.py file? – j_4321 Jun 20 '18 at 21:26
  • @j_4321 when I do that I get a `self.clock = Clock(self.topFrame) TypeError: 'module' object is not callable` on the line where I instantiate the clock. – superhero Jun 20 '18 at 22:09
  • It's because both your module and your class are named `Clock`. Given your import statement, what you want to do is `self.clock = Clock.Clock(self.topFrame)` (or you can change your import statement instead `from modules.clock.Clock import Clock`) – j_4321 Jun 20 '18 at 22:17

0 Answers0