更改配置文件行时更新Tkitner标签

2024-09-29 00:16:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的菜单上有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个标签,我将文本设置为读取配置文件。这意味着,当我重新启动程序时,它将发生更改,但我希望它在不重新启动的情况下更新


Tags: 文件textlogconfigparsercolumnopenini
1条回答
网友
1楼 · 发布于 2024-09-29 00:16:05

在我看来,你有三个选择。 最快的修复方法是使用

ttk.label_name['text']="new text"

更好的选择是使用textvarable,而不仅仅是文本

您将其定义为:

my_text = stringvar()
my_text.set("inital text")

定义标签时 而不是text=“blabla”

textvar = my_text

若要更改标签,只需使用

my_text.set("new text")

第三种选择是使用更新功能。它将每隔一段时间读取您的init文件,并相应地更改您的标签。如果您对该选项感兴趣,请阅读此https://riptutorial.com/tkinter/example/22870/-after

相关问题 更多 >