1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Rep Power

    Binding confusion in Tkinter

    Hello, everyone :-)

    And now for something completely different: I am experiencing a slight problem with binding to Shift-Return key event in Tkinter.

    I am writing a front end to Python a la Mathematica's so that I might be able to display non-ASCII characters, save the contents of the window in a file etc.

    I created a Text widget, in which I type the command, then press the "CALCULATE" button and the result appears on the next line. I would like to bind the action performed by the "CALCULATE" button to a sequence of keys Shift-Return, again, just as in Mathematica. This binding works (that is, calculation is done and the result is displayed after Shift-Return has been pressed), but together with a direct action of Shift-Return on text (that is, the cursor jumps to the next line).

    Here's the piece of my code where the problem occurs (resides in the __init__ method):

    b=Button(toolbar,text="CALCULATE",command=lambda s=self:s.calculate_bttn(text))
    text.bind("<Shift-Return>",lambda event:self.calculate_bttn(text))

    where "calculate_bttn(self,widget)" is a method defined in the current class.

    Note that if I bind to text (just as shown above), the calculation (according to calculate_bttn(self,widget)) is performed first, and after that the line (due to Shift-Return action) is inserted. But if I bind to master (the main window), the sequence of events is reverse: first the line is inserted and then calculate_bttn(self,widget) runs.

    Does anybody have any idea how to stifle the unneeded, unbinded action of Shift-Return, which makes the cursor jump to the next line?

    I understand that I am probably binding to two different widgets, but I can't perceive how to solve the problem descpite already spending three hours on it.

    Any help will be greatly appreciated.

    Thank you.

  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Cambridge, UK
    Rep Power
    According to The Tkinter reference your event handler should return a "break" string to break the chain of handlers:

    def myhandler(event):
        #do stuff
        return "break"
    This should swallow the Shift-Return characters.


IMN logo majestic logo threadwatch logo seochat tools logo