[Tutor] Dictionary blues...

Alan Gauld alan.gauld at freenet.co.uk
Thu Mar 24 00:17:32 CET 2005


> I posted the wrong code before. The code is:

Is this the actual code you have written? If so it is 
so far from being working code that it suggests you 
need to back up a little and work at the basics of 
Python before trying to tackle Tkinter and GUIs.

I'll assume this really is your code and make some 

> from Tkinter import *
> D={a:"tom", b:"dick", c:"harry"}

You need to put the keys in quotes too

> text.bind('<Key>', self.Conv)

self is only used to access the members of a class, 
you don't have any class so you don't need self.
You also don't, at this stage, have anything called 
'text' so you can't bind anything to it. You need to 
create a text widget which in turn it parented under 
a Tk object

top = Tk()
text = Text(top)
text.bind('<Key>', Conv)

But even here, Conv hasn't been defined yet so you 
need to move the Conv definition above those lines.

> def Conv(self,event):

You can remove the self fro the parameter list, its 
only needed if this is a method of a class.

>    if D.has_key(event.keysym):
>      str=D[event.keysym]
>    self.text.insert(END,str)

You can remove the 'text.' thats only used if text 
were part of a class, which in this case it isn't.
Also you probably want to indent the insert line as 
part of the if clause.

>    return 'break'

And before anything works you need to 'pack' the text 
widget and set the event loop running:


> The error message says wrong syntax...

I'm sure it said a lot more than that. Please send the 
whole error message, the bit that tells us what exactly 
Python thought was wrong and where. In this case there 
is so much that is wrong it doesn't matter too much but
in future it will be important. The more you help us 
the more we can help you.

If the above doesn't make sense can I suggest you try 
building a textual version first using the dictionary 
and raw_input to read the keys from the console. Once 
you have the basics working putting it into a GUI will 
be much easier.

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list