问题描述
我创建了一个框架,因为我有两个浏览按钮,我想浏览两个以.txt"扩展名结尾的文件并将其打印在屏幕上.
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()
推荐答案
因为您向 browsefunc
函数传递了一个参数或参数,该函数在它启动时运行.这是因为python运行代码的方式.您可以使用 lambda
表达式来解决此问题
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"))
这篇关于在单击按钮之前执行 Tkinter 按钮命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!