如何使用tkinter,python 3.6.5将复选框名称保存到列表中

时间:2018-05-23 10:23:43

标签: python python-3.x checkbox tkinter tkinter-entry

我想使用tkinter和复选框在目录中选择文件,并在按下按钮时将这些文件名保存在列表中:

import speech_recognition as sr
import playsound
import os
import glob
import unidecode
import pickle
import random
import tkinter
from tkinter.constants import *

ldv = os.listdir("D:/FFOutput/")
i = 0
ldv1 = []
while i < len(ldv):
    ldv1.append(unidecode.unidecode(ldv[i]))
    i += 1
print(ldv1)

root = tkinter.Tk()
frame = tkinter.Frame(root, relief=RIDGE, borderwidth=10)
frame.pack(fill=BOTH, expand=1)
label = tkinter.Label(frame, text="choose file(s)")
label.pack(fill=X, expand=1)


a = 0
while a < len(ldv1):
    bouton = tkinter.Checkbutton(root, text=ldv1[a], command=print(ldv1[a]))
    a += 1
    bouton.pack()

button = tkinter.Button(frame, text="Exit", command=root.destroy)
button.pack(side=BOTTOM)

lr = []

buttonregister = tkinter.Button(root, text="Register checked files names in list lr and close tk")
buttonregister.pack(side=BOTTOM)

print(lr)

root.mainloop()

当我点击buttonregister时,我想将文件名附加到列表lr中并关闭框架。 Example

在该示例中,我希望在单击按钮时在shell中打印(lr)"['alors soyez pret.mp3','c'est bien.mp3']"

1 个答案:

答案 0 :(得分:1)

要使Checkbutton保存一个值,必须使用来自tkinter的BoolVar(或任何其他var)。这通常非常繁琐,因为您必须为每个Checkbutton创建一个变量。这可以通过对Checkbutton进行子类化并为变量添加存储来避免。由于您也需要文本,我们也可以使用该类来存储文本值。

用下面的类替换Checkbuttons就可以了。

class CheckBox(tkinter.Checkbutton):
    boxes = []  # Storage for all buttons

    def __init__(self, master=None, **options):
        tkinter.Checkbutton.__init__(self, master, options)  # Subclass checkbutton to keep other methods
        self.boxes.append(self)
        self.var = tkinter.BooleanVar()  # var used to store checkbox state (on/off)
        self.text = self.cget('text')  # store the text for later
        self.configure(variable=self.var)  # set the checkbox to use our var

然后我们将使用该类来创建按钮,如下所示:

a=0
while a<len(ldv1):
   bouton=CheckBox(tk, text=ldv1[a], command=print(ldv1[a]))  # Replace Checkbutton
   a=a+1
   bouton.pack()

最后,要在窗口关闭时获取值,可以为每个按钮的值循环访问CheckBox.buttons。您需要在mainloop之后添加它或将其添加到函数中。

for box in CheckBox.boxes:
    if box.var.get():  # Checks if the button is ticked
        lr.append(box.text)

print(lr)