如何将一组对象属性的值传递到tkinter组合框值中

2024-05-16 00:27:59 发布

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

我希望用包含在某个类的一组对象中的属性值列表填充tkinter组合框。我有一个可行的方法,但随着对象数量的增加,它似乎效率低下

我曾尝试使用while/for语句,但可能由于tkinter值的格式设置而导致语法失败

class Customer:
def __init__(self, name, people):
    self.name = name
    self.people = people

customer1 = Customer("First Customer", ["Brian", "Sally"])
customer2 = Customer("Second Customer", ["Kevin", "James"])
customer3 = Customer("Third Customer", ["Peter", "Sarah"])

customer_list = [customer1, customer2, customer3]

from tkinter import *
from tkinter.ttk import *

window = Tk()
window.title("Command Console")
window.geometry('350x200')

l1 = Label(window, text = "Select a customer.")
l1.grid(column=0,row=0)

b1 = Button(window, text = "Grab")
b1.grid(column=1,row=1)

c1 = Combobox(window)
c1['values'] = customer_list[0].name, customer_list[1].name, 
customer_list[2].name
c1.grid(column=0,row=1)

尽管上面的方法可行,但最好填充i = 0 to i < len(customer_list)或类似的.name值,但是我无法找到一种机制


Tags: 对象方法nameselftkintercolumncustomerwindow
1条回答
网友
1楼 · 发布于 2024-05-16 00:27:59

我不太懂tk,但下面介绍如何通过从列表中构造元组来概括代码:

c1['values'] = tuple(customer.name for customer in customer_list)

这里我用了一个发电机

相关问题 更多 >