1

The first set of code works. It displays the updating variable. However, in the second code, when I put the variable in a Treeview widget instead, the variable just stays on 0 and does not update. How come this works with the label but not with treeview? What is the easiest way to fix this?

First (works):

from tkinter import *
from tkinter import ttk
import threading
import time

def fun():
    for i in range(10):
        var.set(var.get() + 1)
        time.sleep(.5)

t = threading.Thread(target=fun)

root = Tk()

var = IntVar()
var.set(0)

mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)
label = ttk.Label(mainframe, textvariable=var)
label.grid(column = 0, row = 0)

t.start()
root.mainloop()

Second (does not work):

from tkinter import *
from tkinter import ttk
import threading
import time

def fun():
    for i in range(10):
        var.set(var.get() + 1)
        time.sleep(.5)

t = threading.Thread(target=fun)

root = Tk()

var = IntVar()
var.set(0)

mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)

tree = ttk.Treeview(mainframe, columns = ('number'), height = 1)

tree.insert('', 'end', text = 'Number', values = var.get())
tree.grid(column=0, row=0)

t.start()
root.mainloop()

1 Answer 1

1

modify fun to :

def fun():
    for i in range(10):
        var.set(var.get() + 1)
        x = tree.get_children()
        tree.item(x, text = 'Number', values = var.get())
        time.sleep(.5)

The get_children method returns a list of tuples item IDs, one for each child of the tree. With tree.item then update the child with the required id.

In the second program along with the variable var, you also have to update the child of the tree

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. How come the value doesn't update automatically like the first example?
How come i have to update each child of the tree when in the first example has the label changing automatically? When I receive a new piece of data from my streaming data source I was hoping to not have to update all the children as many of the values may not have changed.
@AndrewK, whatever you insert into a tree automatically makes it a child of the tree. this may help for better understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.