Tuesday 14 April 2015

Using Tkinter with a class method

In this post I did a remake of another previous example,



 but in this case I'm using a class method mixed with the previous way of using the "root = Tk()", well in this case this was just a simple way to change the title, which can be seen in the final parts of the code.

from Tkinter import *

class HH_set:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.songLabel = Label(frame, text = "Spoon - 'Got Nuffin'. Available this summer!")
        self.songLabel.pack()

        self.xclmLabel = Label(frame, text = "Yeah!")
        self.xclmLabel.pack()

        self.hearButton = Button(frame, text = "Let's hear it", state = DISABLED)
        self.hearButton.pack(side = LEFT)

        self.seeButton = Button(frame, text = "Let's see", state = DISABLED)
        self.seeButton.pack(side = RIGHT)

        self.tuneButton = Button(frame, text = "Tune", command = self.printMessage)
        self.tuneButton.pack(side = RIGHT)

    def printMessage(self):
        print "Channel open"

root = Tk()
root.title("Happy Hour")

base_object = HH_set(root)

root.mainloop()

At the begining of the class HH_set, it's defined the function "__init__" with the arguments "self" and "master". After that a frame its created and packed.

frame = Frame(master)
frame.pack()

The labels and buttons are created with a "self." before the name assigned, like:

self.songLabel = Label(frame, text = "Spoon - 'Got Nuffin'. Available this summer!")
self.songLabel.pack()

That's the only variant, which in the first posts is not used because they were pretty straightforward and easy to grasp.

Almost in the end, there is the use of the class "HH_set" (which could've been any other name) in order to create all that was in 'contents'.

base_object = HH_set(root)

No comments:

Post a Comment