从tkinter.Listbox中提取项目列表

2024-04-24 22:21:37 发布

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

我编写了下面的tkinter脚本,以了解如何将数据列表添加到tkinter.Listbox小部件中。我发现了两种方法。

接下来,我想从tkinter.Listbox小部件中提取相同的列表。在4种不同的方法中,我只设法使第4种方法(即e4)起作用。

我怎样才能让e1、e2和e3通道工作?最终目标是获得最初提供给tkinter.Listbox小部件的相同列表。

测试脚本:

import tkinter as tk # Python 3 tkinter modules
import tkinter.ttk as ttk

class App(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        # 1. Initialise Frame
        ttk.Frame.__init__(self, parent)
        self.parent = parent

        # Method1
        name1 = ['Peter', 'Scotty', 'Walter', 'Scott', 'Mary']
        self.lb1_values = tk.StringVar(value=name1)
        self.listbox1 = tk.Listbox(self, listvariable=self.lb1_values)

        # Method2
        self.listbox2 = tk.Listbox(self)
        name2 = ['Sarah', 'Sean', 'Mora', 'Mori', 'Mary']
        for item in name2:
            self.listbox2.insert(tk.END, item)

        self.listbox1.grid(in_=self, row=0, column=0, sticky='nsew')
        self.listbox2.grid(in_=self, row=0, column=1, sticky='nsew')

        # Extract values from listbox and covert to a list
        e1 = self.lb1_values.get()
        print('e1 = ', e1)
        print('type(e1) = ', type(e1))
        e1 = e1.strip(',')
        print('e1 = ', e1)

        e2 = self.listbox1.cget('listvariable')
        print('\ne2 = ', e2)
        print('type(e2) = ', type(e2))
        e2 = e2.split(',')
        print('e2 = ', e2)

        e3 = self.listbox2.cget('listvariable')
        print('\ne3 = ', e3)
        print('type(e3) = ', type(e3))

        e4 = self.listbox2.get(0, tk.END)
        print('\ne4 = ', e4)
        print('type(e4) = ', type(e4))
        e4 = list(e4)
        print('e4 = ', e4)    


if __name__ == '__main__':
    root = tk.Tk()
    root.title('App'), root.geometry('400x200')
    app = App(root)
    app.grid(row=0, column=0, sticky='nsew')
    #root.mainloop()

输出:

e1 =  ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary')
type(e1) =  <class 'str'>
e1 =  ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary')

e2 =  PY_VAR0
type(e2) =  <class 'str'>
e2 =  ['PY_VAR0']

e3 =  
type(e3) =  <class 'str'>

e4 =  ('Sarah', 'Sean', 'Mora', 'Mori', 'Mary')
type(e4) =  <class 'tuple'>
e4 =  ['Sarah', 'Sean', 'Mora', 'Mori', 'Mary']

Tags: selftkintertyperoottkclassprintttk