在Python中选中“选中所有框”复选框

时间:2013-07-24 13:43:07

标签: user-interface python-2.7 python-3.x tkinter

使用python和tkinter我有一个动态创建大量复选框的应用程序(大约40个),我想在它们之前添加另一个可以检查所有复选框

这方面的一个例子是在电子邮件中......当您想要删除大量电子邮件时,可以选中“全选”复选框。

我的问题是如何将此功能添加到我的python GUI应用程序中。我认为这与chk_btn.config(state="")有关,但我不确定

任何和所有帮助表示赞赏!

3 个答案:

答案 0 :(得分:2)

动态创建复选框通常是个坏主意。它可能导致诸如失去按钮的跟踪之类的问题。但是,我写的这个迷你剧本应该演示如何做你想做的事情:

from Tkinter import *

root = Tk()

# Create a dictionary where the keys are the checkbuttons
# and the values are their BooleanVars
buttons = dict()
for _ in xrange(10):
    buttons[Checkbutton(root)] = BooleanVar()

for button in buttons:
    # Place each button on the window
    button.grid()
    # Hook each button up to its BooleanVar
    button.config(variable=buttons[button])
    # Set each BooleanVar to True
    buttons[button].set(True)

# I printed this just to show what is going on
print buttons

root.mainloop()

让我免于忘记按钮的是我用来存储它们的字典和它们的BooleanVars。如果要访问按钮或其变量,可以在该字典中找到它。

答案 1 :(得分:1)

对于任何感兴趣的人 - 忽略我给出的答案(哎呀),使用这个:

from tkinter import *
root = Tk()
frame = Frame(root).grid()

class state:
    def read_states():
        arry = list(map(lambda var: var.get(), states))
        for n in range(len(arry)):
            print(arry[n])
        print('----')
    def change_states(x):
        for n in range(len(folder1)):
            x[n].set(1)
    def clear_states():
        for n in range(len(states)):
            states[n].set(0)
states = []
bgs = []
folder1 = []
folder2 = []
folder_break = []
for n in range(10):
    var = IntVar()
    chk = Checkbutton(frame, text=n+1, variable=var)
    chk.grid(row=n+3)
    if n < 5:
        folder1.append(var)
    else:
        folder2.append(var)
    states.append(var)


btn_2 = Button(frame, text='Change', command=lambda w=folder1: state.change_states(w))
btn_2.grid(row=1)
btn_3 = Button(frame, text='Change2', command=lambda w=folder2: state.change_states(w))
btn_3.grid(row=1, column=1)
btn_4 = Button(frame, text='Clear', command=state.clear_states)
btn_4.grid(row=2)
btn = Button(frame, text='GO', command=state.read_states)
btn.grid(row=0)

root.mainloop()

这给了我更多的自由和控制,并受到第一个答案的启发。

再次感谢:)

答案 2 :(得分:0)

以下是我使用checkbutton选择/取消选中所有复选框的方法:

import Tkinter as tk

def select_clear_states():
    global Vars, all_states
    states = all_states.get()

    if states == 0:
        for i in range(len(Vars)):
            Vars[i].set(0)
    if states == 1:
        for i in range(len(Vars)):
            Vars[i].set(1)

Vars = []

root = tk.Tk()

all_states = tk.IntVar()
select_all = tk.Checkbutton(root, text = "select/deselect all", 
                            variable = all_states, command = select_clear_states)
select_all.grid(row = 0, column = 0, padx = 5, pady = 1)

for n in range(10):

    var = tk.IntVar()
    Vars.append(var)
    checkbox = tk.Checkbutton(root, text = n+1, variable= Vars[n])
    checkbox.grid(row = n+1, column = 0, padx = 5, pady = 1)     

root.mainloop()

我知道使用全局变量并不是很干净,但我目前懒得进入OOP。