[Tutor] Tkinter callback question
Rick Pasotto
rick@niof.net
Tue, 3 Apr 2001 17:21:21 -0400
On Tue, Apr 03, 2001 at 04:00:11PM -0400, Ryan Booz wrote:
>
> How do I get a widget (let's say a button) to execute a command that
> changes another widget (say a label). This seems like it should be
> pretty trivial, and I've looked for two days now and only run into more
> stuff I have to learn (which is ok, just can't get it all done at
> once). Let's say I make a Label with some text "Hello" and I have two
> other buttons ("Good-bye", "Hi There") that when pressed would change
> the Label to their text (or buttons for changing colors or something).
> How do I do this with one function? In a regular python function you
> could pass a variable that would make this happen. But if you pass a
> variable in the command line, it executes at conception and not after
> that. The only way I can get it to work right now is to have a separate
> function for each button that changes one one set of things - there's no
> "variable" in it.
The following code will do what you want. There may be a better way and
if so I'd like to know it.
In order to pass a parameter to a widget's command I think you need to
use a lambda but the lambda namespace does not include the instance's
namespace. Thus, since the actual function needs to be outside the
class, you need to pass the instance as a parameter.
from Tkinter import *
class Main:
def __init__(self,root):
self.root=root
self.label = Label(root,width=30,height=3)
self.label.pack()
frm = Frame(root)
self.button1 = Button(frm,text='Hello!',
command=lambda x=self:do_change(x,1))
self.button1.pack(side=LEFT,padx=10,pady=5)
self.button2 = Button(frm,text='Type it in',
command=lambda x=self:do_change(x,2))
self.button2.pack(side=LEFT,padx=10,pady=5)
self.button3 = Button(frm,text='Goodbye!',
command=lambda x=self:do_change(x,3))
self.button3.pack(side=LEFT,padx=10,pady=5)
frm.pack(expand=TRUE,fill=BOTH)
self.entry = Entry(bg='white',width=20)
self.entry.pack(padx=10,pady=5)
def do_change(self,button=0):
if button == 1:
self.label.config(text='Hello!')
if button == 2:
txt = self.entry.get()
self.label.config(text=txt)
if button == 3:
self.label.config(text='Goodbye!')
if __name__=='__main__':
root = Tk()
main = Main(root)
root.mainloop()
--
"In the U.S. you have to be a deviant or exist in extreme boredom...
Make no mistake; all intellectuals are deviants in the U.S."
-- William Burroughs
Rick Pasotto email: rickp@telocity.com