使用Tkinter

时间:2016-05-19 17:07:31

标签: python tkinter

我想在我的程序处理的目录中显示一个文件列表。我使用Tkinter和python。

我想到的唯一方法是制作一个文件列表,每个文件由列表表示,其中第一个值是文件名,如果是,则第二个为1,如果没有,则为1。

os.chdir("/home/user/files")
for file in glob.glob("*.txt"):
    listOfFiles.append([file, 0])

for f in listOfFiles:
    c = Checkbutton(root, text=f[0], variable=f[1])
    c.pack()

实际上这段代码不起作用,因为它不会为每个文件更改第二项。我的方法有什么好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您必须在Checkbutton语句中放置命令回调,或使用Button来处理它们。最简单的方法是将每个已检查的文件附加到单独的列表中,然后处理该列表。因此,对于下面的示例代码,不是打印“检查某些内容”,而是将文件名(程序中的复选框中的文本)附加到另一个列表中。

try:
    import Tkinter as tk     # Python2
except ImportError:
    import tkinter as tk     # Python3

def cb_checked():
    # show checked check button item(s)
    label['text'] = ''
    for ix, item in enumerate(cb):
        if cb_v[ix].get():     ## IntVar not zero==checked
            label['text'] += '%s is checked' % item['text'] + '\n'

root = tk.Tk()

cb_list = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]

# list(range()) needed for Python3
# list of each button object
cb = list(range(len(cb_list)))
# list of IntVar for each button
cb_v = list(range(len(cb_list)))
for ix, text in enumerate(cb_list):
    # IntVar() tracks checkbox status (1=checked, 0=unchecked)
    cb_v[ix] = tk.IntVar()
    # command is optional and responds to any cb changes
    cb[ix] = tk.Checkbutton(root, text=text,
                            variable=cb_v[ix], command=cb_checked)
    cb[ix].grid(row=ix, column=0, sticky='w')

label = tk.Label(root, width=20)
label.grid(row=ix+1, column=0, sticky='w')

# you can preset check buttons (1=checked, 0=unchecked)
cb_v[3].set(1)
# show initial selection
cb_checked()

root.mainloop()
相关问题