Basic TKinter GUI format in python

Though there are many ways to format your gui code, the following seems to work well for me. It is not pretty, but the important thing is just how I laid it out.

Basically, I like making a subclass of frame for almost everything.

#!/usr/bin/env python

from Tkinter import *
import time
import tkMessageBox
import tkFileDialog
import tkSimpleDialog

class Demo(Frame):
  def __init__(self, parent=None):
    Frame.__init__(self, parent)
    Label(self, text="Basic Demonstration").pack()

    errorbutton = Button(self, text="Error", command=self.showerror)
    errorbutton.bind('', self.showerroronrc) #on hover
    errorbutton.pack(side=TOP, fill=BOTH)
    askbutton = Button(self, text="Ask", command=self.ask)
    askbutton.pack(side=TOP, fill=BOTH)

    openbutton = Button(self, text="Open",
    openbutton.pack(side=TOP, fill=BOTH)

    querybutton = Button(self, text="Input", command=self.query)
    querybutton.pack(side=TOP, fill=BOTH)

    Label(self, text="Name").pack(side=LEFT)

    checkoptions = ["check1", "check2", "check3"]
    for i in checkoptions:
      checkbox = Checkbutton(self, text=i, command=self.checkbox)

    #this is used in the showerror function
    self.ent = Entry(self)
    self.ent.pack(side=RIGHT, fill=X)

  def showerror(self):
    msg = "He's dead, " + self.ent.get()
    tkMessageBox.showerror('Error!', msg)

  def showerroronrc(self, event):
    print "stop hovering!"

  def ask(self):
    self.ynanswer = tkMessageBox.askquestion("question", "Do you like me?")   
    if self.ynanswer == "no":
      print "fine, fuck you, buddy."

  def open(self):
    file = tkFileDialog.askopenfilename()
    print file

  def query(self):
    myfloat = tkSimpleDialog.askfloat("Entry", "Enter a number")
    print myfloat 

  def checkbox(self):
    print "Don't check on me, bitch"

if __name__ == '__main__':

  img = PhotoImage(file="./grass.gif")
  Button(root, image=img).pack(side=RIGHT)

One Response to Basic TKinter GUI format in python

  1. mopey says:

    TKinter is soooo bad compared to QT. Just for my own information.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: