Tkinter button not working as expected

James Stroud jstroud at mbi.ucla.edu
Thu Sep 21 18:04:41 EDT 2006


vagrantbrad at yahoo.com wrote:
> I've created a short test program that uses tkFileDialog.askdirectory
> to help the user input a path into a tk entry widget.  The problem I'm
> having is that when I run the code as listed below, the getPath
> function is called when the program initially runs, not when the button
> is pressed.
> 
> from Tkinter import *
> import tkFileDialog
> 
> class App:
> 
>     def __init__(self, master):
> 
>         frame = Frame(master)
>         frame.pack()
> 
>         t = StringVar()
>         self.entry = Entry(frame, textvariable=t)
>         self.entry.pack(side=LEFT)
> 
>         self.button = Button(frame, text="Select", fg="red")
>         self.button["command"] = self.getPath(t)
>         self.button.pack(side=LEFT)
> 
>     def getPath(self, t):
>         dirPath = tkFileDialog.askdirectory(initialdir="c:\\")
>         print dirPath
>         t.set(dirPath)
> 
> root = Tk()
> app = App(root)
> root.mainloop()
> 
> 
> The problem arises when I try to pass the t variable in the "command"
> option of the button widget.  If I set the command to
> "command=self.getpath" rather than "command=self.getpath(t)", then I
> don't get this issue.  But I would like to be able to pass a variable
> to the the function through the command option.  I'm a Tk newbie ....
> what am I doing wrong?
> 

Well, in python 2.5, you might consider functools.partial.

Other options, including lambda, will be suggested and are the 
traditional way to do this sort of thing.

Here is the revised code:

import functools
from Tkinter import *
import tkFileDialog

class App:

     def __init__(self, master):

         frame = Frame(master)
         frame.pack()

         t = StringVar()
         self.entry = Entry(frame, textvariable=t)
         self.entry.pack(side=LEFT)

         self.button = Button(frame, text="Select", fg="red")

         # note change here
         self.button["command"] = functools.partial(self.getPath, t)
         self.button.pack(side=LEFT)

     def getPath(self, t):
         dirPath = tkFileDialog.askdirectory(initialdir="c:\\")
         print dirPath
         t.set(dirPath)

root = Tk()
app = App(root)
root.mainloop()




-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list