Python 3.TTK。如何更改特定单元格的值?

Python 3. TTK. How to change value of the specific cell?

我对 tkinter/ttk 有一些疑问。

所以,我知道如何获取 Treeview.focus,但如何更改此 table 中特定单元格的值?有什么建议吗?

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()

tview = ttk.Treeview(root)
tview["columns"] = ("SLOT_1","SLOT_2")
tview.column("SLOT_1", width=100 )
tview.column("SLOT_2", width=100)

tview.heading("#0",text="Column 0",anchor="w")
tview.heading("SLOT_1", text="Column 1")
tview.heading("SLOT_2", text="Column 2")

def add_item():
    tview.insert("","end",values=("","bar"))

def edit_item():
    focused = tview.focus()
    print(tview.item(focused))

tview.pack()

add_item = tk.Button(root,text="Add item",command=add_item)
add_item.pack(expand=True,fill='both')

edit_item = tk.Button(root,text="Edit item",command=edit_item)
edit_item.pack(expand=True,fill='both')

root.mainloop()

我正在使用 Python 3.6tkinter/ttk

我添加了一个线程,这样程序在等待用户输入编辑时不会挂起。您可能想要为要输入的编辑添加一个或多个文本框

import tkinter as tk
import tkinter.ttk as ttk
import threading

root = tk.Tk()

tview = ttk.Treeview(root)
tview["columns"] = ("SLOT_1", "SLOT_2")
tview.column("SLOT_1", width=100)
tview.column("SLOT_2", width=100)

tview.heading("#0", text="Column 0", anchor="w")
tview.heading("SLOT_1", text="Column 1")
tview.heading("SLOT_2", text="Column 2")

def test_program_thread():
    thread = threading.Thread(None, edit_item, None, (), {})
    thread.start()

def add_item():
    tview.insert("", "end", values=("", "bar"))


def edit_item():
    focused = tview.focus()
    x = input('Enter a Value you want to change')
    tview.insert("", str(focused)[1:], values=("", str(x)))
    tview.delete(focused)

tview.pack()

add_item = tk.Button(root, text="Add item", command=add_item)
add_item.pack(expand=True, fill='both')

edit_item_button = tk.Button(root, text="Edit item", command=test_program_thread)
edit_item_button.pack(expand=True, fill='both')

root.mainloop()

基于 .

使用单个 .item 更新行而不是使用 .insert 添加新行然后使用 .delete 删除旧行将有助于包含 9 行以上的 Treeview 并将更新的行保留在在树视图中的相同位置。

修改后的完整代码 :

tview = ttk.Treeview(root)
tview["columns"] = ("SLOT_1", "SLOT_2")
tview.column("SLOT_1", width=100)
tview.column("SLOT_2", width=100)

tview.heading("#0", text="Column 0", anchor="w")
tview.heading("SLOT_1", text="Column 1")
tview.heading("SLOT_2", text="Column 2")

def test_program_thread():
    thread = threading.Thread(None, edit_item, None, (), {})
    thread.start()

def add_item():
    tview.insert("", "end", values=("", "bar"))


def edit_item():
    focused = tview.focus()
    x = input('Enter a Value you want to change')
    tview.item(focused, values=("", str(x)))

tview.pack()

add_item = tk.Button(root, text="Add item", command=add_item)
add_item.pack(expand=True, fill='both')

edit_item_button = tk.Button(root, text="Edit item", command=test_program_thread)
edit_item_button.pack(expand=True, fill='both')

root.mainloop()