Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Button command getting executed before clicking the button [duplicate]

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()
like image 537
velpandian Avatar asked Oct 16 '25 15:10

velpandian


1 Answers

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"))
like image 156
Crawley Avatar answered Oct 18 '25 11:10

Crawley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!