使用python 3列出从文件夹到tkinter窗口的文件名

时间:2022-08-09 00:30:19

i have the following problem: i would like to list all filenames from a folder to a tkinter window + a checkbox (with a unique variable) near each filename. so far i have this:

我有以下问题:我想列出文件夹中的所有文件名到tkinter窗口+每个文件名附近的复选框(带有唯一变量)。到目前为止我有这个:

import tkinter as tk

def gui():
    master=tk.Tk()
    files=next(os.walk('forms'))[2]
    i=1
    for f in files:
        'unique var name??'=tk.IntVar()
        tk.Checkbutton(master, text=f, variable='unique var name??').grid(row=i)
    master.mainloop()


gui()

this code works, but returns only the last file name from the respective folder + a checkbox in the tkinter window. i don't know how to define a unique tk.IntVar() variable for every checkbox and how to make the master.mainloop() window list all file names. i use python 3.4 on win 7.

此代码有效,但只返回相应文件夹中的最后一个文件名+ tkinter窗口中的一个复选框。我不知道如何为每个复选框定义一个唯一的tk.IntVar()变量,以及如何使master.mainloop()窗口列出所有文件名。我在win 7上使用python 3.4。

thank you in advance!

先感谢您!

1 个解决方案

#1


You don't need unique variable names, you only need unique variables. A list or dictionary works great. Since you're associating the variables with filenames, a dictionary with the filename as a key makes sense:

您不需要唯一的变量名,只需要唯一的变量。列表或字典效果很好。由于您将变量与文件名相关联,因此使用文件名作为键的字典是有意义的:

vars = {}
for f in files:
    var = tk.IntVar()
    tk.Checkbutton(master, text=f, variable=var).grid(row=i)
    vars[f] = var

Later, to print the value of all the variables, just iterate over the dictionary:

稍后,要打印所有变量的值,只需迭代字典:

for (name, var) in vars.iteritems():
    print(name, var.get())

BTW: you have a bug in your code, in that you never increment the row number. You end up stacking all of the buttons on top of each other in the same row. You need to add something like i += 1 inside your loop.

顺便说一句:你的代码中有一个错误,因为你永远不会增加行号。您最终将所有按钮堆叠在同一行中。你需要在循环中添加类似i + = 1的东西。

#1


You don't need unique variable names, you only need unique variables. A list or dictionary works great. Since you're associating the variables with filenames, a dictionary with the filename as a key makes sense:

您不需要唯一的变量名,只需要唯一的变量。列表或字典效果很好。由于您将变量与文件名相关联,因此使用文件名作为键的字典是有意义的:

vars = {}
for f in files:
    var = tk.IntVar()
    tk.Checkbutton(master, text=f, variable=var).grid(row=i)
    vars[f] = var

Later, to print the value of all the variables, just iterate over the dictionary:

稍后,要打印所有变量的值,只需迭代字典:

for (name, var) in vars.iteritems():
    print(name, var.get())

BTW: you have a bug in your code, in that you never increment the row number. You end up stacking all of the buttons on top of each other in the same row. You need to add something like i += 1 inside your loop.

顺便说一句:你的代码中有一个错误,因为你永远不会增加行号。您最终将所有按钮堆叠在同一行中。你需要在循环中添加类似i + = 1的东西。