0

I have this code:

#!/usr/bin/python

import Tkinter
from tkFileDialog import askopenfilename
import tkMessageBox

root = Tkinter.Tk()

def getFileName():
  # show an "Open" dialog box.
  filename = askopenfilename(filetypes = [('Text files', '*.txt'),('All files','*')])

btnIco = Tkinter.Button(root, text="Icon", command=getFileName())
btnIco.pack()

root.mainloop()

What I intended to do was to run the function getFileName when the button is clicked. But instead the function runs when the code is run and the button does not do anything when clicked. Can you please point out what is wrong?

1

1 Answer 1

2

Replace the following line:

btnIco = Tkinter.Button(root, text="Icon", command=getFileName())

with:

btnIco = Tkinter.Button(root, text="Icon", command=getFileName)

In other word, remove () after getFileName. By appending (), the code is call getFileName before creating the button, and use the return value of the function as a callback instead of the function itself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.