我编写了以下 tkinter 脚本来了解如何将数据列表添加到 tkinter.Listbox 小部件中。我发现了 2 种方法。
接下来,我想从 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']
最佳答案
您不能使用 StringVar
作为 listvariable
属性的目标。如您的代码所示,这会导致列表转换为字符串。
然而,您可以做的是使用 tk.Variable
的实例。 Variable
是 StringVar
的基类。 get
的基本实现不会将值强制转换为字符串。
name1 = ['Peter', 'Scotty', 'Walter', 'Scott', 'Mary']
self.lb1_values = tk.Variable(value=name1)
self.listbox1 = tk.Listbox(self, listvariable=self.lb1_values)
...
e1 = self.lb1_values.get()
print('e1 = ', e1)
print('type(e1) = ', type(e1))
print('e1 = ', e1)
上面的代码产生了这样的输出:
e1 = ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary')
type(e1) = <class 'tuple'>
e1 = ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary')
对于 e2 和 e3,您必须跳过一个额外的圈。不幸的是,cget
方法返回的是内部变量名,而不是对变量对象的引用。要通过名称获取变量的值,您需要使用小部件方法 getvar
。
例如:
e2 = self.listbox1.cget('listvariable')
print('\ne2 = ', e2)
print('type(e2) = ', type(e2))
print('e2 = ', self.getvar(e2))
上面的代码产生了这样的输出:
e2 = PY_VAR0
type(e2) = <class 'str'>
e2 = ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary')
关于python - 从 tkinter.Listbox 中提取项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48618665/