0

I use tkinter Checkbutton to get the information needed and my scripts are:

from tkinter import *
from tkinter.filedialog import askopenfilenames

window = Tk()
window.title('File Viewer')
frm=Frame(window)

filelist=[]

def selectfiles():
    files=askopenfilenames(initialdir="D:\\Document", title="Select files")
    fileList = window.tk.splitlist(files)
    filelist.append(fileList)

btn = Button(frm,text='Select Files',command=selectfiles)
frm.pack()
btn.pack(side=RIGHT, fill=BOTH)

Heads = {'Head A': "HeadAEPTrend1 (Float)", 'Head B': "HeadBEPTrend1 (Float)"}
head_list=[]
for (key, value) in Heads.items():
    strVar = StringVar()
    head_list.append(strVar)
    cb = Checkbutton(frm, text=key, variable=strVar, onvalue=value, offvalue='NA')
    cb.pack(anchor=W)
parameters=[strvar.get() for strvar in head_list if strvar.get() != 'NA']

window.mainloop()

There are 2 things I did not expected:

  1. In the GUI the default is both head A and head B are selected.(I want the default is both heads not selected)
  2. I can only get ['',''] when I call parameters in the shell after I closed the GUI.

Anyone knows what's going wrong?

CHENLU
  • 91
  • 7
  • The Checkbutton's variable needs to be given a value that matches either its `onvalue` or its `offvalue` for it to work right. And `parameters` was set *once*, prior to the mainloop; it will reflect the variable values at that moment in time only. – jasonharper Oct 22 '19 at 03:22

1 Answers1

2

1: Add value='NA' when you initiate your StringVar.

for (key, value) in Heads.items():
    strVar = StringVar(value='NA')
    ...

2: Consider this:

head_list=[]
...
parameters=[strvar.get() for strvar in head_list if strvar.get() != 'NA']
...

There is no selection when your list comprehension of parameters is done. You need to do it after the checkbuttons have been clicked, no before. You can do so by adding a command to your Checkbutton, or trace changes on your StringVar. e.g.:

def get_parameters():
    global parameters
    parameters=[strvar.get() for strvar in head_list if strvar.get() != 'NA']

...

for (key, value) in Heads.items():
    ...
    cb = Checkbutton(frm, text=key, variable=strVar, onvalue=value, offvalue='NA',
                     command=get_parameters)
...
Henry Yik
  • 22,275
  • 4
  • 18
  • 40