2

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

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

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

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

4

3 回答 3

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 而制作的字典。如果您想访问一个按钮或其变量,您可以在该字典中找到它。

于 2013-07-24T14:57:50.413 回答
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()

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

再次感谢你:)

于 2013-08-27T12:51:55.953 回答
0

这是我使用复选按钮选择/取消选择所有复选框的解决方法:

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。

于 2016-12-23T13:51:53.630 回答