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

วิธีดึงค่าของปุ่มมาแสดงใน Entry Widget ด้วย Tkinter


ปุ่มเป็น widget ที่มีประโยชน์มากในแอปพลิเคชัน Tkinter เราสามารถดึงค่าของปุ่มใดๆ มาแสดงใน Entry widget โดยกำหนดฟังก์ชันที่แทรกค่าลงใน Entry widget เพื่อดึงค่า ให้กำหนดปุ่มพร้อม command สำหรับเพิ่มค่าเฉพาะที่จะแสดงใน Entry widget

เพื่ออัปเดต Entry widget ให้ลบค่าเดิมด้วยเมธอด delete(0, END)

ตัวอย่าง

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")

def on_click(text):
    entry.delete(0, END)
    entry.insert(0, text)

# Add an Entry widget
entry=Entry(win, width=25)
entry.pack()

# Add Buttons in the window
b1=ttk.Button(win, text="A", command=lambda: on_click("A"))
b1.pack()
b2=ttk.Button(win, text="B", command=lambda: on_click("B"))
b2.pack()
b3=ttk.Button(win, text="C", command=lambda: on_click("C"))
b3.pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีปุ่มหลายปุ่ม เมื่อคลิกปุ่ม จะแสดงค่าของปุ่มในช่อง Entry

วิธีดึงค่าของปุ่มมาแสดงใน Entry Widget ด้วย Tkinter