【问题标题】:Using list in parameter to create radiobuttons in GUI使用参数中的列表在 GUI 中创建单选按钮
【发布时间】:2020-03-12 12:30:19
【问题描述】:

我使用列表作为 GUI 窗口的参数,并且列表中的每个单独项目都应该在 GUI 窗口中创建为单选按钮。目前,我使用一个 for 循环为每个单选按钮生成不同的值,并使用另一个 for 循环生成不同的列。但是,我只能为列表中的最后一项创建单选按钮。

这是我目前拥有的:

from tkinter import *
from tkinter.scrolledtext import *

class ExpenditureGUI:

def __init__(self, listOfCategories):
    self._listOfCategories = listOfCategories
    self._tk = Tk()
    self._tk.title('Expenditure Tracker')     
    self._tk.geometry('500x200')        
    self._tk.resizable(False,False)
    self.initWidgits()
    self._tk.mainloop()


@property    
def listOfCategories(self):
    return self._listOfCategories
@listOfCategories.setter
def listOfCategories(self, newValue):
    self._listOfCategories = newValue

def initWidgits(self):
    #flow layout
    topF = Frame(self._tk)
    self._lblAmount = Label(topF, text = 'Amount: ')      
    self._txtAmount = Entry(topF, width=30)


    rbtnF = Frame(topF)
    self._rbtnVar = IntVar()  
    self._rbtnVar.set(0)  
    self._lblExpenditure = Label(topF, text = 'Type of Expenditure: ')

    n = 0
    for type in self._listOfCategories:
        self._rbtntype = Radiobutton(rbtnF, text = f'{type}', value = n, variable = self._rbtnVar)


    self._lblExpenditure.grid(row = 0, column = 0, sticky = E)

    n = 0
    for type in self._listOfCategories:
        self._rbtntype.grid(row = 0, column = n)

【问题讨论】:

    标签: python oop user-interface tkinter


    【解决方案1】:

    我不是 GUI 库方面的专家,但这看起来很可疑:

    for type in self._listOfCategories:
            self._rbtntype = Radiobutton(rbtnF, text = f'{type}', value = n, variable = self._rbtnVar)
                                                ^^^^^^^^^^^^^^^^
    

    在此循环结束后,self._rbtntype 变量将包含仅引用类别列表中的 last 元素的文本(即循环变量 type)。

    您可能希望在代码示例的最后一个循环中构造一个新的Radiobutton。也许这样的事情会奏效。它可能需要在每次循环迭代中更新n

    for type in self._listOfCategories:
        rbtntype = Radiobutton(rbtnF, text = f'{type}', value = n, variable = self._rbtnVar)
        rbtntype.grid(row = 0, column = n)
    

    【讨论】:

    • 已解决!我意识到第一个循环没有创建任何单选按钮,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2011-01-01
    • 1970-01-01
    • 2012-10-15
    • 2015-04-06
    相关资源
    最近更新 更多