2017-02-14 49 views
0

我正在創建一個Tkinter應用程序,嘗試從多個複選框獲取值。我可以創建複選框,但無法檢索值.i.e。選中或未選中複選框。Python Tkinter - 從多重複選框獲取值

要求:

我需要遍歷所有複選框變量識別檢查的。

import openpyxl 
import sys 
import pandas as pd 
from Tkinter import * 
import ttk 
import tkFont 


reload(sys) 
sys.setdefaultencoding('utf8') 

top = Tk() 
notebook = ttk.Notebook(top) 
notebook.grid(row=1, column=0, columnspan=1, sticky=W) 
frame1 = ttk.Frame(top) 
notebook.add(frame1, text='TAB1') 
s = ttk.Style() 
s.theme_use('clam') 
helv36 = tkFont.Font(family='Helvetica', size=12, weight=tkFont.BOLD) 

wb = openpyxl.load_workbook('File',data_only=True) 
ws = wb['Sheet1'] 

mylist = [] 
mylist1 = [] 
for col in ws['A']: 
    mylist.append(col.value) 
for col in ws['B']: 
    mylist1.append(col.value) 

mylist = [str(item) for item in mylist] 
mylist1 = [str(item) for item in mylist1] 

i=2 
for name in mylist: 
    Label(frame1, text="col1", 
      borderwidth=1,font=helv36).grid(row=1) 
    Label(frame1, text=name, 
        borderwidth=1).grid(row=i) 
    i +=1 


i =2 
for name in mylist1: 
    Label(frame1, text="col2", 
      borderwidth=1,font=helv36).grid(row=1, column=1) 
    Label(frame1, text=name, 
      borderwidth=1).grid(row=i,column=1) 
    val = IntVar() 
    val = "v" + str(i) 
    c_val = Checkbutton(frame1, variable=val) 
    c_val.grid(row=i, column=2,sticky = W) 
    i +=1 


***def chkbox_checked(): 
    #Need to loop to get checked checkboxes*** 


B200 = Button(frame1, text ="Check", command = chkbox_checked,font=helv36, bg='orange') 
B200.grid(row=100) 
top.mainloop() 
+0

你給了一個要求,但都沒有問的問題。您需要哪些解決方案幫助? –

+0

我需要獲取選中的複選框的變量 – jay

回答

1

您可以將BooleanVar關聯到複選框並獲取值。然後,您可以使用set()方法設置複選框的默認值,並使用get()獲取複選框的狀態。例如:

import tkinter as tk 
root=tk.Tk() 
c=tk.BooleanVar() 
tk.Checkbutton(root,variable=c,command=lambda: print(c.get())).pack() 
root.mainloop() 

,如果你要循環的一些複選框,你可以這樣做:

import tkinter as tk 
root=tk.Tk() 

c1=tk.BooleanVar() 
c2=tk.BooleanVar() 
c3=tk.BooleanVar() 
c4=tk.BooleanVar() 

def get_value(): 
    for c in (c1,c2,c3,c4): 
     print(c.get()) 

tk.Checkbutton(root,text='checkbox1',variable=c1,).pack() 
tk.Checkbutton(root,text='checkbox2',variable=c2,).pack() 
tk.Checkbutton(root,text='checkbox3',variable=c3,).pack() 
tk.Checkbutton(root,text='checkbox4',variable=c4,).pack() 
tk.Button(root,text='get value',command=get_value).pack() 

root.mainloop()