Home > Back-end >  Tkinter class object issues
Tkinter class object issues

Time:12-18

I am working on a somewhat complicated Tkinter app that has multiple classes that act as windows. I am only going to share the needed parts to figure out why I am messing up.

I am trying to display a digital clock on the start page above some buttons.

class StartPage(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller

        clock = Label(self, font = ('calibri', 40, 'bold'),
                                  background = 'purple',
                                  foreground = 'white')
        clock.pack()
        self.time()

    def time(self):
        string = strftime('%H:%M:%S %p')
        clock.config(text = string)
        clock.after(1000, time)

The error code: clock.config(text = string) NameError: name 'clock' is not defined

I have played around with different things like adding self.clock.config, but I havent figured it out yet.

I just updated it trying to set the clock label as its own function in StartPage.

    def time(self):
        string = strftime('%H:%M:%S %p')
        self.clockLabel.config(text = string)
        self.clockLabel.after(1000, time)

    def clockLabel(self):
        clock = Label(self, font = ('calibri', 40, 'bold'),
                      background = 'purple',
                      foreground = 'white')
        clock.pack()

in the init, i still have self.time().

SOLVED

class StartPage(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        
        self.clockLabel()
        self.time()

    def time(self):
        string = strftime('%H:%M:%S %p')
        self.clock.config(text = string)
        self.clock.after(1000, self.time)

    def clockLabel(self):
        self.clock = Label(self, font = ('calibri', 40, 'bold'),
                      background = 'purple',
                      foreground = 'white')
        self.clock.pack()
        

[![Picture of working clock][1]][1] [1]: https://i.stack.imgur.com/nPMl4.png

CodePudding user response:

The issue here may be related to the name of a variable or function and how they are referenced after they are declared. We performed the following to make the class attributes recognizable

  1. Start every class attribute with self
  2. Initialize the clock attribute with a None value and set it to a label in a separate function:
def packClockLabel(self):
    self.clock = Label(self, font = ('calibri', 40, 'bold'),
                      background = 'purple',
                      foreground = 'white')
    clock.pack()
  • Related