4

I have created a frame, In that i have two browse button, i want browse two file that ending with ".txt" extension and printing it on screen.

In my scenario, browse function getting called before pressing Button's on the frame. Am expecting it should called when i press Button. Complete code attached. Kindly someone correct me what i did wrong.

from Tkinter import *
import tkFileDialog as filedialog

global filename

root = Tk()

def browsefunc(entry):
    entry = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
    print entry


browsebutton1 = Button(root, text="Browsefile1", command=browsefunc("TXT_file1"))
browsebutton1.pack()

browsebutton2 = Button(root, text="Browsefile2", command=browsefunc("TXT_file2"))
browsebutton2.pack()


root.mainloop()
velpandian
  • 431
  • 4
  • 11
  • 23

1 Answers1

11

Because you are passing the browsefunc function an argument or parameter the function runs when it starts. This is because of the way that python runs the code. You can use a lambda expression to fix this

browsebutton1 = Button(root, text="Browsefile1", command=lambda: browsefunc("TXT_file1"))
Crawley
  • 600
  • 2
  • 8
  • 15