Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเปลี่ยนข้อความ Label ใน Tkinter เมื่อกดปุ่ม


Widget Label ใน Tkinter ใช้แสดงข้อความหรือภาพ เราสามารถตั้งค่า label widget เช่น text property, สี, พื้นหลัง ฯลฯ ด้วยเมธอด config(**options)

หากต้องการแก้ไข label widget แบบไดนามิก ให้ใช้ปุ่มและฟังก์ชันเพื่อเปลี่ยนข้อความของ label widget

ตัวอย่าง

# Import the required libraries 
from tkinter import * 
# Create an instance of tkinter frame or window 
win = Tk() 
# Set the size of the tkinter window 
win.geometry("700x350") 
# Define a function update the label text 
def on_click(): 
    label["text"] = "Python" 
    b["state"] = "disabled" 
# Create a label widget 
label = Label(win, text="Click the Button to update this Text", font=('Calibri 15 bold')) 
label.pack(pady=20) 
# Create a button to update the label widget 
b = Button(win, text="Update Label", command=on_click) 
b.pack(pady=20) 
win.mainloop()

ผลลัพธ์

เมื่อรันโค้ด จะแสดงข้อความ label และปุ่มในหน้าต่าง

วิธีเปลี่ยนข้อความ Label ใน Tkinter เมื่อกดปุ่ม

เมื่อคลิกปุ่ม จะอัปเดตข้อความ label

วิธีเปลี่ยนข้อความ Label ใน Tkinter เมื่อกดปุ่ม