mardi 25 juillet 2017

Tkinter checkboxes created in loop

I'm working on my first Tkinter project, and have used several stackoverflow answers and explanations (and other links they lead to) as the basis for trying to understand how to build my application.

I structured my application after reading this question (and most of the links from the accepted answer): Switch between two frames in tkinter

In one of my frames, I need to create checkboxes using a for loop. I found this page helpful: How do I create multiple checkboxes from a list in a for loop in python tkinter

I am having a hard time getting all of the checkboxes checked initially by default (my desired behavior).

The relevant part of my code is as follows (python2.7):

import Tkinter at tk

class Main(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        ...
        ## gets set on a different frame in the application
        self.files_list[]

class A(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        ...
        ## self.f_list contains the values that I am expecting on this frame
        self.f_list = controller.files_list

        for f in self.f_list:
            self.file_name = tk.StringVar()
            self.file_name.set(f['file'])
            self.run_file = tk.IntVar()
            self.run_file.set(1)
            cb = tk.Checkbutton(self, text=self.file_name.get(), variable=self.run_file)
            cb.pack()

This produces the list as I would expect of "file names", each with a checkbox. However, only the last checkbox produced from the loop is checked when run.

Before calling the pack method, I put a print statement to print self.run_file.get() and each time through the loop it prints a value of 1.

I tried changing my loop several different ways :

## same behavior
self.run_file = tk.Variable()
self.run_file.set(1) 

## same behavior
self.run_file = tk.IntVar(value=1)

## no checkboxes set
cb = tk.Checkbutton(self, text=self.file_name.get(), variable=self.run_file.get())

I feel like since the value of self.file_name is different each time through the loop there is no issue there. Since the last checkbox is checked by default, it makes me feel that the value is getting lost on the previous checkboxes but I don't know how to structure my checkboxes or the self.run_file variable so that each box is checked by default. I'm using self on the variables in the for loop after reading this question: Python, Tkinter : if there a way to check checkboxes by default?

I have looked at numerous different questions around this topic, but, still can't come up with the correct answer. Can someone point me in the right direction?




Aucun commentaire:

Enregistrer un commentaire