[Tkinter-discuss] How to enable load button in python-tkinter widget

Guilherme Polo ggpolo at gmail.com
Fri Jun 27 13:28:17 CEST 2008


On Fri, Jun 27, 2008 at 7:12 AM, Michael O'Donnell
<michael.odonnell at uam.es> wrote:
> Hi Anil,
>
>  A pure Tkinter dropdown box: click on a button and a menu drops
> down, allowing you to select. If you specify a callback function, this is called
> when you make a selection:
>
> from Tkinter import *
> import os, sys
>
> #  SelecteButton Class - creates a button which when clicked on gives
> a popup menu.
> # if the callback arg is given, this is a function called when a
> selection is made, expecting the
> # selected option as arg
> # The value can be accessed by asking the widget for its x.selected attribute.
> #  Coded Mick O'Donnell michael.odonnell at uam.es
>
> class SelectButton(Label):
>
>    def __init__(self, parent, options, callback=None, default=None,
> **otherKeys):
>        Label.__init__(self, parent, bg="white", relief="raised",
> bd=2, **otherKeys)
>        self.options=options
>        self.callback=callback
>        self.oldGrab=None
>        if default==None:  default=self.options[0]
>        self.bind("<Button-1>", self.showOptions)
>        self.setOption(default, False)
>
>    def setOption(self, selected, docallback=True):
>        self.selected=selected
>        self["text"]=selected
>        if docallback and self.callback:
>            self.callback(selected)
>
>    def showOptions(self, event):
>        menu=Menu(None, tearoff=0)
>        for option in self.options:
>            menu.add_command(label=option, command= lambda
> lab1=option: self.setOption(lab1))
>        menu.post(event.widget.winfo_rootx(), event.widget.winfo_rooty())
>        if os.name =="posix" and sys.platform != "darwin":
>            menu.grab_set()
>
> # DEMO
>
> if __name__ == '__main__':
>
>    def showSelected(label): print "You selected: ", label
>
>    tk = Tk()
>    ssw = SelectButton(tk, ['1','2','3','4','5'],
> callback=showSelected, default=str(2))
>    ssw.pack(side=TOP, expand=TRUE, fill=BOTH)
>    tk.mainloop()

If you want to go this way, then Tkinter.OptionMenu is there already.



-- 
-- Guilherme H. Polo Goncalves


More information about the Tkinter-discuss mailing list