如何在Python按钮上将标签文本更改为文件名?

时间:2015-05-14 14:52:27

标签: python tkinter

如何将label_1的文字更改为我在browse_for_file_1中选择的文件?我一直在尝试各种方法,但我似乎无法让GUI更新。我想这可能是因为它在一个框架内的框架中?

import Tkinter as tk
import tkFileDialog

root = tk.Tk()

#Frames
frame_1 = tk.Frame(root)
frame_1.pack()

def browse_for_file_1():
    file_name_1 = tkFileDialog.askopenfilename(parent=root,title='Open 1st File')
    print file_name_1
    label_1.config(text=file_name_1)
    root.update()



#Browse 1
browse_button_1 = tk.Button(frame_1, text='Browse for 1st File', width=25, command=browse_for_file_1).pack(side=tk.LEFT, pady=10, padx=10)
label_1 = tk.Label(frame_1, fg="red", text="No file selected.")
label_1.pack(side=tk.RIGHT, pady=10, padx=10)

#Quit Button
quit = tk.Button(root, text='QUIT', width=25, fg="red", command=root.destroy).pack(pady=10, padx=10)

root.title("Zero Usage")
root.mainloop()

1 个答案:

答案 0 :(得分:4)

更改您的电话:

browse_button_1 = tk.Button(frame_1, text='Browse for 1st File', width=25, command=lambda:browse_for_file_1(label_1)).pack(side=tk.LEFT, pady=10, padx=10)

然后你的功能可以是:

def browse_for_file_1(label_1):
  file_name_1 = tkFileDialog.askopenfilename(parent=root,title='Open 1st File')
  label_1.config(text=file_name_1)
  # or label_1.config({'text':file_name_1})