jeudi 15 novembre 2018

tkinter return names of dynamic checkboxes

I'm trying to write my fisrt script in python & tkinter.

I block and i'm lost when i need to get in variable the name of each checkboxes selected when i click on the buton Validate

Checkboxes are dyamic from text files: txt file:

item1
item2
...
item100

A screen of the GUI: enter image description here

Here my code:

in "#" Code which i tried wihtout success.

from tkinter import *
from tkinter.ttk import Frame, Label, Entry
import glob

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.master.title("My Menu")

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="lst1", command=self.onDisplay)
        submenu.add_command(label="lst2")
        submenu.add_command(label="lst3")
        fileMenu.add_cascade(label='Listing', menu=submenu, underline=0)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)

## Here the function which display checkboxes
def onDisplay(self):
    self.pack(fill=BOTH, expand=True)
    frame1 = Frame(self)
    frame1.pack(fill=BOTH)
    lbl1 = Label(frame1, text="Choice", width=6)
    path = '/root/liste/*.txt'
    files=glob.glob(path)
    count = 0
    #var = dict()
    for file in files:
        with open(file, 'r') as lst_file:
            for item in lst_file:
                #var[item]=IntVar()
                #cb = Checkbutton(frame1, text=item.rstrip(), variable=var[item], command=self.cb)
                ##Here all checkboxes generated dynamically
                cb = Checkbutton(frame1, text=item.rstrip())
                cb.grid(row=count//10, column=count%10)
                #cb.pack()
                count += 1
    #btn1 = Button(self, text='Validate', font=("Arial", 12), command=self.cb)
    btn1 = Button(self, text='Validate', font=("Arial", 12)
    btn1.pack(side=RIGHT, padx=5)

def cb(self):
    print("variable is", self.var.get())

def onExit(self):

    self.quit()

def main():

    root = Tk()
    root.geometry("800x550+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

Many thanks for any help

Regards,




Aucun commentaire:

Enregistrer un commentaire