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

วิธีปรับขนาดข้อความปุ่ม (Button Text) แบบไดนามิกใน Tkinter

สมมติว่าเราสร้างปุ่มและ Label ใน Tkinter Frame ภารกิจคือให้ข้อความปุ่มปรับขนาดตัวอักษรตามหน้าต่างหลักได้แบบไดนามิก เราสามารถสร้างปุ่มโดยใช้ Button Widget อย่างไรก็ตาม มีฟังก์ชันอื่นๆ หลายตัวที่ใช้สร้างปุ่ม Label แบบไดนามิก

ในตัวอย่างนี้ เราจะสร้างปุ่ม 2 ปุ่มพร้อม Label ภายใน โดยใช้ Grid Method เช่น rowconfigure() และ columnconfigure() เราจะปรับขนาดหน้าต่างหลักหรือ Root แบบไดนามิก

เพื่อทำให้ข้อความปุ่มเป็นไดนามิก เราจะใช้เมธอด bind('', command) ซึ่งจะช่วยผูกฟังก์ชันและเมธอดเข้าด้วยกัน เราสามารถส่ง Callback Function ซึ่งโดยทั่วไปอ้างถึงตำแหน่งใหม่ของ Widget และ Helper Function ที่ปรับเปลี่ยนข้อความปุ่มตามขนาดหน้าต่าง

ก่อนอื่น เราจะปรับขนาดข้อความปุ่มตามความกว้าง แล้วค่อยตามความสูง

ตัวอย่าง

from tkinter import *

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

# Dynamically resize the window and its widget
Grid.rowconfigure(win, index=0, weight=1)
Grid.columnconfigure(win, index=0, weight=1)

# Define the function to change the size of the button text
def resize(e):
    # Get the width of the button
    w = e.width / 10
    # Dynamically Resize the Button Text
    b.config(font=("Times New Roman", int(w)))
    # Resize the height
    if e.height <= 300:
        b.config(font=("Times New Roman", 30))
    elif e.height < 100:
        b.config(font=("Times New Roman", 10))

# Let us Create buttons
b = Button(win, text="Python")
b.grid(row=0, column=0, sticky="nsew")

win.bind('', resize)

win.mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นจะสร้างปุ่มพร้อมข้อความ "Python" และปุ่มนี้สามารถปรับขนาดได้แบบไดนามิก

วิธีปรับขนาดข้อความปุ่ม (Button Text) แบบไดนามิกใน Tkinter