使用参数中的列表在GUI中创建单选按钮

2024-09-23 16:29:26 发布

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

我使用了一个列表作为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)

Tags: textfromimportself列表fortkinterdef
1条回答
网友
1楼 · 发布于 2024-09-23 16:29:26

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

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

此循环结束后,self._rbtntype变量将包含仅引用类别列表中最后一个元素的文本(即循环变量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)

相关问题 更多 >