Search code examples
pythonpython-2.7tkintertkinter-layout

Tkinter Button command getting executed before clicking the button


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

Solution

  • 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"))