如何更新tkinter中的某个小部件

2024-05-20 00:00:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更新标签的位置,所以在用.place()方法替换它之后,我使用.update()方法。问题是,我的窗口上的所有小部件都会得到更新,我不希望这样,因为程序工作更努力,我在“移动”标签时会看到滞后。我能做什么

...
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()
...

事实上,我想在update_label函数中替换多个标签,但我想让示例更容易理解


Tags: the方法程序here部件defupdateplace
2条回答

您可以使用.update()方法,但是您的代码有一些问题

首先,将tk属性与标签一起使用,而不是与按钮一起使用。尽量保持一致

我修改了你的代码,使它更干净。它现在起作用了:

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()

希望这有帮助

编辑:

写入l.update()不会更新或移动任何其他小部件。如果希望移动/更新所有小部件,则必须将它们放入update_label()函数中

希望这有帮助

要更新单个小部件的位置,可以使用^{}方法临时删除它,然后使用新值调用其place()方法(再次)重新定位它。由于您似乎希望根据小部件当前所在的位置更新位置,因此首先使用place_info()小部件方法从中检索有关小部件当前位置的信息

下面是一个基于您问题中代码的可运行示例,它说明了我的建议:

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()

相关问题 更多 >