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

วิธีสร้าง Toggle Button ใน Tkinter


Python มีชุดไลบรารีและโมดูลอุดมสมบูรณ์สำหรับสร้างส่วนประกอบต่างๆ ของแอปพลิเคชัน Tkinter เป็นไลบรารี Python อีกตัวหนึ่งที่รู้จักกันดีสำหรับสร้างและพัฒนาแอปพลิเคชัน GUI มี widget ฟังก์ชัน และโมดูลมากมาย

ในแอปพลิเคชันนี้ จะสร้าง Toggle button ที่สลับโหมดกลางวัน/กลางคืนของแอปพลิเคชัน เพื่อสร้าง Toggle button ให้แสดงภาพใน Label ก่อน

กำหนดปุ่มและฟังก์ชันเพื่อเปลี่ยนสีพื้นหลังของหน้าต่าง เนื่องจากปุ่มต้องสลับซ้ำๆ จึงต้องประกาศตัวแปรสากล 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()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มี Toggle button

วิธีสร้าง Toggle Button ใน Tkinter

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

วิธีสร้าง Toggle Button ใน Tkinter