Tkinter button not working as expected
jstroud at mbi.ucla.edu
Fri Sep 22 00:04:41 CEST 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)
> t = StringVar()
> self.entry = Entry(frame, textvariable=t)
> self.button = Button(frame, text="Select", fg="red")
> self.button["command"] = self.getPath(t)
> def getPath(self, t):
> dirPath = tkFileDialog.askdirectory(initialdir="c:\\")
> print dirPath
> root = Tk()
> app = App(root)
> 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:
from Tkinter import *
def __init__(self, master):
frame = Frame(master)
t = StringVar()
self.entry = Entry(frame, textvariable=t)
self.button = Button(frame, text="Select", fg="red")
# note change here
self.button["command"] = functools.partial(self.getPath, t)
def getPath(self, t):
dirPath = tkFileDialog.askdirectory(initialdir="c:\\")
root = Tk()
app = App(root)
UCLA-DOE Institute for Genomics and Proteomics
Los Angeles, CA 90095
More information about the Python-list