在Tkinter中更新标签文本

时间:2018-07-02 06:09:48

标签: python python-2.7 tkinter

我有以下代码打开文件,我想在其中将文件的路径显示为a

b

问题:当我多次单击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() 打开不同的文件时,Button B1的文本被覆盖在以前的文字,如下面的屏幕截图所示。

当我第一次单击时:

MSDN

第二次点击:

http://aseigneurin.github.io/2016/03/04/kafka-spark-avro-producing-and-consuming-avro-messages.html

1 个答案:

答案 0 :(得分:1)

您每次点击都会创建一个新标签。取而代之的是,您应该使用空白文本创建一个,然后在单击时对其进行更新。

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