How can i update a certain widget in tkinter

Viewed 2161

I want to update the position of a label, so I use .update() method, after I replace it with .place() method. The problem is that all my widgets, that are on my window, get updated and I do not want this, because the program is working harder, and I see lag while "moving" my label. What can I do?

...
def update_label:
     l.place(relx = 0.2, rely = 0.1+0.2)
     l.update()#here the program is updating every widget

l=tk.Label(root)
l.place(relx = 0.2, rely = 0.1)

b=Button(root,command(update_label()))
b.pack()
...

In fact, I want to replace more than one label in update_label function, but I wanted to make the example easier to understand.

2 Answers

You can use the .update() method, but there are a few things wrong with your code.

First off, you use the tk attribute with the label, but not with the button. Try to be consistent.

I reworked your code and made it cleaner. It now works:

import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
x = 0.2
y = 0.1

l = tk.Label(root, text = "label")
l.place(relx = x, rely = y)
def update_label():
    global x, y
    y += 0.2
    l.place(relx = x, rely = y)
    l.update()#here the program is updating every widget


b = tk.Button(root,text = "update", command = update_label)
b.pack()

Hope this helps!

Edit:

Writing l.update() won't update or move any other widgets. If you wish to move/update all widgets, then you must put them in the update_label() function.

Hope this helps!

To update the position of a single widget, you can use the place_forget() method to temporarily remove it and then call its place() method (again) with new values to reposition it. Since it appears you want to update the position based on the where the widget currently is, information about the widget's current position is retrieved from it first using the place_info() widget method.

Here's a runnable example based on the code in your question that illustrates what I'm suggesting:

import tkinter as tk

root = tk.Tk()
root.geometry("800x600")


def update_label(lbl):
    info = lbl.place_info()  # Get dictionary of widget's current place options.

    cur_relx = float(info['relx'])  # Get current value of relative x.
    cur_rely = float(info['rely'])  # Get current value of relative y.

    lbl_1.place_forget()  # Remove widget from current manager.
    lbl_1.place(relx=cur_relx, rely=cur_rely+0.2)  # Add it back with updated y position.


lbl_1 = tk.Label(root, text='Label 1')
lbl_1.place(relx=0.2, rely=0.1)

lbl_2 = tk.Label(root, text='Label 2')
lbl_2.place(relx=0.2, rely=0.2)

btn_1 = tk.Button(root, text='Update', command=lambda lbl=lbl_1: update_label(lbl))
btn_1.pack()

root.mainloop()
Related