[Tutor] some tkinter questions

Evgeny Roubinchtein eroubinc@u.washington.edu
Thu, 23 Dec 1999 13:50:11 -0800 (PST)

On Wed, 22 Dec 1999, Suzanne Little wrote:

>I've been working on a mini version/prototype/whatever you want to call it
>which just has a listbox and it pops up another window which has
>buttons. When you press the print button in the other window it should
>print the currently selected element. This is basically what I need in my
>'big' application - to be able to get the currently selected element to
>perform functions with it. 

I've made a couple simple changes to your code, and it appears to do what
you want now.  It is sort of "Java-style" (in that I am passing reference
to the listbox window around) -- there have to be better ways to do this
with Python.


from Tkinter import *
from list import *

class ListComp(Frame):

    def __init__(self, parent=None, listBox=None):
	Frame.__init__(self, parent)
        # save a reference to the listBox we're 
        # getting the items from
	self.trialListbox = listBox
        # save a reference to our parent window
	self.w1 = parent

    def createWidgets(self):
	bframe = Frame(self)
	Button(bframe, text='Print', command=self.Iprint).pack(side=LEFT)
	Button(bframe, text='Quit', command=self.Iquit).pack(side=LEFT)

    def Iprint(self):
	#retreive the element currently selected in the listbox and 
	#print it

        # here, we use the reference we saved in the constructor
	if self.trialListbox != None:
	    item = self.trialListbox.listbox.curselection()
	    member = self.trialListbox.listbox.get(item)
	    print 'Term: ' + member

    def Iquit(self):
	#close this window but not the one with the listbox
        # actually, close our parent, again we saved the reference
        # in the constructor.


from Tkinter import *
from listComp import *

class TrialListbox(Frame):
    def __init__(self, parent=None):
	Frame.__init__(self, parent)
	self.master.title('A Listbox Trial')

    def createWidgets(self):

    def makeList(self):
	frame = Frame(self)
	scrollbar = Scrollbar(frame, orient=VERTICAL)
	self.listbox = Listbox(frame, yscrollcommand=scrollbar.set)
	scrollbar.pack(side=RIGHT, fill=Y)
	self.listbox.pack(side=LEFT, fill=BOTH, expand=1)
	self.listbox.insert(END, 'hello1')
	#etc etc

    def makeButtons(self):
	bframe = Frame(self)
	Button(bframe, text='Call Print', command=self.callPrint).pack(side=BOTTOM)
	Button(bframe, text='Quit', command=self.getOut).pack(side=BOTTOM)

    def callPrint(self):
	#open up the window with the print command button
	w1 = Toplevel()
        # pass a reference to ourselves to the 
        # ListComp, so it can get at our listbox
	w1.window = ListComp(w1, self)

    def getOut(self):

if __name__ == '__main__': 
    app = TrialListbox()


Performance is easier to add than clarity.