【问题标题】:get Object from a tkinter listbox从 tkinter 列表框中获取对象
【发布时间】:2019-12-20 05:31:55
【问题描述】:

我使用def __ str__ 创建了一个名为“client”的类,因此我可以在列表框中添加客户端列表并显示客户端名称而不是<object at 0x etc> 内存名称。

问题是当我将客户端添加到listbox 时,我想使用事件函数从列表中获取选择,来自listbox 的不是对象本身,而是来自@ 的字符串987654325@。 如何更改代码以获取对象实例而不是字符串名称?

class PageOne(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        label = Label(self, text="Clientes", font=LARGE_FONT)
        label.pack(pady=10, padx=10)
        button = Button(self, text="Voltar", 
                        command=lambda:controller.show_frame(StartPage))
        button.place(x=330, y=50)

        self.listbox = Listbox(self, height=17, width=25)
        self.listbox.place(x=25, y=110)

        scrollbar = Scrollbar(self.listbox, orient="vertical")
        scrollbar.config(command=self.listbox.yview)
        scrollbar.place(height=273, x=134)

        self.listbox.config(yscrollcommand=scrollbar.set)
        self.listbox.bind('<<ListboxSelect>>', self.onselect)

        for client in clients:
            self.listbox.insert(END, client)

        # creating the gui
        label = Label(self, text="Nome:", font=MEDIUM_FONT)
        label.place(x=250, y=120)
        self.name_var = StringVar()
        self.name_var.set(clients[0].name)
        name_label = Label(self, textvariable=self.name_var, font=MEDIUM_FONT)
        name_label.place(x=330, y=120)

    def onselect(self, evt):
        w = self.listbox.get(self.listbox.curselection())
        self.name_var.set(w)
        print(w)

我想创建一个 GUI,这样我每次按下 listbox 时都可以更改客户端的名称/年龄/国家/地区,例如有关所选客户端的信息 GUI。这就是我需要该对象的原因,以便我可以编辑我创建的StringVars

“w”变量只是我的客户端名称的字符串,而不是客户端本身,这就是我想要更改但不知道如何更改。

class Client:
    def __init__(self, name, gsm, local, tp, email=None, served=False):
        self.name = name
        self.gsm = gsm
        self.email = email
        self.local = local
        self.tp = tp
        self.served = served

    def __str__(self):
        return self.name

【问题讨论】:

  • 获取object instance 而不是字符串名称?做client_object = clients[self.listbox.curselection()]
  • @stovfl 我完全忘记了客户端和列表框的排序方式相同,你刚刚睁开了我的眼睛!!非常感谢!

标签: python tkinter


【解决方案1】:

@stovfl 的回答:

获取对象实例而不是字符串名称?做client_object = clients[self.listbox.curselection()[0]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2014-09-28
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多