python - 如果更改配置文件行,则更新 Tkitner 标签
问题描述
我的菜单上有 3 个标签,显示 3 个不同文件/目录的文件路径。我有 3 个按钮,允许用户更改所述文件路径。如果按下按钮,将自动更新 config.ini 文件。
我希望这些标签显示为配置文件中的默认值,除非该文件已更新,然后它会动态更改以显示新文件路径。
以下是我的按钮命令的 3 种方法:
def open_vend_direct():
vend_directory = filedialog.askopenfilename(
initialdir="/", title="Select file", filetypes=(("Excel Files (CSV)", "*.csv"), ("all files", "*.*")))
parser = ConfigParser()
parser.read('config.ini')
parser.set('VendorList','List_Location',vend_directory)
with open('config.ini', 'w') as f:
parser.write(f)
def open_attach_direct():
vend_attach_direct = filedialog.askdirectory()
parser = ConfigParser()
parser.read('config.ini')
parser.set('VendorFile','file_Location',vend_attach_direct)
with open('config.ini', 'w') as f:
parser.write(f)
def open_log_direct():
log_locate = filedialog.askdirectory()
parser = ConfigParser()
parser.read('config.ini')
parser.set('LogFolder','log_location',log_locate)
with open('config.ini', 'w') as f:
parser.write(f)
这是我的 3 个按钮及其各自的标签:
parser = ConfigParser()
parser.read('config.ini')
vend_list_button = ttk.Button(optionmenu, text='Vendor List Directory',
command=open_vend_direct).grid(column=1, row=1, sticky=W)
vend_list_locat = ttk.Label(optionmenu, text=parser.get('VendorList','list_location')).grid(
column=2, row=1, sticky=(W, E))
############################
# row 2
vend_attach_button = ttk.Button(optionmenu, text='Vendor File Directory',
command=open_attach_direct).grid(column=1, row=2, sticky=W)
vend_attach_locat = ttk.Label(optionmenu, text=parser.get('VendorFile','file_location')).grid(
column=2, row=2, sticky=(W, E))
###########################
# row 3
log_location_button = ttk.Button(
optionmenu, text='Log Folder Preference', command=open_log_direct).grid(column=1, row=3, sticky=W)
log_locat = ttk.Label(optionmenu, text=parser.get('LogFolder','log_location')).grid(
column=2, row=3, sticky=(W, E))
如您所见,对于这 3 个标签,我将文本设置为读取配置文件。这意味着当我重新启动程序时它会改变,但我希望它在不重新启动的情况下更新。
解决方案
在我看来,您有三个选择。最快的解决方法是更改标签
ttk.label_name['text']="new text"
更好的选择是使用 textvarable 而不仅仅是文本。
您将其定义为:
my_text = stringvar()
my_text.set("inital text")
定义标签而不是文本时=“blablabla”
textvar = my_text
并更改标签只需使用
my_text.set("new text")
第三种选择是使用更新功能。它将每隔一段时间读取您的 init 文件并相应地更改您的标签。如果您对该选项感兴趣,请阅读此https://riptutorial.com/tkinter/example/22870/-after--
推荐阅读
- java - 在 Java 中使用不同的部署配置运行相同的测试用例
- powershell - CreateItem(0) 在计划任务中失败
- android - 从地图中拾取点并将坐标存储在数据库中,但有些点不是GPS坐标
- c# - WCF服务C#调用另一个WCF服务VB
- php - cURL 已安装,但仍然出现此错误 Elasticsearch-PHP 需要 cURL 或自定义 HTTP 处理程序
- wpf - 滚动时 WPF 数据网格单元格边框在固定(静态列)上重叠
- java - Android防止耗时加载WebView
- php - 导出日历和发送邮件 Outlook PHP
- android - 通过禁用电池优化在 android (API Level >=25) 中运行后台服务
- python - 创建一个 IPv4 地址并使用预期的输出递增它