【问题标题】:Tkinter - Removing multiple records with checkboxesTkinter - 使用复选框删除多条记录
【发布时间】:2020-11-05 20:34:10
【问题描述】:

我正在尝试填充结果列表(在此示例中来自 python 列表)并为每个结果提供它自己的 Checkbutton。这适用于 TK 按钮代码中的 variable=Variable() 部分,但我不确定它是如何工作的。 生成结果后,我需要能够选择它们,然后删除所选的。我正在寻求帮助以获取每个复选框的状态,以便我可以删除该条目。这是我到目前为止的代码。

from tkinter import *

root = Tk()
root.title("DB Sandbox")
root.geometry("400x400")

def del_selected():
    pass

results = ['one', 'two', 'three', 'four']

for result in results:
        l = Checkbutton(root, text=result, variable=Variable())
        l.pack()

delbutt = Button(root, text="Delete Selected", command=del_selected)
delbutt.pack(pady=10)


root.mainloop()

对此的任何指导都非常感谢!

【问题讨论】:

  • 什么是Variable() 创建/返回?
  • 当我开始构建它时,我发现使用它作为循环遍历列表并创建输出的解决方案。正如我上面所说,我不太确定该类是如何工作的。当试图研究它时,我找不到解释。希望这里有人会。
  • variable=Variable() 这到底是什么意思?或者你想做什么?用那个?
  • tkinter 支持多种"variable" classesintVars 经常与Checkbox 小部件一起使用。没有更多上下文,很难理解您的问题或您要完成的任务。
  • @martineau 和@CoolCloud VariableStringVarIntVar 等的基类,一般不应该直接使用。

标签: python tkinter checkbox


【解决方案1】:

正如 cmets 中提到的@acw1668,Checkbutton 可能不是此任务的最佳选择,但如果您真的想要,您需要跟踪每个复选框并且它是可变的,如下所示:

from tkinter import *

root = Tk()
root.title("DB Sandbox")
root.geometry("400x400")

def del_selected():
    global check_buttons, butt_vars # the best approach would be OOP, but this works
    for button, var in zip(check_buttons, butt_vars):
        if var.get(): # button selected: var.get() == 1, otherwise: var.get() == 0
            button.forget() # remove it from the geometry manager

results = ['one', 'two', 'three', 'four']
# this holds the variables to check whether the checkbox is selected or not
butt_vars = [IntVar() for _ in range(len(results))]
# this holds the checkbutton instances
check_buttons = [Checkbutton(root, text=x, variable=butt_vars[i]) for i, x in enumerate(results)]

for butt in check_buttons:
        butt.pack()

delbutt = Button(root, text="Delete Selected", command=del_selected)
delbutt.pack(pady=10)


root.mainloop()

【讨论】:

  • 我认为OP也想删除results中的选定项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多