在python 2.7中使用tkinter动态添加复选框

时间:2012-12-13 14:59:58

标签: python user-interface tkinter tk

我想通过预制列表动态地将ckeckbox添加到我的gui。如何使用列表中的名称填充GUI?它们都具有相同类型的功能,因此不应成为问题。

2 个答案:

答案 0 :(得分:3)

如果您想在启动时使用预制列表填充GUI:

from Tkinter import *

root = Tk()

premadeList = ["foo", "bar", "baz"]

for checkBoxName in premadeList:
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

root.mainloop()

如果您想在运行时使用复选框动态填充GUI:

import random
import string
from Tkinter import *

root = Tk()

def addCheckBox():
    checkBoxName = "".join(random.choice(string.letters) for _ in range(10))
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

b = Button(root, text="Add a checkbox", command=addCheckBox)
b.pack()

root.mainloop()

当然,你可以做到这两点:

import random
import string
from Tkinter import *

root = Tk()

def addCheckBox():
    checkBoxName = "".join(random.choice(string.letters) for _ in range(10))
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

b = Button(root, text="Add a checkbox", command=addCheckBox)
b.pack()

premadeList = ["foo", "bar", "baz"]

for checkBoxName in premadeList:
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

root.mainloop()

答案 1 :(得分:1)

使用带有复选框的树视图。

Treeview with checkboxes

How to create a tree view with checkboxes in Python