简体   繁体   中英

Update text of label in Tkinter

I have the following code to open files, where I want show the path of the file as a Label .

import Tkinter, Tkconstants, tkFileDialog

top = Tkinter.Tk()
top.resizable(width=False, height=False)

top.geometry("700x300+350+200")

def OpenOldFile():
    top.filename = tkFileDialog.askopenfilename(initialdir = "/",title="Select old file")
    lb2 = Tkinter.Label(text="Old File:").grid(row=2,column=1, sticky='w')
    lb3 = Tkinter.Label(text=top.filename).grid(row=2,column=2, sticky='w')

def OpenNewFile():
    top.filename = tkFileDialog.askopenfilename(initialdir = "/",title="Select New file")
    lb2 = Tkinter.Label(text="New File:").grid(row=6,column=1, sticky='w')
    lb3 = Tkinter.Label(text=top.filename).grid(row=6,column=2, sticky='w')

lb1 = Tkinter.Label(text= "Select Old file:").grid(row=1,column=1, sticky='w')
B1 = Tkinter.Button(text = "Click to open file", command = OpenOldFile).grid(row=1,column=2, sticky='w')

lb4 = Tkinter.Label(text="Select New File:").grid(row=4,column=1, sticky='w')
B2 = Tkinter.Button(text="Click to open file", command = OpenNewFile).grid(row=4,column=2, sticky='w')

top.mainloop()

Problem : When I click Button B1 multiple times to open the different files, the text of Label lb3 is overwriting on the previous text as shown below in the screenshots.

When I click first time:

在此处输入图片说明

Second click:

在此处输入图片说明

You are creating a new label in every click. Instead of that, you should create one with empty text then update it as you click.

lb3 = Tkinter.Label()
lb3.grid(row=6,column=2, sticky='w')

def OpenOldFile():
    top.filename = tkFileDialog.askopenfilename(initialdir = "/",title="Select old file")
    lb3.config(text=top.filename) #or lb3["text"] = top.filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM