Monday 13 April 2015

Using a class to create a button

This time I'm using something that is new for me (at least when I'm writing this post :P), which is the use of a class (along with functions) in order to create a button with TKinter. The result is similar to one of the first examples that I've posted, but the code is more complex.


from Tkinter import *
def frame(root, side):
    # wf : Window Frame
    wf = Frame(root)
    wf.pack(side=side, expand=YES, fill=BOTH)
    return wf

def button(root, side, text, command=None):
    btn = Button(root, text=text, command=command)
    btn.pack(side=side, expand=YES, fill=BOTH)
    return btn

class Sample(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title("Simpl3")
        self.master.iconname("smpl3")

        opsF = frame(self, TOP)
        btn = button(opsF, LEFT, "About time!")

if __name__ == "__main__":
    Sample().mainloop()




I'm not familiar with this way of Python programming, so I used as reference a sample that uses even more wierd stuff that I still haven't figured out, so I've decided to post what I could understand. Anyway, the result is a clickable button:




The last two lines are supposed to be present in every code that uses the class mechanism, except that for this case we're going to use a combination with the mainloop 'method'.



The functions 'frame' and 'button' have been created so we could simplify and organize our code a little better.


The function '__init__' inside the 'Sample' class use the master method, which takes care of the title and the iconname. After that, we create a frame and a button with their respective names.

No comments:

Post a Comment