Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thay đổi text Label Tkinter khi nhấn button

Widget Label thường dùng để hiển thị text/ảnh. Cấu hình thuộc tính text, color qua config(**options).

Để thay đổi text Label động, dùng button + function cập nhật label["text"].

Ví dụ

from tkinter import *

win = Tk()
win.geometry("700x350")

def on_click():
    label["text"] = "Python"
    b["state"] = "disabled"

label = Label(win, text="Click the Button to update this Text", font=('Calibri 15 bold'))
label.pack(pady=20)
b = Button(win, text="Update Label", command=on_click)
b.pack(pady=20)
win.mainloop()

Kết quả

Label ban đầu: "Click the Button to update this Text". Click button → Label: "Python", button disable.

Thay đổi text Label Tkinter khi nhấn button Thay đổi text Label Tkinter khi nhấn button

Cách khác: label.config(text="New text") hoặc label.configure(text="New text"). Tương đương label["text"] = "New text".