Basic TKinter GUI format in python
July 23rd, 2008 by webstersprodigyThough 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)
self.pack()
Label(self, text="Basic Demonstration").pack()
errorbutton = Button(self, text="Error", command=self.showerror)
errorbutton.bind('<Enter>', 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", command=self.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)
checkbox.pack(side=TOP)
#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."
Frame.quit(self)
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__':
root=Tk()
Demo(root).pack()
img = PhotoImage(file="./grass.gif")
Button(root, image=img).pack(side=RIGHT)
mainloop()
March 12th, 2009 at 03:02
TKinter is soooo bad compared to QT. Just for my own information.