在 tkinter 中更新标签

Update Labels in tkinter

我正在向我的代码添加 "select file section"。我想有两个选项,第一个选择文件路径,第二个输入文件路径。

我无法实现的另一个功能是,如果用户选择文件路径,该路径会出现在条目部分。

这是我正在谈论的代码部分:

from tkinter import filedialog
import tkinter as tk

class open_file:
    def __init__(self, master):
        self.master = master
        self.file_path = ''

        self.b1 = tk.Button(master,
               text = 'Open',
               command = self.open_file).grid(row=0, column=1)

        v = tk.StringVar(root, value = self.file_path)
        self.l1 = tk.Entry(master, width=24, textvariable=v).grid(row=0, column=0)


    def open_file(self):
        self.file_path = filedialog.askopenfilename(filetypes = (("Python Files", "*.py")
                                                             ,("All files", "*.*") ))

root = tk.Tk()
app = open_file(root)
root.mainloop()

由于您有一个链接到文本的 StringVar,因此您需要使用 StringVar.set() 来设置条目的文本。

来自http://effbot.org/tkinterbook/variable.htm:

The set method updates the variable, and notifies all variable observers. You can either pass in a value of the right type, or a string.

您已经在 StringVar 上设置了内容,但它们不会在 self.file_path 更改时动态更新。 在您的情况下,您必须使 StringVar (v) 成为 __init__ 函数

中的 class 成员
 self.v = tk.StringVar(root, value = self.file_path)

此外,当您要更新文件路径时,请通过 self.v.set(String)

进行设置
def open_file(self):
        self.file_path = filedialog.askopenfilename(filetypes = (("Python Files", "*.py")
                                                            ,("All files", "*.*") ))
        if self.file_path:  #check if file path is not None or empty
                self.v.set(self.file_path)