Tkinter / python:如何创建一个检查按钮来选择所有的检查按钮

时间:2017-01-25 15:04:33

标签: python-2.7 tkinter

我使用Tkinter创建了一个复选框列表,但我想选中所有复选框,只有一个复选框。

以下是我的代码的一部分:

root = tk.Tk()
root.title("SOMETHING")

buttons=[]
#If it is checked, then run the file
def callback():
    for var, name in buttons:
        if var.get():
            subprocess.call("python " + "scripts/" + name)

for name in os.listdir("scripts"):
    if name.endswith('.py') or name.endswith('.pyc'):
        if name not in ("____.py", "_____.pyc"):
            var = tk.BooleanVar()
            cb = tk.Checkbutton(root, text=name, variable=var)
            cb.pack()
            buttons.append((var,name))

def select_all():
    if var1.get():
        for i in cb:
            i.select(0,END)

def deselect_all():
    if var2.get():
        for i in cb:
            i.deselect_set(0,END)

var1=tk.BooleanVar()
selectButton = tk.Checkbutton(root, text="Select All", command=select_all, variable=var1)
selectButton.pack()

var2=tk.BooleanVar()
deselectButton = tk.Checkbutton(root, text="None", command=deselect_all, variable=var2)
deselectButton.pack()

submitButton = tk.Button(root, text="Run", command=callback)
submitButton.pack()

root.mainloop()

当我运行该文件并按"选择全部"时,我收到此错误:' str'对象没有属性'选择'。

请帮助谢谢:)

1 个答案:

答案 0 :(得分:0)

我查看了您的代码并附上了一个有效的tkinter代码。将让您使用子进程解决问题。

我的主要评论是你使用控制变量以及如何使用它来获取和设置它们的值是不合适的。我删除了不必要的代码。此外,还向您展示了如何从列表中提取信息。希望这有助于您的tkinter编码之旅。

工作代码:

import tkinter as tk
import os, subprocess

#If it is checked, then run the file
def callback():
    if var.get():
        for i in buttons:
            cmd = "python3 " + filedir +"/" + i[1] #Note:Runs python3 and not python2
            print(cmd)
            subprocess.call(cmd)

def select_all(): # Corrected
    for item in buttons:
        v , n = item
        if v.get():
            v.set(0)
        else:
            v.set(1)

root = tk.Tk()
root.title("SOMETHING")

filedir = 'test'
buttons=[]

for name in os.listdir(filedir):
    if name.endswith('.py') or name.endswith('.pyc'):
        if name not in ("____.py", "_____.pyc"):
            var = tk.IntVar() 
            var.set(0)
            cb = tk.Checkbutton(root, text=name, variable=var)
            cb.pack()
            buttons.append((var,name))

var1=tk.IntVar()
var1.set(0)
selectButton = tk.Checkbutton(root, text="Select All", command=select_all,
                              variable=var1)
selectButton.pack()

submitButton = tk.Button(root, text="Run", command=callback)
submitButton.pack()

root.mainloop()
相关问题