如何在Python中使用循环创建单选按钮

2024-09-27 09:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我把创建这些单选按钮的所有数据存储在一个元组中 (我知道字体不会引起问题,它存储在上面,但不会显示在这里):

    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循环遍历这个元组并从每一行生成一个单选按钮呢?所有的变量都必须相同吗?我和他们有问题。在

下面是我的循环尝试:

^{pr2}$

Tags: selffontsuniformmanualselect按钮元组preset
1条回答
网友
1楼 · 发布于 2024-09-27 09:34:37

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

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)

相关问题 更多 >

    热门问题