提问人:aesh 提问时间:10/10/2023 最后编辑:aesh 更新时间:10/10/2023 访问量:44
如何使用函数和循环将值插入到树视图中?(不插入)
How can I insert values into a Treeview using a function and a loop? (not insert)
问:
我想将值插入到 Treeviews 的 Badge 列中,使用 (not ) 和循环4, 1, 7, 5, 9, 3
column = function()
treeview.insert
如您所见,我解压缩了每个列表,然后用 .而且我也使用 .我知道有更好的方法,但我需要维护这段代码。Rank = record[0], Name = record[1], and Badge = example()
values = datagrid
目前在 Treeview 的 Badge 列中,我看到 .相反,我想打印4, 4, 4, 4, 4, 4
4, 1, 7, 5, 9, 3
from tkinter import *
from tkinter import ttk
ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws['bg']='#fb0'
data = [
[1,"Jack"],
[2,"Tom"],
[3,"Daniel"],
[4,"Leonard"],
[5,"Frank"],
[6,"Robert"],
]
tv = ttk.Treeview(ws)
tv['columns']=('Rank', 'Name', 'Badge')
tv.column('#0', width=0, stretch=NO)
tv.column('Rank', anchor=CENTER, width=80)
tv.column('Name', anchor=CENTER, width=80)
tv.column('Badge', anchor=CENTER, width=80)
tv.heading('#0', text='', anchor=CENTER)
tv.heading('Rank', text='Id', anchor=CENTER)
tv.heading('Name', text='rank', anchor=CENTER)
tv.heading('Badge', text='Badge', anchor=CENTER)
tv.pack()
def func1():
def example():
x = [
["4"],
["1"],
["7"],
["5"],
["9"],
["3"],
]
for a in x:
return a
for index, record in enumerate(data):
Rank = record[0]
Name = record[1]
Badge = example()
datagrid = [Rank, Name, Badge]
tv.insert(parent='', index='end', values=(datagrid))
button = Button(ws, text="Button", command = func1)
button.place(x=1, y=1)
ws.mainloop()
答:
2赞
furas
10/10/2023
#1
在函数中使用它将从一开始就运行函数中的所有代码,并且它将始终使用列表中的第一个元素。return
您必须使用 而不是 .它将创建生成器,并且还需要从生成器中获取下一个值。yield
return
next()
def example():
x = [
["4"],
["1"],
["7"],
["5"],
["9"],
["3"],
]
for a in x:
yield a
gen = example()
for index, record in enumerate(data):
Rank = record[0]
Name = record[1]
Badge = next(gen)
# ... rest ...
您也可以直接在不使用生成器(它需要在之后正确分配值for
next()
( )
for
zip()
)
gen = example()
for (index, record), Badge in zip(enumerate(data), gen):
Rank = record[0]
Name = record[1]
# ... rest ...
但坦率地说,我会直接使用而不创建x
example()
x = [["4"],["1"],["7"],["5"],["9"],["3"],]
for (index, record), Badge in zip(enumerate(data), x):
Rank = record[0]
Name = record[1]
# ... rest ...
评论
return
yield
return