使用Tkinter中的复选按钮更改列表状态



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

我的想法的唯一方法是制作一个文件列表,每个文件都由列表表示,其中第一个值是文件名,第二个值是 1,如果过程 0 如果不是。

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()

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

您必须在 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()

最新更新