質問

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()
役に立ちましたか?

解決

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()

他のヒント

You forgot to use a geometry manager on the button:

button = tkinter.Button(window, command=test)
button.pack()

If you don't do it, the button won't be drawn. You might find this link useful: http://effbot.org/tkinterbook/pack.htm. Note that to pass the command to handler you have to write only the name of the function (Like it's descibed in the other answer).

This is an old question, but I just wanted to add an alternate method of preventing Tkinter from running methods at start-up. You can use Python's functools.partial (doc):

import tkinter
import tkinter.filedialog
import getpass
import functools

gui = tkinter.Tk()
user = getpass.getuser()
button = tkinter.Button(
  gui, 
  command=functools.partial(
    tkinter.filedialog.askopenfilename, 
    initialdir='C:/Users/%s' % user)
  )
button.grid()
gui.mainloop()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top