[Tkinter-discuss] separation gui from logic

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Thu Nov 17 10:32:53 CET 2005


Cameron Laird wrote:
> On Sun, Nov 06, 2005 at 06:35:37AM +0100, Pavel Kosina wrote:
> 			.
> 			.
> 			.
> 
>>In Tkinter I try put to gui design into one file, and in another file 
>>do: import gui design file and the script logic itself.
>>I am not much successful, especially at callback functions, that are 
>>included in gui design files, f.e. Button(text='Tisk', command=hello),  
>>and refer to functions that exist in the main script.
>>
>>Is it somehow possible to do this? Not just this example of Button (how 
>>to solve reffering to function that not exists yet, and exists in 
>>"upper" program only), but this whole idea of separation....
> 
> 			.
> 			.
> 			.
> Yes.
> 
> I had hopes that Fredrik or John or Jeff or someone would speak up.
> I suspect there's already a good explanation of this subject written
> somewhere.  If none turns up in the next few days, I'll write a bit
> on it.
> 
> I'm sorry you've had to wait so long for help.

I saw this message (or one just like it) in the python list so very
sorry for not replying sooner.  I don't think I've come across an
answer on the net but one way you could do it is by passing the
callbacks in as a dictionary like so:-



import Tkinter

class GUIDesign(Tkinter.Tk):
	def __init__(self, parent, callbacks={}):
		Tkinter.Tk.__init__(self)
		self.parent = parent		
		
		button1 = Tkinter.Button(self, text = "Button1",
                     command=callbacks["button1"])
		button1.pack()
			

class Main:
	def __init__(self):
		## draw the GUI
		cbacks = {"button1" : self.button1_callback}
		
		gui = GUIDesign(self, cbacks)
		gui.mainloop()
		
		
		
		
	def button1_callback(self):
		print "Button 1 pressed"
		
Main()


The only drawback (as far as I can see) is that every time the GUI
changes (a new button is added) you must also update the callbacks
dictionary.  I'm not so sure this is the 'best' solution, but it
is 'a' solution :)

Cheers
Martin






More information about the Tkinter-discuss mailing list