Search code examples
pythonbuttontkinteropenfiledialog

Tkinter program runs button command on startup?


So I have a program that is basically supposed to have a button that opens a file dialog in the (username) folder. But when I run the program it opens without even pushing the button. What's more, the button doesn't even show up. So in addition to that problem I have to find a way to turn the selected directory into a string.

import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
tkinter.Button(gui, command=tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)).pack()
gui.mainloop()

Solution

  • Regarding your first issue, you need to put the call to tkinter.filedialog.askopenfilename in a function so that it isn't run on startup. I actually just answered a question about this this morning, so you can look here for the answer.

    Regarding your second issue, the button isn't showing up because you never placed it on the window. You can use the grid method for this:

    button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
    button.grid()
    

    All in all, your code should be like this:

    import tkinter
    import tkinter.filedialog
    import getpass
    gui = tkinter.Tk()
    user = getpass.getuser()
    button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
    button.grid()
    gui.mainloop()