Tkinter button not working as expected

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Sep 21 18:02:47 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.
[...]
> what am I doing wrong?

Recently I've done a stupid error with a callback (probably I was
sleeping), so I try again. Note many little changes that I belive
improve your program:

import Tkinter as tk
import tkFileDialog

class App(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.pack()

        self.entrytxt = tk.StringVar()
        entry = tk.Entry(self, textvariable=self.entrytxt)
        entry.pack(side=tk.LEFT)

        button = tk.Button(self, text="Select", fg="red",
command=self.getPath)
        button.pack(side=tk.LEFT)

    def getPath(self):
        dirPath = tkFileDialog.askdirectory(initialdir="c:/")
        self.entrytxt.set(dirPath)
        print dirPath

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

Bye,
bearophile




More information about the Python-list mailing list