[英]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
. 我有以下代码打开文件,我想在其中将文件的路径显示为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. 问题 :当我多次单击Button
B1
以打开不同的文件时, Label
lb3
的文本将覆盖先前的文本,如下面的屏幕快照所示。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.