Python 3.x 使用Tkinter,如何在单击按钮时动态更改标签?
将Tkinter与Python结合使用:我需要在单击按钮时更改标签文本,并在按钮处理完成后将其更改为原始值。尝试下面的方法,我无法更改文本。我做错了什么? 使用栅格几何体。 对于标签文本,使用StringVar和set方法更新文本Python 3.x 使用Tkinter,如何在单击按钮时动态更改标签?,python-3.x,user-interface,button,tkinter,Python 3.x,User Interface,Button,Tkinter,将Tkinter与Python结合使用:我需要在单击按钮时更改标签文本,并在按钮处理完成后将其更改为原始值。尝试下面的方法,我无法更改文本。我做错了什么? 使用栅格几何体。 对于标签文本,使用StringVar和set方法更新文本 # one button, one label - in grid geometry - 1 row x 2 cols. # Button text = "Click me" # Label text = "Ready"
# one button, one label - in grid geometry - 1 row x 2 cols.
# Button text = "Click me"
# Label text = "Ready"
# on clicking button:
# while button processing going on: label text = "Processing button 1"
# after button processing done: label text = "Ready"
import tkinter as tk
import time
from functools import partial
def btn_is_clicked(_label_strVar):
## change text
_label_strVar.set(f"Processing button")
## processing sometihng long
print(f"Sleeping...")
time.sleep(3)
## restore text
_label_strVar.set(f"Ready")
print(f"Exitend command")
root = tk.Tk()
root.geometry("200x100")
n_rows = 1
n_cols = 2
## label for messages to user
lbl_msg = tk.StringVar()
lbl = tk.Label(
master=root,
textvariable=lbl_msg,
bg="blue", fg="white",
borderwidth=10,
relief=tk.SUNKEN
)
lbl_msg.set(f"Ready")
## button
btn = tk.Button(
master=root,
text=f"Click me",
borderwidth=10,
relief=tk.RAISED,
command=partial(btn_is_clicked, lbl_msg)
)
## configure the grid
for r_idx in range(n_rows):
root.rowconfigure(r_idx, weight=1, minsize=20)
for c_idx in range(n_cols):
root.columnconfigure(c_idx, weight=1, minsize=20)
btn.grid(
row=0, column=0,
rowspan=1, columnspan=1,
sticky="nsew"
)
lbl.grid(
row=0, column=1,
rowspan=1, columnspan=1,
sticky="nsew"
)
root.mainloop()
不要在tkinter程序中使用time.sleep。它阻止所有事件处理。在之后使用
。
在这种情况下,更改文本所需的事件和重置文本所生成的事件都会在time.sleep
完成后得到处理。所以你看不到任何效果
(未经测试的修复程序):
Ok将在不睡觉的情况下进行测试。实际用例有一些很长的处理过程,但面临标签文本更改的问题。否则,基本方法是否正确?因为tkinter mainloop被睡眠阻塞,所以在函数返回之前,标签不会更新。在\u label\u strVar.set(f“Processing button”)
之后添加root.update\u idletasks()
,以强制更新标签。然而,耗时的任务应该在一个线程中执行。这正是我所需要的!非常感谢。
def btn_is_clicked(btn, _label_strVar):
_label_strVar.set(f"Processing button")
btn.after(1000, _label_strVar.set, "Ready")