【问题标题】:How can i update a certain widget in tkinter我如何更新 tkinter 中的某个小部件
【发布时间】:2020-05-13 20:01:21
【问题描述】:

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

...
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函数中替换多个标签,但我想让例子更容易理解。

【问题讨论】:

  • 我该怎么写?(你能写出整个表达式吗?)
  • Gheorghe:抱歉,我之前关于使用config() 方法的评论不适用——它用于更新小部件的选项,如颜色、大小等,不是位置。请参阅我发布的有关如何执行此操作的答案。

标签: python tkinter widget


【解决方案1】:

您可以使用.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() 函数中。

希望这会有所帮助!

【讨论】:

  • 这看起来不会只更新特定标签。我不想更新程序中的所有其他小部件(框架、按钮、标签等)。如果我写 l.update() 就像我写 root.update() 一样,我不想要这个。
  • 如果我写 l.update() 就像我写 root.update() 一样,我不想要这个。这是什么意思?
  • 哦,我明白你的意思了。如果我在窗口上放置了太多小部件这一事实可能会导致延迟移动,您是否有想法?我的意思是,我试图评论我创建和放置这些多个小部件(按钮、标签、框架等)的代码的一部分,并且只让我想要移动的标签,我注意到 movemet这些标签更快更流畅。
  • @GheorgheGh 如果它是滞后的,这意味着你的窗口上有太多的小部件。通常要解决此问题,您可以将文件转换为 exe 文件,然后它会运行得更快。
【解决方案2】:

要更新单个小部件的位置,您可以使用place_forget() 方法暂时将其移除,然后使用新值调用其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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多