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

วิธีใส่รูปภาพและข้อความในปุ่ม (Button) เดียวกันใน Tkinter

ใน Tkinter สามารถโหลดรูปภาพด้วย PhotoImage() แต่หากใส่รูปในปุ่มโดยตรง ข้อความจะถูกบัง ดังนั้นจึงใช้คุณสมบัติ compound เพื่อกำหนดตำแหน่งรูปภาพเทียบกับข้อความ (LEFT, RIGHT, TOP, BOTTOM)

ตัวอย่างโค้ด

# Import tkinter library
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of Tkinter frame or window
win = Tk()

# Set the geometry of tkinter frame
win.geometry("750x250")

# Define a function to close the window
def close_win():
    win.destroy()

# Load the image
image = Image.open('preview.png')

# Resize the Image
image = image.resize((50, 50), Image.Resampling.LANCZOS)

# Convert the image to PhotoImage
img = ImageTk.PhotoImage(image)

# Create a Label
Label(win, text="Click the below button to close the window", font=('Aerial 15 bold')).pack(pady=20)

# Create a button with image and text
button = Button(win, text="Click Me", font=('Helvetica 15 bold'), image=img, compound=LEFT, command=close_win)
button.pack()

win.mainloop()

ผลลัพธ์

โค้ดจะแสดงปุ่มที่มีทั้งรูปภาพและข้อความ เมื่อคลิกจะปิดหน้าต่าง

วิธีใส่รูปภาพและข้อความในปุ่ม (Button) เดียวกันใน Tkinter