simplebutton3: simplebutton3.py

# Like java SimpleButton2, but using OOP

# Weird import for compatibility across Python 2 and Python 3
try:   
	import tkinter   
except ImportError:
	import Tkinter as tkinter   

# Make our own button class, subclass of standard one
class MyButton (tkinter.Button): #//*1 We subclass the standard button

	# Args = label you want, button's parent widget or window
	def __init__(self, label, parent): #//*1 
		# Call superclass' constructor as usual
		tkinter.Button.__init__ (self, parent) #//*1 

		# Set our stuff
		self["text"] = label #//*2 Set their ivars
		self["command"] = self._myCallback #//*2
		self._count = 0 #//*3 Create and set our ivar
		
		self.pack()

	# Our callback is a method, not a global function
	def _myCallback (self): #//*4 Callback, uses ivar
		self._count += 1 #//*4
		print (self["text"] + " was pushed " + str(self._count) + " times") #//*4

# Create main frame
top = tkinter.Tk()

# Put 2 buttons in it, using our class
b1 = MyButton ("Push me", top)
b2 = MyButton ("Push me also", top)

# Start the main GUI loop
top.mainloop()
[download file]