需要有关 python tkinter UI、组合框的帮助

问题描述 投票:0回答:1

我是 python UI 新手。

我有一个包含 60 多个文本文件(txt1、txt2 等)的文件夹,每个文件都包含一个名称列表。

在我的 Python UI 中,我有 2 个组合框。我希望第一个允许我从文件夹路径中可用的 txt 文件列表中选择一个文本文件,一旦选择该文件(组合框 1),就用从组合 1 中选择的 txt 文件内的名称填充第二个组合框。那可能吗?如果是的话,该怎么做?

我提前向您表示感谢。

非常感谢您的帮助!

对于组合框1:

def combolistdisp(combo):
    os.chdir("./")
    ls=[]
    for file in glob.glob("*.sql"):
        #print(file)
        ls.append(file)
        combo['values']=(ls)

对于组合框2:

我需要帮助如何读取从组合框 1 中选择的文件并使用文件内的内容填充组合框 2。

python tkinter python-3.11
1个回答
0
投票

是的,这是可能的。

您可以按照以下函数来做到这一点。首先,使用

txt_files

获取指定目录中的txt文件列表
def populate_combo1():
    txt_files = [file for file in os.listdir(folder_path.get()) if file.endswith('.txt')]
    comboBox1['values'] = txt_files

然后读取所选文件的行并使用

comboBox2['values'] = [line.strip() for line in file]

进行填充
def populate_combo2(event):
    selected_file = comboBox1.get()
    if selected_file:
        with open(os.path.join(folder_path.get(), selected_file), 'r') as file:
            comboBox2['values'] = [line.strip() for line in file]
© www.soinside.com 2019 - 2024. All rights reserved.