python-3.x - 通过 Tkinter 中的列表变量修改列表框条目

标签 python-3.x tkinter

我在教程中读到我可以将数据从 tkinter.Listbox 分离到我自己的列表中。我在这里的例子中这样做了。 但是我如何根据我自己的变量列表来操纵列表框条目的顺序?

#!/usr/bin/env python3

from tkinter import *

root = Tk()
mylist = ['one', 'two', 'three']
var = StringVar(value=mylist)
box = Listbox(master=root, listvariable=var)
box.pack(fill=BOTH, expand=True)

# this need to affect the list
mylist.append('four')
mylist.remove('two')
mylist.insert(3, mylist.pop(1))

root.mainloop()

此处的列表框(在 GUI 中)不受影响。

据我所知,当我修改数据列表时,Listbox 绝对会自动刷新其内容。所以我不必触摸 Listbox。我只需要触摸 list() 中的数据。

有办法吗?

最佳答案

Listboxget()delete()insert()
您可以从 box 中获取值,将其移除并放入新位置。

或者您可以从 box 中删除所有项目并从 mylist 添加新项目。
我觉得这个方法比较通用。

box.delete(0, 'end')
for item in mylist:
    box.insert('end', item)

因为你使用了listvariable所以你可以直接在var中替换list

var.set(mylist)

完整代码

from tkinter import *

root = Tk()

mylist = ['one', 'two', 'three']

var = StringVar(value=mylist)
box = Listbox(master=root, listvariable=var)
box.pack(fill=BOTH, expand=True)

mylist.append('four')
mylist.remove('two')
mylist.insert(3, mylist.pop(1))

var.set(mylist)

root.mainloop()

关于python-3.x - 通过 Tkinter 中的列表变量修改列表框条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47383170/

相关文章:

python-3.x - 试图找到一种在引用前一行的 Pandas 中使用 while 循环的有效方法

python - 如何在 Tkinter 中更改图像的分辨率?

python - 让 Anaconda 的 tkinter 了解系统字体或为 Anaconda 安装新字体

python - 我的计算器 Python Tkinter 的按钮大小

Python断言语句和代码可重用性

python - 具有所有静态方法的类

python - 尝试注释哈希变量时,“ABCMeta”对象不可下标

python - .iconbitmap 给出 TclError : bitmap "*.ico" not defined

python - tkinter 顶级窗口不会从系统托盘菜单打开

python - 从python3中的文件中读取字节字符串