如何使用循环在Python中创建radiobuttons

时间:2017-04-16 05:34:00

标签: python tkinter

我必须创建多个单选按钮。每个网格都有自己的名称和位置。还涉及几个变量。

我存储了所有数据,以便在元组中创建这些单选按钮 (我知道FONTS不会引起问题,它存储在上面但不会在这里显示):

    self.unitType = IntVar()
    self.matPropSel = IntVar()
    self.secProfSel = IntVar()
    self.endSupSel = IntVar()
    self.loadTypeSel = IntVar()

     self.RADIOLABELS = (  # Text, Font, Variable, Value, Row, Column
        ('English', self.FONTS[3], self.unitType, 1, 3, 1),
        ('metric', self.FONTS[3], self.unitType, 2, 4, 1),
        ('select preset', self.FONTS[3], self.matPropSel, 1, 6, 1),
        ('manual entry', self.FONTS[3], self.matPropSel, 2, 7, 1),
        ('select preset', self.FONTS[3], self.secProfSel, 1, 10, 1),
        ('manual entry', self.FONTS[3], self.secProfSel, 2, 11, 1),
        ('one end', self.FONTS[3], self.endSupSel, 1, 15, 1),
        ('both ends', self.FONTS[3], self.endSupSel, 2, 16, 1),
        ('point', self.FONTS[3], self.loadTypeSel, 1, 18, 1),
        ('uniform distribution', self.FONTS[3], self.loadTypeSel, 2, 19, 1),
        ('uniform variation', self.FONTS[3], self.loadTypeSel, 3, 20, 1)
     )

那么,我如何使用for循环来完成这个元组并从每一行生成一个单选按钮?所有变量都必须相同吗?我遇到了问题。

这是我尝试循环:

    outerIndexer = 0
    for labels in self.RADIOLABELS:
        Radiobutton(self, text=self.RADIOLABELS[outerIndexer][0], font=self.RADIOLABELS[outerIndexer][1],
                    variable=self.RADIOLABELS[outerIndexer][2], value=self.RADIOLABELS[outerIndexer][3])\
            .grid(row=self.RADIOLABELS[outerIndexer][4], column=self.RADIOLABELS[outerIndexer][5])
    outerIndexer += 1

1 个答案:

答案 0 :(得分:1)

你可以通过循环RADIOLABELS这样做。注意:还建议将按钮保存到列表中,以免丢失。

self.RADIOLABELS = (  # Text, Font, Variable, Value, Row, Column
    ('English', self.FONTS[3], self.unitType, 1, 3, 1),
    ('metric', self.FONTS[3], self.unitType, 2, 4, 1),
    ('select preset', self.FONTS[3], self.matPropSel, 1, 6, 1),
    ('manual entry', self.FONTS[3], self.matPropSel, 2, 7, 1),
    ('select preset', self.FONTS[3], self.secProfSel, 1, 10, 1),
    ('manual entry', self.FONTS[3], self.secProfSel, 2, 11, 1),
    ('one end', self.FONTS[3], self.endSupSel, 1, 15, 1),
    ('both ends', self.FONTS[3], self.endSupSel, 2, 16, 1),
    ('point', self.FONTS[3], self.loadTypeSel, 1, 18, 1),
    ('uniform distribution', self.FONTS[3], self.loadTypeSel, 2, 19, 1),
    ('uniform variation', self.FONTS[3], self.loadTypeSel, 3, 20, 1)
 )

radiobuttons = []
for _Text, _Font, _Variable, _Value, _Row, _Column in self.RADIOLABELS: # it will unpack the values during each iteration
    _Radio = tk.Radiobutton(root, text = _Text, font = _Font, variable = _Variable, value = _Value)
                           # ^ root should be the frame/Tk you're trying to place it on, it will be self if this is a direct subclass of a Frame or Tk
            # ^ or Radiobutton(.....) if you did from tkinter import *
    _Radio.grid(row = _Row, column = _Column)
    radiobuttons.append(_Radio)