带有var文本的Tkinter更新标签

时间:2018-03-08 17:41:56

标签: python-3.x tkinter

我正在尝试创建一个标签,每次从filedialog中选择文件时都会更新。我按照示例here但我以某种方式开始创建了多个窗口。我做错了什么?

import tkinter as tk
import tkinter.filedialog as fd

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.select_history = tk.Button(self,text="Select  Student History File",command=self.select_history).pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",command=root.destroy).pack(side="top")

        tk.Label(root, textvariable=historyfile).pack(side="bottom")        


    def select_history(self):
        fname = fd.askopenfilename()
        historyfile.set(fname)
        print(fname)

root = tk.Tk()
root.geometry("400x450+0+0")
root.configure(background="lightblue")

app = Application(master=root)
app.mainloop()

1 个答案:

答案 0 :(得分:0)

您的变量historyfile未定义。将tk.Label(root, textvariable=historyfile).pack(side="bottom")更改为

self.historyfile = tk.StringVar()
tk.Label(root, textvariable=self.historyfile).pack(side="bottom")

在函数select_history中,使用

self.historyfile.set(fname)

总代码:

import tkinter as tk
import tkinter.filedialog as fd

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.select_history = tk.Button(self,text="Select  Student History File",command=self.select_history).pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",command=root.destroy).pack(side="top")
        self.historyfile = tk.StringVar()
        tk.Label(root, textvariable=self.historyfile).pack(side="bottom")        


    def select_history(self):
        fname = fd.askopenfilename()
        self.historyfile.set(fname)
        print(fname)

root = tk.Tk()
root.geometry("400x450+0+0")
root.configure(background="lightblue")

app = Application(master=root)
app.mainloop()