Wanek T
Wanek T

Reputation: 25

list file names from a folder to a tkinter window, with python 3

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:

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.

thank you in advance!

Upvotes: 2

Views: 3795

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

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.

Upvotes: 2

Related Questions