[Tkinter-discuss] Kinetic Scrolling and Keyboard Shortcuts in Menus

Cam Farnell msa01 at bitflipper.ca
Sun Aug 31 20:47:20 CEST 2008

I ran into exactly this keyboard shortcut issue while writing the Rapyd-Tk Python development environment (http://www.bitflipper.ca/rapyd/). My solution is based on these functions, where the left part is the usual menu label and the right part is the shortcut. If the length of the shortcut text varies a lot you can compute the width on the fly as is done in Rapyd, otherwise just use some reasonable constant.

def PadToWidth(LeftPart,RightPart,Width,Widget):
    Given left and right parts, return string of specified width in pixels.
    o "LeftPart" is the string to be left justified in the result.
    o "RightPart" is the string to be right justified in the result.
    o "Width" is the desired width, in pixels, of the result.
    o "Widget" the calculation is done with reference to the font set for this widget.
    Note that since we pad with space characters, the result will be as close as
        possible to the target size but will not necessarily be exactly the number
        of pixels requested.
    UsedPixels = TextMeasure(LeftPart+RightPart,Widget)
    PadPixels = Width - UsedPixels
    PadCount = int(round(float(PadPixels) / float(TextMeasure(' ',Widget))))
    return '%s%s%s'%(LeftPart,' '*PadCount,RightPart)

def TextMeasure(Text,Widget):
    Measure size of "Text", in pixels, if displayed in "Widget".
    return int(Widget.tk.call("font", "measure", Widget["font"]
        ,"-displayof", Widget.master, Text ))

Johnston Jiaa wrote:

> Also, I have set keyboard shortcuts for some functions in my program.  
> The functions these shortcuts call are also linked to menu items in the 
> menu bar.  How can I get the menu labels to reflect the keyboard 
> shortcuts for each relative command?  I know I can set the shortcut as a 
> string in the label manually, but it will be stupid, not flush with the 
> right edge of the menu, like in other programs.
> Thanks for helping my program not be stupid

More information about the Tkinter-discuss mailing list