2016-05-19 7 views
0

私のプログラムで処理されるディレクトリにファイルのリストを提示したいと思います。私はPythonでTkinterを使用します。Tkinterのチェックボタンでリストの状態を変更してください

私がヒットした唯一の方法は、各ファイルがリストで表されるファイルのリストを作成することです。最初の値はファイル名、2番目はproccess 0の場合は1です。

os.chdir("/home/user/files") 
for file in glob.glob("*.txt"): 
    listOfFiles.append([file, 0]) 

for f in listOfFiles: 
    c = Checkbutton(root, text=f[0], variable=f[1]) 
    c.pack() 

実際には、各ファイルの2番目の項目は変更されないため、このコード部分は機能しません。私のアプローチには良い解決策はありますか?

答えて

0

Checkbuttonステートメントにコマンドコールバックを配置するか、Buttonを使用してそれらを処理する必要があります。最も簡単な方法は、チェックされた各ファイルを別のリストに追加し、そのリストを処理することです。したがって、以下のサンプルコードでは、「何かがチェックされています」の代わりに、ファイル名(プログラムのチェックボックスのテキスト)を別のリストに追加します。

try: 
    import Tkinter as tk  # Python2 
except ImportError: 
    import tkinter as tk  # Python3 

def cb_checked(): 
    # show checked check button item(s) 
    label['text'] = '' 
    for ix, item in enumerate(cb): 
     if cb_v[ix].get():  ## IntVar not zero==checked 
      label['text'] += '%s is checked' % item['text'] + '\n' 

root = tk.Tk() 

cb_list = [ 
'apple', 
'orange', 
'banana', 
'pear', 
'apricot' 
] 

# list(range()) needed for Python3 
# list of each button object 
cb = list(range(len(cb_list))) 
# list of IntVar for each button 
cb_v = list(range(len(cb_list))) 
for ix, text in enumerate(cb_list): 
    # IntVar() tracks checkbox status (1=checked, 0=unchecked) 
    cb_v[ix] = tk.IntVar() 
    # command is optional and responds to any cb changes 
    cb[ix] = tk.Checkbutton(root, text=text, 
          variable=cb_v[ix], command=cb_checked) 
    cb[ix].grid(row=ix, column=0, sticky='w') 

label = tk.Label(root, width=20) 
label.grid(row=ix+1, column=0, sticky='w') 

# you can preset check buttons (1=checked, 0=unchecked) 
cb_v[3].set(1) 
# show initial selection 
cb_checked() 

root.mainloop() 
+0

この目的のためにボタンも使いやすいですか? – siema

関連する問題