收集由for循环创建的多个tkinter复选框的输入 [英] Gather input from multiple tkinter checkboxes created by a for loop

查看:64
本文介绍了收集由for循环创建的多个tkinter复选框的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用tkinter制作了一个应用程序,该应用程序创建了一些数据的复选框列表.复选框是根据数据集的大小动态创建的.我想知道一种获取每个特定复选框输入的方法.

I made an application with tkinter which creates a list of checkboxes for some data. The checkboxes are created dynamically depending on the size of the dataset. I want to know of a way to get the input of each specific checkbox.

这是我的代码,您应该可以运行它.

Here is my code, which you should be able to run.

from tkinter import *

root = Tk()

height = 21
width = 5

for i in range(1, height):
    placeholder_check_gen = Checkbutton(root)
    placeholder_check_gen.grid(row=i, column=3, sticky="nsew", pady=1, padx=1)

for i in range(1, height):
    placeholder_scope = Checkbutton(root)
    placeholder_scope.grid(row=i, column=4, sticky="nsew", pady=1, padx=1)

root.mainloop()

我查看了其他答案,有些人通过在复选框设置"variable = x"中定义一个变量来逃脱现实.然后使用"show():"调用该变量具有"variable.get()"的函数;里面.如果有人可以给我指出正确的方向,或者我该如何进行.谢谢,非常感谢.

I looked over other answers and some people got away by defining a variable inside the checkbox settings "variable=x" and then calling that variable with a "show():" function that would have "variable.get()" inside. If anyone could please point me in the right direction or how I could proceed here. Thank you and much appreciated.

推荐答案

通常,您需要为每个检查按钮创建 IntVar StringVar 的实例.您可以将它们存储在列表或字典中,然后以通常的方式检索值.如果您不创建这些变量,则会为您自动创建它们.在这种情况下,您需要保存对每个复选框的引用.

Normally you need to create an instance of IntVar or StringVar for each checkbutton. You can store those in a list or dictionary and then retrieve the values in the usual way. If you don't create these variables, they will be automatically created for you. In that case you need to save a reference to each checkbutton.

这里是保存参考的一种方法:

Here's one way to save a reference:

self.general_checkbuttons = {}
for i in range(1, self.height):
    cb = Checkbutton(self.new_window)
    cb.grid(row=i, column=3, sticky="nsew", pady=1, padx=1)
    self.general_checkbuttons[i] = cb

然后,您可以在相同范围内进行迭代以获取值.为此,我们首先向小部件询问其关联变量的名称,然后使用tkinter的 getvar 方法获取该变量的值.

Then, you can iterate over the same range to get the values out. We do that by first asking the widget for the name of its associated variable, and then using tkinter's getvar method to get the value of that variable.

for i in range(1, self.height):
    cb = self.general_checkbuttons[i]
    varname = cb.cget("variable")
    value = self.root.getvar(varname)
    print(f"{i}: {value}")

这篇关于收集由for循环创建的多个tkinter复选框的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆