【问题标题】:How to update tkinter text label after updating current work directory with file使用文件更新当前工作目录后如何更新 tkinter 文本标签
【发布时间】:2021-07-26 08:36:37
【问题描述】:

我有一个按钮,要求用户选择一个目录和一个将该路径存储在变量pwd 中的函数。选择目录后,我想显示路径并在用户单击按钮并选择新目录时更新它。

如何在每次函数获取新路径时更新或刷新文本标签?

import os
from tkinter import *
from tkinter import filedialog

#Set working directory for GUI
def work_dir():
    pwd = filedialog.askdirectory()
    os.chdir(pwd)

window = Tk()

btn_getPWD = Button(text="Change Work Directory", command = work_dir)
btn_getPWD.pack()

cwd = Label(window, text = "Current Working Directory: " + os.getcwd())
cwd.pack(anchor="w")

【问题讨论】:

  • 您可以为标签设置行和列,就像我在这里所做的那样,它会显示一个文件,如果我更改文件,它会显示该文件的路径。 l0=Label(wins,text='showing file ' + filename,bg='black',fg='yellow').grid(column=2,row=1)
  • 只需在work_dir()函数内更新标签cwd的文本即可。
  • @acw1668 如何更新work_dir() 以使其正常工作?我还将os.getcwd() 更改为pwd,但没有任何显示(这是有道理的,因为在我单击按钮之前该函数不会运行)。

标签: python python-3.x windows user-interface tkinter


【解决方案1】:

这有什么难的?使用config()更新函数内部的文字:

def work_dir():
    pwd = filedialog.askdirectory()
    os.chdir(pwd)
    cwd.config(text="Current Working Directory: " + pwd)

【讨论】:

  • 谢谢,这成功了!你有什么资源可以指点我来了解更多关于 tkinter 的信息吗?我还是 python 新手。
  • @Peter Check this out
猜你喜欢
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多