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

与世无争的帅哥 提交于 2021-01-19 08:38:13

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/49085244/tkinter-button-command-getting-executed-before-clicking-the-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!