Python Forum
Help me understand this... (Classes and self).
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me understand this... (Classes and self).
#2
If written this way, may be easier to understand
has default values for title, width, height, xpos and ypos
** Note ** Uses f-string which requires python 3.6 or newer.
In example title default is overridden.
import time
import tkinter as tk
    
  
class Application(object):
    """
        Initialization with default values for title, width, height, xpos, ypos
        any of which can be overidden.

        Uses f-string which requires python 3.6 or newer.
    """
    def __init__(self, parent, title='Application', width=200, height=100, xpos=200, ypos=200):
        self.parent = parent

        self.parent.title(title)
        self.parent.geometry(f"{width}x{height}+{xpos}+{ypos}")

        self.time_var = tk.StringVar()
        self.build()
          
    def build(self):
        tk.Label(self.parent, textvariable=self.time_var, width=10, fg='blue',
            font=('Helvetica', 30, 'bold')).pack(expand=True)
              
        self.update_time()
          
    def update_time(self):
        self.time_var.set(time.strftime('%H:%M:%S'))
        self.parent.after(1000, self.update_time)


def main():
    # Create an instance of Tk named main_win
    main_win = tk.Tk()
    #override default title
    title='The Time'
    # create instance of Application (with initialization variables)      
    app = Application(main_win)

    # standard tkinter mainloop      
    main_win.mainloop()


if __name__ == '__main__':
    main()
Reply


Messages In This Thread
RE: Help me understand this... (Classes and self). - by Larz60+ - Mar-12-2019, 08:58 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand classes menator01 7 3,478 Oct-27-2019, 04:26 PM
Last Post: menator01
Question Helping understand classes Miraclefruit 10 6,536 Nov-27-2017, 01:58 PM
Last Post: Windspar
  Using classes? Can I just use classes to structure code? muteboy 5 5,236 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020