Python มีชุดไลบรารีและโมดูลมากมายที่สามารถใช้สร้างส่วนประกอบต่างๆ ของแอปพลิเคชันได้ Tkinter เป็นไลบรารี Python ที่รู้จักกันดีสำหรับการสร้างและพัฒนาแอปพลิเคชันที่ใช้ GUI Tkinter มีวิดเจ็ต ฟังก์ชัน และโมดูลมากมายที่ใช้เพื่อทำให้ภาพแอปพลิเคชันมีชีวิตชีวา เราสามารถสร้างวิดเจ็ตปุ่มเพื่อทำงานบางอย่างในแอปพลิเคชันได้
ในแอปพลิเคชันนี้ เราจะสร้างปุ่มสลับที่จะเปิด/ปิดโหมดกลางคืนและกลางวันของแอปพลิเคชัน ในการสร้างปุ่มสลับ เราต้องสร้างภาพในป้ายกำกับก่อน
เรากำหนดปุ่มและฟังก์ชันเพื่อเปลี่ยนสีพื้นหลังของหน้าต่าง เนื่องจากจำเป็นต้องเปลี่ยนปุ่มซ้ำๆ เราจึงต้องประกาศตัวแปรส่วนกลาง is_on=True ซึ่งช่วยในการควบคุมฟังก์ชัน
ตัวอย่าง
# Import tkinter in the notebook
from tkinter import *
# Create an instance of window of frame
win = Tk()
# set Title
win.title('Toggle Button Demonstration')
# Set the Geometry
win.geometry("700x400")
win.resizable(0, 0)
# Create a variable to turn on the button initially
is_on = True
# Create Label to display the message
label = Label(win, text="Night Mode is On", bg="white", fg="black", font=("Poppins bold", 22))
label.pack(pady=20)
# Define our switch function
def button_mode():
global is_on
# Determine it is on or off
if is_on:
on_.config(image=off)
label.config(text="Day Mode is On", bg="white", fg="black")
is_on = False
else:
on_.config(image=on)
label.config(text="Night Mode is On", fg="black")
is_on = True
# Define Our Images
on = PhotoImage(file="on.png")
off = PhotoImage(file="off.png")
# Create A Button
on_ = Button(win, image=on, bd=0, command=button_mode)
on_.pack(pady=50)
# Keep Running the window
win.mainloop() ผลลัพธ์
หากเรารันโค้ดข้างต้น จะแสดงหน้าต่างที่มีปุ่มสลับ

หากเราคลิกปุ่ม มันจะเปลี่ยนสีของหน้าต่าง
